From 8579aa07e36b8ba1a8290462ec8f1c398498d3f2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 02:08:52 -0700 Subject: [PATCH 001/260] Shortcuts: in the web build a key-position shortcut uses the key of the same press eframe's web build sends a keystroke's text before its key press. On a layout without Latin letters, the one-key shortcuts paired each text with the last key press before it, so in the web build a lone keystroke had no key and ran no shortcut, and a second keystroke in the same frame used the first one's key. Each text now takes the press right before it, unless an earlier text in the frame took that press, and otherwise the press right after it. The one-key shortcuts and the shortcut names a tool sees while it is busy use the same pairing. The desktop order (key, then text) pairs as before. --- crates/ui-egui/src/shortcuts.rs | 48 ++++++++++++++++++++------- crates/ui-egui/src/shortcuts/tests.rs | 25 ++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 62 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index bb0cb06e09..086b32bd58 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -358,15 +358,18 @@ fn single_key_shortcuts(app: &mut VectorcraftApp, ctx: &egui::Context) { // Single-key tool shortcuts (no Cmd/Ctrl/Alt). With a layout without Latin letters (Persian, // Arabic, Russian, Greek…) the key's position stands in for what it types (#793). let events: Vec<(String, Modifiers)> = ctx.input(|i| { - let mut physical = None; + let typed_by = typing_presses(&i.events); i.events .iter() - .filter_map(|e| match e { - egui::Event::Key { physical_key, pressed: true, .. } => { - physical = *physical_key; - None + .zip(typed_by) + .filter_map(|(e, by)| match e { + egui::Event::Text(t) => { + let physical = match by.and_then(|k| i.events.get(k)) { + Some(egui::Event::Key { physical_key, .. }) => *physical_key, + _ => None, + }; + Some((latin(t, physical), i.modifiers)) } - egui::Event::Text(t) => Some((latin(t, physical), i.modifiers)), _ => None, }) .collect() @@ -843,18 +846,39 @@ fn latin(text: &str, physical: Option) -> String { } } +/// For each event, the index of the key press that typed it when it is text: the press right +/// before it (egui-winit) unless an earlier text took that press, or else the press right after it +/// (eframe's web build with no text field focused). Each press types at most one text. +fn typing_presses(events: &[egui::Event]) -> Vec> { + let is_press = |k: usize| matches!(events.get(k), Some(egui::Event::Key { pressed: true, .. })); + let mut taken = None; + events + .iter() + .enumerate() + .map(|(j, e)| { + if !matches!(e, egui::Event::Text(_)) { + return None; + } + let before = j.checked_sub(1).filter(|&k| is_press(k) && taken != Some(k)); + let by = before.or_else(|| Some(j + 1).filter(|&k| is_press(k))); + taken = by.or(taken); + by + }) + .collect() +} + /// Each new press's shortcut names, first match first, and the letter it types, without Cmd, Ctrl /// or Alt. A text-only press counts as well (Shift+~ arrives as the text `~` with Shift), unless -/// the key that typed it repeated. A text's key is the press right before it (egui-winit) or, -/// failing that, right after it (eframe's web build with no text field focused). Text reads its -/// key's modifiers, or the latest modifier change (`held` before any), and tries its key's own -/// name first. +/// the key that typed it repeated. A text's key is the one `typing_presses` pairs it with. Text +/// reads its key's modifiers, or the latest modifier change (`held` before any), and tries its +/// key's own name first. fn shortcut_presses(events: &[egui::Event], held: Modifiers) -> Vec<(Vec, Option)> { let key_name = |key: &Key, m: &Modifiers| if m.shift { format!("Shift+{}", key.name()) } else { key.name().to_string() }; let press_at = |j: Option| match j.and_then(|j| events.get(j)) { Some(egui::Event::Key { key, pressed: true, repeat, modifiers, .. }) => Some((*repeat, *modifiers, key_name(key, modifiers))), _ => None, }; + let typed_by = typing_presses(events); let mut latest = held; events .iter() @@ -868,8 +892,8 @@ fn shortcut_presses(events: &[egui::Event], held: Modifiers) -> Vec<(Vec Some((vec![key_name(key, modifiers)], letter_of(*key))) } egui::Event::Text(t) => { - let typed_by = press_at(j.checked_sub(1)).or_else(|| press_at(Some(j + 1))); - let (repeated, mods, key_name) = typed_by.map_or((false, latest, None), |(r, m, n)| (r, m, Some(n))); + let (repeated, mods, key_name) = + press_at(typed_by.get(j).copied().flatten()).map_or((false, latest, None), |(r, m, n)| (r, m, Some(n))); if repeated || mods.command || mods.alt || mods.ctrl { return None; } diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 553c57df4a..49c41536e6 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1470,6 +1470,31 @@ fn one_key_shortcuts_follow_the_key_on_layouts_without_latin_letters() { assert_eq!(app.session.tool_id(), "directSelection", "AZERTY: the letter typed"); } +/// The web build sends a keystroke's text before its key press: the one-key shortcut on a layout +/// without Latin letters still goes by the key of the same keystroke, and two keystrokes in one +/// frame each use their own key, in either order. +#[test] +fn one_key_shortcuts_use_the_key_of_the_same_keystroke_in_either_order() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let press = |key| egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: Modifiers::NONE }; + let text = |t: &str| egui::Event::Text(t.into()); + frame(&mut app, vec![text("з"), press(Key::P)]); + assert_eq!(app.session.tool_id(), "pen", "text before its key"); + frame(&mut app, vec![text("м"), press(Key::V), text("з"), press(Key::P)]); + assert_eq!(app.session.tool_id(), "pen", "the second text uses the second key"); + app.select_tool("pen"); + frame(&mut app, vec![press(Key::P), text("з"), press(Key::V), text("м")]); + assert_eq!(app.session.tool_id(), "selection", "key before its text"); + let names = |events: &[egui::Event]| -> Vec { + shortcut_presses(events, Modifiers::NONE).into_iter().filter_map(|(n, _)| n.into_iter().next()).collect() + }; + let web = names(&[text("м"), press(Key::V), text("з"), press(Key::P)]); + assert_eq!(web, ["V", "V", "P", "P"], "each text tries its own key's name first"); + let desktop = names(&[press(Key::V), text("м"), press(Key::P), text("з")]); + assert_eq!(desktop, ["V", "V", "P", "P"]); +} + #[test] fn plus_typed_any_way_zooms_in() { assert_eq!(parse("Cmd++"), parse("Cmd+="), "`+` and `=` are one chord key"); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index aef1c3790d..a4207f302d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -617,6 +617,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The function key shortcuts for Brushes, Color, Layers, Info, Gradient, Stroke, Attributes, Graphic Styles, Appearance, Align, Transform, Pathfinder, Transparency, and Symbols activate a background tab on the first press, hide its expanded dock or floating group when that tab is in front, and restore the group with all its tabs together on the next press; in an icon column they open and close the flyout while keeping the icons. A reassigned chord keeps that behavior, and Window > a hidden sibling restores the group. - Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). Not yet: Select All across threaded frames (one frame's text is selected). - While the Type tool edits text, a character typed with AltGr is typed and runs no command. Firefox on Windows reports AltGr as Ctrl and Alt held, so in the web build AltGr+L (ł on a Polish layout) does not also open Layer Options for a new layer, and AltGr+Q (@ on a German layout) does not also run Reset Tracking and Kerning. A Ctrl+Alt chord that types no character runs its command. + - On a layout without Latin letters, a one-key shortcut goes by the position of the key that typed the character, in the web build too, where the character arrives before its key press: on a Russian layout the P key (`з`) chooses the Pen, and two keys pressed in one frame each run their own shortcut. - With the Artboard tool, Cmd/Ctrl+A after a click on a row of the Artboards panel selects every artboard, as the macOS menu bar's Select All does then; the active artboard stays active, and the art's selection does not change. After a press outside the panel's list, Cmd/Ctrl+A selects every object again. It used to select every object after a click in the panel too. Public reference: [Select artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/select-artboards.html). - Cmd/Ctrl+/ (`appearance.addFill`) and Cmd/Ctrl+Alt+/ (`appearance.addStroke`) add a new fill and a new stroke to the selected objects, as the Appearance panel's Add New Fill and Add New Stroke buttons do, on the keys the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for adding a new fill and a new stroke. Keyboard Shortcuts lists both under Window › Appearance. - Cmd/Ctrl+Alt+Shift+. and , (`type.size.increaseByFive`, `type.size.decreaseByFive`) step the font size of the selected type, or of the text the Type tool has selected, by five times the Size/Leading increment (Preferences › Type); Cmd/Ctrl+Shift+. and , still step it by one increment. From 012773959762773fb96a4120fd6937e02d0c43da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 02:33:38 -0700 Subject: [PATCH 002/260] Shortcuts: a text with no key press of its own leaves the next keystroke's press to that keystroke's text A text-only event right before a desktop keystroke in the same frame ([text, key, text]) took the key press as the press after it, which left the keystroke's own text with no key. A text now takes the press after it only when every later text in the same run of alternating texts and presses has a press after it too, as in the web build's [text, key] order; otherwise the press goes to the text after it. --- crates/ui-egui/src/shortcuts.rs | 19 +++++++++++++++++-- crates/ui-egui/src/shortcuts/tests.rs | 5 +++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 086b32bd58..39fbc2a2c8 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -848,9 +848,24 @@ fn latin(text: &str, physical: Option) -> String { /// For each event, the index of the key press that typed it when it is text: the press right /// before it (egui-winit) unless an earlier text took that press, or else the press right after it -/// (eframe's web build with no text field focused). Each press types at most one text. +/// (eframe's web build with no text field focused). Each press types at most one text. A text +/// takes the press after it only when every later text in the same run of alternating texts and +/// presses has a press after it too; otherwise the text after that press takes it as the press +/// before it, and this text has none. fn typing_presses(events: &[egui::Event]) -> Vec> { let is_press = |k: usize| matches!(events.get(k), Some(egui::Event::Key { pressed: true, .. })); + let is_text = |k: usize| matches!(events.get(k), Some(egui::Event::Text(_))); + // Whether the run of alternating texts and presses that starts with the text at `j` ends + // with a press. + let ends_with_press = |mut j: usize| loop { + if !is_press(j + 1) { + break false; + } + if !is_text(j + 2) { + break true; + } + j += 2; + }; let mut taken = None; events .iter() @@ -860,7 +875,7 @@ fn typing_presses(events: &[egui::Event]) -> Vec> { return None; } let before = j.checked_sub(1).filter(|&k| is_press(k) && taken != Some(k)); - let by = before.or_else(|| Some(j + 1).filter(|&k| is_press(k))); + let by = before.or_else(|| ends_with_press(j).then_some(j + 1)); taken = by.or(taken); by }) diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 49c41536e6..e07c31a74e 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1486,6 +1486,11 @@ fn one_key_shortcuts_use_the_key_of_the_same_keystroke_in_either_order() { app.select_tool("pen"); frame(&mut app, vec![press(Key::P), text("з"), press(Key::V), text("м")]); assert_eq!(app.session.tool_id(), "selection", "key before its text"); + // A text with no key press of its own right before a desktop keystroke leaves that press to + // the keystroke's text. + assert_eq!(typing_presses(&[text("p"), press(Key::V), text("м")]), [None, None, Some(1)]); + frame(&mut app, vec![text("p"), press(Key::V), text("м")]); + assert_eq!(app.session.tool_id(), "selection", "the text after the key uses it"); let names = |events: &[egui::Event]| -> Vec { shortcut_presses(events, Modifiers::NONE).into_iter().filter_map(|(n, _)| n.into_iter().next()).collect() }; From d3ea958f8f8240fb42f5d3030809d7328f9b4a6c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 02:47:09 -0700 Subject: [PATCH 003/260] Shortcuts: a modifier key press is never the key that typed a text In the web build, pressing Shift and then a letter in one frame sends the Shift press, the letter's text and then the letter's key press. The text paired with the Shift press as the press before it, so a key-position shortcut looked up Shift instead of the letter, and a held Shift's repeated presses dropped the text as a repeat. Modifier key presses now never pair with a text. --- crates/ui-egui/src/shortcuts.rs | 5 +++-- crates/ui-egui/src/shortcuts/tests.rs | 2 ++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 39fbc2a2c8..435758b85d 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -848,12 +848,13 @@ fn latin(text: &str, physical: Option) -> String { /// For each event, the index of the key press that typed it when it is text: the press right /// before it (egui-winit) unless an earlier text took that press, or else the press right after it -/// (eframe's web build with no text field focused). Each press types at most one text. A text +/// (eframe's web build with no text field focused). Modifier key presses type no text. Each press +/// types at most one text. A text /// takes the press after it only when every later text in the same run of alternating texts and /// presses has a press after it too; otherwise the text after that press takes it as the press /// before it, and this text has none. fn typing_presses(events: &[egui::Event]) -> Vec> { - let is_press = |k: usize| matches!(events.get(k), Some(egui::Event::Key { pressed: true, .. })); + let is_press = |k: usize| matches!(events.get(k), Some(egui::Event::Key { key, pressed: true, .. }) if !is_modifier(*key)); let is_text = |k: usize| matches!(events.get(k), Some(egui::Event::Text(_))); // Whether the run of alternating texts and presses that starts with the text at `j` ends // with a press. diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index e07c31a74e..6bce0cc6fb 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1491,6 +1491,8 @@ fn one_key_shortcuts_use_the_key_of_the_same_keystroke_in_either_order() { assert_eq!(typing_presses(&[text("p"), press(Key::V), text("м")]), [None, None, Some(1)]); frame(&mut app, vec![text("p"), press(Key::V), text("м")]); assert_eq!(app.session.tool_id(), "selection", "the text after the key uses it"); + // A modifier key press does not type text, so the web text after Shift uses the key after it. + assert_eq!(typing_presses(&[press(Key::ShiftLeft), text("З"), press(Key::P)]), [None, Some(2), None]); let names = |events: &[egui::Event]| -> Vec { shortcut_presses(events, Modifiers::NONE).into_iter().filter_map(|(n, _)| n.into_iter().next()).collect() }; From 2d9ceb8137b96a434908bfd0b51f131eb3ef7243 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 02:51:09 -0700 Subject: [PATCH 004/260] Shortcuts: rewrap the typing_presses doc comment --- crates/ui-egui/src/shortcuts.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 435758b85d..504e84b2d7 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -849,10 +849,9 @@ fn latin(text: &str, physical: Option) -> String { /// For each event, the index of the key press that typed it when it is text: the press right /// before it (egui-winit) unless an earlier text took that press, or else the press right after it /// (eframe's web build with no text field focused). Modifier key presses type no text. Each press -/// types at most one text. A text -/// takes the press after it only when every later text in the same run of alternating texts and -/// presses has a press after it too; otherwise the text after that press takes it as the press -/// before it, and this text has none. +/// types at most one text. A text takes the press after it only when every later text in the same +/// run of alternating texts and presses has a press after it too; otherwise the text after that +/// press takes it as the press before it, and this text has none. fn typing_presses(events: &[egui::Event]) -> Vec> { let is_press = |k: usize| matches!(events.get(k), Some(egui::Event::Key { key, pressed: true, .. }) if !is_modifier(*key)); let is_text = |k: usize| matches!(events.get(k), Some(egui::Event::Text(_))); From 663e691908ad6bf8c4c825a45db0637a755ed27e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 02:35:20 -0700 Subject: [PATCH 005/260] Fix #4864: a search pick of an Asset Export command opens the panel The command palette runs a picked command with no params. Export Assets then failed with "no assets yet" (or, with assets collected, exported to no folder), and Remove, Rename and Asset Export Settings failed or did nothing. Run with no params from the palette, a menu or a shortcut, these four commands now show the Asset Export panel, and leave it open when it already shows, docked or floating. Calls with params are unchanged. --- crates/ui-egui/src/menus/invoke.rs | 13 +++++++++++-- crates/ui-egui/src/palette.rs | 25 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 75f7462c7e..382c730aa1 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -256,8 +256,8 @@ fn open_view_dialog(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool { false } -/// The dialogs the selection, raster, wrap, blend and Expand commands open when called without params; whether `id` -/// was one of them. +/// The dialogs the selection, raster, wrap, blend and Expand commands open, and the panel the Asset Export commands +/// open, when called without params; whether `id` was one of them. fn open_object_dialog(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool { // Save Selection…: a name dialog, starting from the first free "Selection N". if id == "select.save" && p.as_object().is_none_or(|o| o.is_empty()) { @@ -315,5 +315,14 @@ fn open_object_dialog(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool { } return true; } + // Export Assets, Remove, Rename and Asset Export Settings with no params, as the command + // palette runs them (#4864): the Asset Export panel, where each one is done. A panel that already + // shows stays open. + if matches!(id, "assets.export" | "assets.remove" | "assets.rename" | "assets.settings.set") && p.as_object().is_none_or(|o| o.is_empty()) { + if let Err(e) = crate::panel_docking::reveal_panel(app, crate::panels::asset_export::ID) { + app.status(e); + } + return true; + } false } diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index a6cc61e230..f7728f4c33 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -199,6 +199,31 @@ mod tests { assert_eq!((st.selection.len(), st.selection.key), (2, None), "both objects stay selected, without a key"); } + /// #4864: a pick of an Asset Export command, which the palette runs with no params, opens the + /// Asset Export panel instead of failing on the missing params or exporting nowhere. + #[test] + fn a_pick_of_an_asset_export_command_opens_its_panel() { + let ids = ["assets.export", "assets.remove", "assets.rename", "assets.settings.set"]; + for id in ids { + assert!(items().iter().any(|(_, item, _)| item == id), "{id} is in the palette"); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.ui.status.clear(); + assert!(!crate::panel_docking::showing(&app.ui, crate::panels::asset_export::ID), "{id}"); + // Run a pick the way `show` runs it. + menus::invoke(&mut app, id, json!({})); + assert!(crate::panel_docking::showing(&app.ui, crate::panels::asset_export::ID), "{id}: {}", app.ui.status); + assert!(!app.ui.status.contains("invalid parameters"), "{id}: {}", app.ui.status); + // A second pick leaves the open panel open, docked or floating. + menus::invoke(&mut app, id, json!({})); + assert!(crate::panel_docking::showing(&app.ui, crate::panels::asset_export::ID), "{id}: picked twice"); + app.run("window.panel.float", json!({"panel": crate::panels::asset_export::ID})).unwrap(); + assert!(crate::panel_docking::showing(&app.ui, crate::panels::asset_export::ID), "{id}: floating"); + menus::invoke(&mut app, id, json!({})); + assert!(crate::panel_docking::showing(&app.ui, crate::panels::asset_export::ID), "{id}: floating, picked again"); + } + } + /// #1757: Up and Down move the highlighted result, wrapping at the ends; a new query starts /// from the first again. #[test] From 4e785b40ce1d07fabb4ba06646d43ce11e5a2710 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 03:12:49 -0700 Subject: [PATCH 006/260] Part of #4516: Windows renders start workers only for the cores the process may use The renderer sized its worker pool from available_parallelism, which on Windows counts every processor in the machine, also when the process's affinity mask allows fewer. A process allowed one core started 8 workers, and the renderer's flush spun on that core while the workers got no time, so renders crawled or stalled. The desktop app and vectorcraft-cli now read the affinity mask at startup (src/windows_cores.rs, shared) and pass the count to the renderer with vectorcraft_render::set_usable_cores. With one usable core the renderer renders on the calling thread. --- Cargo.lock | 1 + apps/vectorcraft-cli/Cargo.toml | 5 ++- apps/vectorcraft-cli/src/main.rs | 7 ++++ apps/vectorcraft/Cargo.toml | 6 ++- apps/vectorcraft/src/main.rs | 5 +++ apps/vectorcraft/src/windows_cores.rs | 59 +++++++++++++++++++++++++++ crates/render/src/lib.rs | 2 +- crates/render/src/threads.rs | 44 ++++++++++++++++++-- 8 files changed, 121 insertions(+), 8 deletions(-) create mode 100644 apps/vectorcraft/src/windows_cores.rs diff --git a/Cargo.lock b/Cargo.lock index 62f084afc5..ff1d18be21 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6065,6 +6065,7 @@ dependencies = [ "smithay-clipboard", "socket2", "vectorcraft-engine", + "vectorcraft-render", "vectorcraft-text", "vectorcraft-ui-egui", "wayland-backend", diff --git a/apps/vectorcraft-cli/Cargo.toml b/apps/vectorcraft-cli/Cargo.toml index cb9183315f..8f39e3b58d 100644 --- a/apps/vectorcraft-cli/Cargo.toml +++ b/apps/vectorcraft-cli/Cargo.toml @@ -34,8 +34,9 @@ winsafe = { version = "0.0.29", default-features = false, features = ["kernel", # DirectWrite's system font collection and GDI's font list (the desktop app's src/system_fonts.rs, # shared): fonts that font services such as Adobe Fonts load in place (#579, #1258). MIT OR -# Apache-2.0. -windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi"] } +# Apache-2.0. Win32_System_Threading has `GetProcessAffinityMask`, which the desktop app's +# src/windows_cores.rs, shared, uses to count the cores the process may run on. +windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Threading"] } # CoreText's font manager (the desktop app's src/mac_fonts.rs, shared): fonts that apps and font # managers register from their own folders (#579). Zlib OR Apache-2.0 OR MIT. diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index bba1976c1d..b7334586ca 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -49,6 +49,10 @@ mod prefs_dir; #[cfg(windows)] #[path = "../../vectorcraft/src/system_fonts.rs"] mod system_fonts; +/// The desktop app's affinity-mask reader, shared: renders start workers only for usable cores. +#[cfg(windows)] +#[path = "../../vectorcraft/src/windows_cores.rs"] +mod windows_cores; use serde_json::{Value, json}; use vectorcraft_engine::file_access::{self, AutomationRoots}; @@ -161,6 +165,9 @@ fn help() -> Result<(), String> { } fn main() -> ExitCode { + // Before the first render: the cores the process may run on. + #[cfg(windows)] + windows_cores::install(); // Before any font lookup: the fonts font services load (#579). #[cfg(windows)] system_fonts::install(); diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 0657c93c8a..7af8c51eff 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -54,7 +54,11 @@ pollster = "1" # Win32_UI_WindowsAndMessaging has `MSG` and `WM_POINTERDOWN`, which src/windows_stylus.rs uses to # read a pen's barrel button from its pointer messages. Win32_UI_Input_Pointer has # `GetPointerPenInfo`, which it uses to read the pen's pressure and which end of the pen is down. -windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] } +# Win32_System_Threading has `GetProcessAffinityMask`, which src/windows_cores.rs uses to count the +# cores the process may run on. +windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Threading", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] } +# The renderer's worker count follows those cores (src/windows_cores.rs). +vectorcraft-render = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] # The macOS menu bar (src/mac_menu.rs): Tauri's menu crate, AppKit menus behind a safe API (no GTK diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index e90977726d..1e2ab4fae6 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -50,6 +50,8 @@ mod system_fonts; mod tablet; mod window; mod window_frame; +#[cfg(windows)] +mod windows_cores; mod windows_stylus; mod xwayland; @@ -184,6 +186,9 @@ fn main() -> std::process::ExitCode { // Before desktop services, so every start-up warning is recorded (`logging`). let logger = logging::install(); vectorcraft_ui_egui::i18n::detect_system_lang_in_background(); + // Before the first render: the cores the process may run on. + #[cfg(windows)] + windows_cores::install(); // Before the first font scan (the app's start): the fonts font services load (#579). #[cfg(windows)] system_fonts::install(); diff --git a/apps/vectorcraft/src/windows_cores.rs b/apps/vectorcraft/src/windows_cores.rs new file mode 100644 index 0000000000..97d040550c --- /dev/null +++ b/apps/vectorcraft/src/windows_cores.rs @@ -0,0 +1,59 @@ +//! Windows: the cores the process may run on, from its affinity mask, for the renderer's worker +//! count (`vectorcraft_render::set_usable_cores`). `available_parallelism` counts every processor +//! in the machine, also when the process may run on fewer (started with `start /affinity`, or +//! pinned by a launcher). The desktop app and `vectorcraft-cli` (exports, MCP) both install it; the +//! CLI shares this file. +//! +//! `GetProcessAffinityMask` is a C API with no safe binding, hence the scoped `unsafe_code` +//! allowance. +#![allow(unsafe_code)] + +use windows::Win32::System::Threading::{GetCurrentProcess, GetProcessAffinityMask}; + +/// Tells the renderer how many cores the process may run on. +pub fn install() { + vectorcraft_render::set_usable_cores(usable_cores()); +} + +/// The number of cores in the process's affinity mask, or `None` when Windows reports none (a +/// process with threads in more than one processor group). +fn usable_cores() -> Option { + let (mut process, mut system) = (0usize, 0usize); + // SAFETY: `GetCurrentProcess` returns a pseudo-handle that needs no closing, and both pointers + // point at live `usize`s for the length of the call. + unsafe { GetProcessAffinityMask(GetCurrentProcess(), &mut process, &mut system) }.ok()?; + (process != 0).then(|| process.count_ones() as usize) +} + +#[cfg(test)] +mod tests { + /// A process that may run on one core renders on the calling thread. With workers, the + /// renderer's flush spins on that core while the workers it waits for get no time, and a render + /// crawls or stalls. + #[test] + fn a_process_limited_to_one_core_starts_no_render_workers() { + const CHILD: &str = "VECTORCRAFT_TEST_ONE_CORE"; + const NAME: &str = "windows_cores::tests::a_process_limited_to_one_core_starts_no_render_workers"; + if std::env::var_os(CHILD).is_some() { + assert_eq!(super::usable_cores(), Some(1)); + super::install(); + assert_eq!(vectorcraft_render::default_threads(), 0); + return; + } + // `start /affinity 1` runs this test again in a process allowed only the first core. + use std::os::windows::process::CommandExt; + let exe = std::env::current_exe().unwrap(); + let output = std::process::Command::new("cmd") + .raw_arg(format!("/C start \"\" /affinity 1 /wait /b \"{}\" --exact {NAME} --nocapture", exe.display())) + .env(CHILD, "1") + .env_remove("VECTORCRAFT_RENDER_THREADS") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "one-core test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index d5c601dc13..8bf6b0d232 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -227,6 +227,6 @@ pub(crate) use text_geom::is_opentype_alternate; #[cfg(test)] use text_geom::text_geom; pub(crate) use threads::single_threaded_context; -pub use threads::{default_threads, set_default_threads}; +pub use threads::{default_threads, set_default_threads, set_usable_cores}; #[cfg(test)] mod tests; diff --git a/crates/render/src/threads.rs b/crates/render/src/threads.rs index eb1fb66eae..dfd6bf757d 100644 --- a/crates/render/src/threads.rs +++ b/crates/render/src/threads.rs @@ -9,14 +9,25 @@ pub(crate) fn single_threaded_context(w: u16, h: u16) -> RenderContext { /// Preferred rasterizer thread count set by the app (Preferences → Performance); negative = automatic. static THREADS_OVERRIDE: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(-1); +/// The cores the process may run on, as the app read them from the system; 0 = not known. +static USABLE_CORES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + /// Override the worker-thread count used by renderers created from now on (`None` = automatic). pub fn set_default_threads(n: Option) { THREADS_OVERRIDE.store(n.map_or(-1, i32::from), std::sync::atomic::Ordering::Relaxed); } -/// Rasterizer worker threads: 0 on wasm; otherwise one per core up to 8, leaving a core free. On a -/// 10-core machine 8 workers render a 50,000-path page 1.4× faster than 4 (9 are slower again); -/// the pixels don't depend on the count (`pixels_do_not_depend_on_the_thread_count`). +/// The number of cores the process may run on, when the app knows a smaller number than +/// `available_parallelism` gives (`None` = not known). On Windows `available_parallelism` counts +/// every processor in the machine, also when the process's affinity mask allows fewer. +pub fn set_usable_cores(n: Option) { + USABLE_CORES.store(n.unwrap_or(0), std::sync::atomic::Ordering::Relaxed); +} + +/// Rasterizer worker threads: 0 on wasm; otherwise one per core the process may run on, up to 8, +/// leaving a core free. On a 10-core machine 8 workers render a 50,000-path page 1.4× faster than 4 +/// (9 are slower again); the pixels don't depend on the count +/// (`pixels_do_not_depend_on_the_thread_count`). pub fn default_threads() -> u16 { #[cfg(target_arch = "wasm32")] { @@ -31,6 +42,31 @@ pub fn default_threads() -> u16 { if std::env::var_os("VECTORCRAFT_RENDER_THREADS").is_some() { return std::env::var("VECTORCRAFT_RENDER_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(0); } - std::thread::available_parallelism().map(|n| (n.get().saturating_sub(1)).min(8) as u16).unwrap_or(0) + let usable = USABLE_CORES.load(std::sync::atomic::Ordering::Relaxed); + std::thread::available_parallelism().map(|n| automatic_threads(n.get(), usable)).unwrap_or(0) + } +} + +/// [`default_threads`] when automatic, on `cpus` processors of which the process may use `usable` +/// (0 = all). +fn automatic_threads(cpus: usize, usable: usize) -> u16 { + let cores = if usable == 0 { cpus } else { cpus.min(usable) }; + (cores.saturating_sub(1)).min(8) as u16 +} + +#[cfg(test)] +mod tests { + use super::automatic_threads; + + /// A process that may run on one core renders on the calling thread. With workers, vello_cpu's + /// flush spins on that core while the workers it waits for get no time, and a render crawls or + /// stalls. + #[test] + fn workers_follow_the_cores_the_process_may_use() { + assert_eq!(automatic_threads(24, 0), 8); + assert_eq!(automatic_threads(24, 1), 0); + assert_eq!(automatic_threads(24, 4), 3); + assert_eq!(automatic_threads(4, 16), 3); + assert_eq!(automatic_threads(1, 0), 0); } } From da9eaaacf8c9742b2cd07badd95c7c77d335a297 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 31 Oct 2026 19:43:13 +0700 Subject: [PATCH 007/260] Windows cores: test the affinity mask in-process A test that spawned the test binary with `start /affinity 1` ran while the control server's socket tests held connections; the child inherited them and reset one (idle_expiry_closes_without_writing_a_line failed every full run). The one-core worker count stays covered by `automatic_threads`. --- apps/vectorcraft/src/windows_cores.rs | 35 ++++++--------------------- 1 file changed, 8 insertions(+), 27 deletions(-) diff --git a/apps/vectorcraft/src/windows_cores.rs b/apps/vectorcraft/src/windows_cores.rs index 97d040550c..b35c0876cf 100644 --- a/apps/vectorcraft/src/windows_cores.rs +++ b/apps/vectorcraft/src/windows_cores.rs @@ -27,33 +27,14 @@ fn usable_cores() -> Option { #[cfg(test)] mod tests { - /// A process that may run on one core renders on the calling thread. With workers, the - /// renderer's flush spins on that core while the workers it waits for get no time, and a render - /// crawls or stalls. + /// The mask Windows reports for this process gives at least one core and no more than the + /// machine has. (A child process started with `start /affinity` would test a one-core mask + /// end to end, but a process spawned while other tests hold sockets inherits them and resets + /// their connections; `automatic_threads` covers the one-core count.) #[test] - fn a_process_limited_to_one_core_starts_no_render_workers() { - const CHILD: &str = "VECTORCRAFT_TEST_ONE_CORE"; - const NAME: &str = "windows_cores::tests::a_process_limited_to_one_core_starts_no_render_workers"; - if std::env::var_os(CHILD).is_some() { - assert_eq!(super::usable_cores(), Some(1)); - super::install(); - assert_eq!(vectorcraft_render::default_threads(), 0); - return; - } - // `start /affinity 1` runs this test again in a process allowed only the first core. - use std::os::windows::process::CommandExt; - let exe = std::env::current_exe().unwrap(); - let output = std::process::Command::new("cmd") - .raw_arg(format!("/C start \"\" /affinity 1 /wait /b \"{}\" --exact {NAME} --nocapture", exe.display())) - .env(CHILD, "1") - .env_remove("VECTORCRAFT_RENDER_THREADS") - .output() - .unwrap(); - let stdout = String::from_utf8_lossy(&output.stdout); - assert!( - output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), - "one-core test failed:\n{stdout}\n{}", - String::from_utf8_lossy(&output.stderr), - ); + fn the_affinity_mask_gives_the_cores_the_process_may_use() { + let cores = super::usable_cores().unwrap(); + let all = std::thread::available_parallelism().unwrap().get(); + assert!((1..=all).contains(&cores), "{cores} of {all}"); } } From 9163c22396c003d48f9c306ffe7cdeeaf2582065 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 00:54:56 -0700 Subject: [PATCH 008/260] Fix #4819: Convert to Smooth and Corner convert a selected blend's spine With a blend selected, the Contextual Task Bar's Corner and Smooth buttons failed with "select paths or anchor points", since `path.convertAnchors` only read paths. They now convert every point of the blend's spine, as they convert every anchor of a path selected whole, in one undo step. The key objects stay where they are. With Direct Selection, the Control bar and the Properties panel now show their Convert buttons for a selected blend too. --- crates/engine/src/cmd/path.rs | 26 +++++++++++++++++++-- crates/engine/src/tests/blendspine.rs | 29 ++++++++++++++++++++++++ crates/ui-egui/src/chrome/control_bar.rs | 9 ++++---- crates/ui-egui/src/chrome/tests.rs | 17 ++++++++++++++ 4 files changed, 75 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 5450f3d3c4..3503ed14f5 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -112,7 +112,7 @@ pub fn specs() -> Vec { "Convert Anchor Points", [], None, - "{to: \"corner\"|\"smooth\"} convert the direct-selected anchors (all anchors of fully selected paths) as one undo step: corner retracts both handles, smooth pulls handles in line with the neighbours (smooth anchors keep theirs)", + "{to: \"corner\"|\"smooth\"} convert the direct-selected anchors (all anchors of fully selected paths, every point of a selected blend's spine) as one undo step: corner retracts both handles, smooth pulls handles in line with the neighbours (smooth anchors keep theirs)", has_selection, convert_anchors ), @@ -1123,7 +1123,11 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result { _ => return Err(bad(C, "`to` must be \"corner\" or \"smooth\"")), }; let t = anchor_targets(s)?; - if t.is_empty() { + // A selected blend converts every point of its spine, as a path selected whole does. + let st = s.doc()?; + let blends: Vec = + st.selection.objects.iter().copied().filter(|id| st.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Blend { .. }))).collect(); + if t.is_empty() && blends.is_empty() { return Err(bad(C, "select paths or anchor points")); } s.edit("Convert Anchor Points", |d, _| { @@ -1138,6 +1142,24 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result { } } } + for id in &blends { + let Some(NodeKind::Blend { children, spec }) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; + let Some((mut path, anchors)) = vectorcraft_doc::live::pin_spine(children, spec) else { continue }; + let pinned = path.clone(); + let Some(sp) = path.subpaths.first_mut() else { continue }; + for ai in 0..sp.anchors.len() { + if smooth { + sp.smooth_anchor(ai); + } else if let Some(a) = sp.anchors.get_mut(ai) { + a.retract(); + } + } + // A spine the conversion leaves as it was stays as the blend has it. + if path != pinned { + spec.key_anchors = anchors.iter().map(|a| u32::try_from(*a).unwrap_or(u32::MAX)).collect(); + spec.spine = Some(path); + } + } Ok(()) })?; ok() diff --git a/crates/engine/src/tests/blendspine.rs b/crates/engine/src/tests/blendspine.rs index 78e9335ac3..0ab2aac5b6 100644 --- a/crates/engine/src/tests/blendspine.rs +++ b/crates/engine/src/tests/blendspine.rs @@ -115,6 +115,35 @@ fn spine_conversion_rejects_invalid_arguments_without_mutation() { } } +/// #4819: Convert Selected Anchor Points to Smooth or Corner (the Control bar's and the Contextual +/// Task Bar's buttons) converts the points of a selected blend's spine, as it converts every +/// anchor of a path selected whole, in one undo step, the keys staying put. +#[test] +fn converting_anchors_of_a_selected_blend_converts_its_spine() { + let mut s = session(); + let (a, b, g) = blend(&mut s); + s.execute("object.blend.spine.addAnchor", &json!({"id": g.0, "x": 55, "y": 5})).unwrap(); + s.execute("object.blend.spine.moveAnchor", &json!({"id": g.0, "anchor": 1, "x": 55, "y": 105})).unwrap(); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let keys = spec(&s, g).key_anchors; + s.execute("path.convertAnchors", &json!({"to": "smooth"})).unwrap(); + let sp = spec(&s, g); + assert_eq!(sp.key_anchors, keys); + let middle = sp.spine.as_ref().unwrap().subpaths[0].anchors[1]; + assert_eq!(middle.p, Point::new(55.0, 105.0)); + assert!(middle.has_in() && middle.has_out(), "{middle:?}"); + assert!((middle.h_in.y - 105.0).abs() < 1e-9 && (middle.h_out.y - 105.0).abs() < 1e-9, "tangent to the chord between its neighbors: {middle:?}"); + assert!(middle.h_in.x < 55.0 && middle.h_out.x > 55.0, "{middle:?}"); + assert_eq!(center(&node(&s, a)), Point::new(5.0, 5.0)); + assert_eq!(center(&node(&s, b)), Point::new(105.0, 5.0)); + + s.execute("path.convertAnchors", &json!({"to": "corner"})).unwrap(); + let corner = spec(&s, g).spine.unwrap().subpaths[0].anchors.clone(); + assert!(corner.iter().all(|a| !a.has_in() && !a.has_out()), "{corner:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spec(&s, g).spine.unwrap().subpaths[0].anchors[1], middle, "one undo step"); +} + #[test] fn moving_a_key_point_moves_the_key_and_the_other_way_round() { let mut s = session(); diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index c1bdfefa57..79b6b54675 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -7,9 +7,9 @@ type AnchorButton<'a> = (&'a str, &'a str, &'a str, Option<&'a str>); #[derive(Clone, Copy, PartialEq, Eq)] pub enum AnchorControls { None, - /// Paths selected as a whole with a tool that edits anchors (Direct Selection, the Pen…), - /// which shows all their anchors selected: "Convert:" only, as removing or cutting at every - /// anchor isn't what they're for. + /// Paths or blends selected as a whole with a tool that edits anchors (Direct Selection, the + /// Pen…), which shows all their anchors selected: "Convert:" only, as removing or cutting at + /// every anchor isn't what they're for. A blend converts the points of its spine. Convert, /// Anchors direct-selected: "Convert:" and "Anchors:". All, @@ -23,7 +23,8 @@ pub fn anchor_controls(app: &VectorcraftApp) -> AnchorControls { if !st.selection.anchors.is_empty() { return AnchorControls::All; } - let paths = st.selection.objects.iter().any(|id| st.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))); + let paths = + st.selection.objects.iter().any(|id| st.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Blend { .. }))); if paths && vectorcraft_tools::catalog::edits_anchors(app.session.tool_id()) { AnchorControls::Convert } else { AnchorControls::None } } diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 91a276e9b0..798777d7ea 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1031,6 +1031,23 @@ fn the_control_bar_isolates_the_selected_object_and_exits_isolation_mode() { assert_eq!(isolation_button(&mut app, &ctx, vec![]), None, "the isolation bar ends pattern editing"); } +/// #4819: with Direct Selection, a selected blend shows the Control bar's and the Properties +/// panel's Convert buttons, as a path selected whole does; with the Selection tool it doesn't. +#[test] +fn a_blend_selected_with_direct_selection_shows_the_convert_buttons() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let rect = |app: &mut crate::VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (rect(&mut app, 10.0), rect(&mut app, 200.0)); + let blend = app.run("object.blend.make", json!({"ids": [a, b], "steps": 1})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [blend]})).unwrap(); + assert!(super::anchor_controls(&app) == super::AnchorControls::None, "the Selection tool"); + app.select_tool("directSelection"); + assert!(super::anchor_controls(&app) == super::AnchorControls::Convert); +} + /// The Zoom tool's hint follows Performance › Animated Zoom (#394): a drag zooms as it goes, /// or (off) zooms into the area dragged across. #[test] From 7860931a3bd483de9c350909b87189ea4e36ffd2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 01:15:25 -0700 Subject: [PATCH 009/260] Select Same: Fill Color from a Live Paint face stays in its Live Paint group Select > Same > Fill Color and Fill & Stroke from a face of a Live Paint group now select the matching faces of that group only, and from any other object they select no Live Paint face. Before, they matched faces of every Live Paint group and paths outside them alike. --- crates/engine/src/cmd/select.rs | 34 ++++++++++++++++++----- crates/engine/src/tests/menucmds.rs | 42 +++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index b8b04482f1..462746771c 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -5,6 +5,7 @@ use std::collections::BTreeSet; use serde_json::{Value, json}; use vectorcraft_color::Paint; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_tools::builder::is_live_paint; use super::wand::{fill_of, stroke_of}; use super::{ @@ -106,11 +107,11 @@ pub fn specs() -> Vec { "Fill Color", ["Select", "Same"], None, - "{} the objects filled with the first selected object's fill colour (any tint of its global or spot swatch, the same tint with prefs selectSameTintPercent); a member path of a compound path selected first compares as its compound path, except in isolation mode inside that compound path", + "{} the objects filled with the first selected object's fill colour (any tint of its global or spot swatch, the same tint with prefs selectSameTintPercent); a member path of a compound path selected first compares as its compound path, except in isolation mode inside that compound path; from a Live Paint face, the faces of its Live Paint group only, and from any other object, no Live Paint face", has_selection, |s, _| { let tint = s.prefs.select_same_tint_percent; - same(s, "select.same.fillColor", |a, b| same_paint(&fill_of(a), &fill_of(b), tint)) + same_fill(s, "select.same.fillColor", |a, b| same_paint(&fill_of(a), &fill_of(b), tint)) } ), cmd!( @@ -135,11 +136,11 @@ pub fn specs() -> Vec { "Fill & Stroke", ["Select", "Same"], None, - "{} the objects with the first selected object's fill and stroke colours (tints and compound paths as select.same.fillColor)", + "{} the objects with the first selected object's fill and stroke colours (tints, compound paths and Live Paint faces as select.same.fillColor)", has_selection, |s, _| { let tint = s.prefs.select_same_tint_percent; - same(s, "select.same.fillAndStroke", |a, b| { + same_fill(s, "select.same.fillAndStroke", |a, b| { same_paint(&fill_of(a), &fill_of(b), tint) && same_paint(&stroke_of(a).0, &stroke_of(b).0, tint) }) } @@ -684,9 +685,30 @@ fn same_reference<'a>(st: &'a DocState, cmd: &str) -> Result<(&'a Node, bool)> { /// [`paint_reported`] accepts. A compound path matches as a whole. In isolation mode inside a /// compound path, its member paths are matched instead. fn same(s: &mut Session, cmd: &str, eq: impl Fn(&Node, &Node) -> bool) -> Result { - let (refn, members) = same_reference(s.doc()?, cmd)?; + same_in(s, cmd, false, eq) +} + +/// Select > Same > Fill Color and Fill & Stroke: [`same`], kept to one side of a Live Paint group. +/// From a face or edge of a Live Paint group, only the faces and edges of that group match; from +/// any other object, no face or edge of a Live Paint group does +/// (). +fn same_fill(s: &mut Session, cmd: &str, eq: impl Fn(&Node, &Node) -> bool) -> Result { + same_in(s, cmd, true, eq) +} + +fn same_in(s: &mut Session, cmd: &str, live_paint: bool, eq: impl Fn(&Node, &Node) -> bool) -> Result { + let st = s.doc()?; + let (refn, members) = same_reference(st, cmd)?; + let group = live_paint_group(&st.doc, refn.id); let refn = refn.clone(); - select_where(s, cmd, &json!({}), |d, n| (if members { !n.is_container() } else { paint_reported(d, n) }) && eq(n, &refn)) + select_where(s, cmd, &json!({}), |d, n| { + (!live_paint || live_paint_group(d, n.id) == group) && (if members { !n.is_container() } else { paint_reported(d, n) }) && eq(n, &refn) + }) +} + +/// The Live Paint group `id` is a face or edge of. +fn live_paint_group(d: &Document, id: NodeId) -> Option { + d.parent_of(id).filter(|p| d.node(*p).is_some_and(is_live_paint)) } /// Select the objects [`walk_selectable`] visits that `f` accepts (not looking inside accepted diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index df6f7db084..ff11009b16 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1813,6 +1813,48 @@ fn select_same_matches_compound_paths_on_their_own_paint() { assert_eq!(same(&mut s, outer, "select.same.shapeType"), vec![outer, inner]); } +/// Select > Same > Fill Color and Fill & Stroke from a Live Paint face select the faces of that +/// Live Paint group with the same fill, and nothing outside it. From an object outside every Live +/// Paint group, they select no face. +#[test] +fn select_same_fill_keeps_live_paint_faces_to_their_group() { + let mut s = session(); + let live = |s: &mut Session, y: f64| { + let a = rect(s, 0.0, y, 100.0, 100.0); + let b = rect(s, 50.0, y, 100.0, 100.0); + sel(s, &[a, b]); + id_of(&s.execute("livePaint.make", &json!({})).unwrap()) + }; + let paint = |s: &mut Session, g: NodeId, x: f64, y: f64, hex: &str| { + NodeId(s.execute("livePaint.fill", &json!({"group": g.0, "point": [x, y], "color": hex})).unwrap()["face"].as_u64().unwrap()) + }; + let g1 = live(&mut s, 0.0); + let g2 = live(&mut s, 300.0); + let [left, right] = [25.0, 125.0].map(|x| paint(&mut s, g1, x, 50.0, "#ff0000")); + let middle = paint(&mut s, g1, 75.0, 50.0, "#0000ff"); + let other = paint(&mut s, g2, 25.0, 350.0, "#ff0000"); + let [r1, r2] = [400.0, 450.0].map(|x| rect(&mut s, x, 0.0, 10.0, 10.0)); + for r in [r1, r2] { + fill(&mut s, r, "#ff0000"); + s.execute("paint.setStroke", &json!({"none": true, "ids": [r.0]})).unwrap(); + } + let same = |s: &mut Session, from: NodeId, cmd: &str| { + sel(s, &[from]); + s.execute(cmd, &json!({})).unwrap(); + let mut v = selected(s); + v.sort(); + v + }; + for cmd in ["select.same.fillColor", "select.same.fillAndStroke"] { + let mut faces = vec![left, right]; + faces.sort(); + assert_eq!(same(&mut s, left, cmd), faces, "{cmd} from a face"); + assert_eq!(same(&mut s, middle, cmd), vec![middle], "{cmd} from the blue face"); + assert_eq!(same(&mut s, other, cmd), vec![other], "{cmd} from the other group's face"); + assert_eq!(same(&mut s, r1, cmd), vec![r1, r2], "{cmd} from a path outside"); + } +} + /// Select by Color needs no object to start from: it matches fills and strokes as /// `document.inspect` reports them, `#rrggbb`. #[test] From 37211078c2bf08592cbe075f0e1b1e32adb1eb11 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 00:32:58 -0700 Subject: [PATCH 010/260] Fix #4837: the saved color scheme, accent and canvas color show at launch The first UI pass installed the default theme over the one the saved preferences had applied earlier in the same frame, and later frames saw the preferences as already applied. Classic, a non-default accent and a Canvas Color showed as the defaults until a preference changed, and again after the app took a new graphics context. The first pass now applies the saved preferences. --- crates/ui-egui/src/app.rs | 3 ++- crates/ui-egui/src/prefs_dialog.rs | 14 +++++++++++++- crates/ui-egui/src/prefs_dialog/tests.rs | 19 +++++++++++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 923459f898..13d5a00d8a 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -400,7 +400,8 @@ impl VectorcraftApp { crate::ime::install_hooks(ctx); self.adopt_context(ctx); if !self.styled { - theme::apply(ctx, self.ui.brightness); + // The saved accent, color scheme and canvas color, not the defaults (#4837). + prefs_dialog::reapply(self, ctx); egui_extras::install_image_loaders(ctx); self.styled = true; } diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index d638e0b261..b91c149f45 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -125,7 +125,7 @@ pub fn apply_runtime(app: &mut VectorcraftApp, ctx: &egui::Context) { scrub: p.scrub_numeric_fields, bare_points: p.numbers_without_units_are_points, }; - let id = egui::Id::unique("dc-applied-prefs"); + let id = applied_id(); let prev: Option = ctx.data(|d| d.get_temp::>(id)).flatten(); if prev != Some(want) { theme::apply_with(ctx, want.brightness, want.accent, want.scheme); @@ -160,6 +160,18 @@ pub fn apply_runtime(app: &mut VectorcraftApp, ctx: &egui::Context) { } } +/// Where [`apply_runtime`] keeps the preferences it last pushed into `ctx`. +fn applied_id() -> egui::Id { + egui::Id::unique("dc-applied-prefs") +} + +/// [`apply_runtime`] with nothing recorded as applied, so the theme (brightness, accent, color +/// scheme and canvas color) and the other UI-side preferences are pushed into `ctx` again. +pub(crate) fn reapply(app: &mut VectorcraftApp, ctx: &egui::Context) { + ctx.data_mut(|d| d.remove::>(applied_id())); + apply_runtime(app, ctx); +} + pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(mut d) = app.ui.dialog.clone() else { return }; let t = Tokens::get(ctx); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index c433fbc029..80fb23a176 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -60,6 +60,25 @@ fn canvas_color_choices_paint_the_pasteboard() { assert!(app.run("prefs.set", serde_json::json!({"key": "canvasColor", "value": "pink"})).is_err()); } +/// #4837: the saved Color Scheme, Accent and Canvas Color are the ones the first frame shows, not +/// the defaults the first UI pass installs. +#[test] +fn saved_scheme_accent_and_canvas_color_show_from_the_first_frame() { + let mut app = app(); + for (key, value) in [("uiColorScheme", "classic"), ("uiAccent", "pink"), ("canvasColor", "white")] { + app.run("prefs.set", json!({"key": key, "value": value})).unwrap(); + } + let ctx = egui::Context::default(); + for _ in 0..2 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.logic(ui.ctx())); + out.textures_delta.clear(); + let (t, classic) = (Tokens::get(&ctx), Tokens::for_scheme(Scheme::Classic, app.ui.brightness, Accent::Pink)); + assert_eq!((t.accent, t.app_bar, t.panel), (classic.accent, classic.app_bar, classic.panel)); + assert_eq!(t.pasteboard, egui::Color32::WHITE); + assert_eq!(ctx.global_style().visuals.hyperlink_color, classic.accent); + } +} + fn app() -> VectorcraftApp { VectorcraftApp::new(Session::new(), Services::default()) } From f6b79c3f5084aa31c6bcfdf0ed521688126eb556 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 00:17:39 -0700 Subject: [PATCH 011/260] Docs: the type.underline line in docs/mcp.md no longer repeats the end of the sentence before it --- docs/mcp.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 2cd37deac9..6fc3dd98bf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3199,7 +3199,7 @@ Pen's second anchor at (150, 431), in line with the square's centre. give its Kerning or Tracking field the keyboard focus with the value selected, or open its font family menu with the search field focused; each replies `{field: "kerning" | "tracking" | "fontName"}`. Without selected type or text the Type tool edits, the panel shows and the command fails. - shows it, in the same text; at a caret it leaves the text as it is. The UI command `type.underline` (Cmd+Shift+U, + The UI command `type.underline` (Cmd+Shift+U, in remote mode `press_key {key: "U", mods: {cmd: true, shift: true}}` or `invoke_menu`) does what the Character panel's Underline button does: it underlines the Type tool's selected text or the selected type objects, or removes the underline when the text the panel shows is underlined, and returns whether the text is now underlined. From ab2426ca15a5c99609140eec23a006e3541fd6da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 23:53:09 -0700 Subject: [PATCH 012/260] Swatches: the delete prompt for several swatches uses each language's plural forms The confirmation for deleting several swatches and groups now goes through i18n::tn, as the Graphic Styles prompt does, and each catalog gives the count-dependent forms in an @plural row. --- crates/ui-egui/src/i18n/bg.tsv | 2 +- crates/ui-egui/src/i18n/bs.tsv | 2 +- crates/ui-egui/src/i18n/ca.tsv | 2 +- crates/ui-egui/src/i18n/cs.tsv | 2 +- crates/ui-egui/src/i18n/da.tsv | 2 +- crates/ui-egui/src/i18n/de.tsv | 2 +- crates/ui-egui/src/i18n/el.tsv | 2 +- crates/ui-egui/src/i18n/es.tsv | 2 +- crates/ui-egui/src/i18n/fi.tsv | 2 +- crates/ui-egui/src/i18n/fr.tsv | 2 +- crates/ui-egui/src/i18n/hu.tsv | 2 +- crates/ui-egui/src/i18n/id.tsv | 2 +- crates/ui-egui/src/i18n/it.tsv | 2 +- crates/ui-egui/src/i18n/ja.tsv | 2 +- crates/ui-egui/src/i18n/ka.tsv | 2 +- crates/ui-egui/src/i18n/ko.tsv | 2 +- crates/ui-egui/src/i18n/nl.tsv | 2 +- crates/ui-egui/src/i18n/pl.tsv | 2 +- crates/ui-egui/src/i18n/pt-br.tsv | 2 +- crates/ui-egui/src/i18n/ru.tsv | 2 +- crates/ui-egui/src/i18n/sv.tsv | 2 +- crates/ui-egui/src/i18n/tr.tsv | 2 +- crates/ui-egui/src/i18n/uk.tsv | 2 +- crates/ui-egui/src/i18n/vi.tsv | 2 +- crates/ui-egui/src/i18n/zh-hans.tsv | 2 +- crates/ui-egui/src/i18n/zh-hant.tsv | 2 +- crates/ui-egui/src/panels/swatches/actions.rs | 2 +- crates/ui-egui/src/panels/swatches/tests.rs | 20 +++++++++++++++++++ docs/target-app-parity.md | 1 + 29 files changed, 48 insertions(+), 27 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index f7687e1616..2ddd7fd2b6 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -732,7 +732,6 @@ font-technology Variable Променливи Delete the graphic style “{name}”? Изтриване на графичния стил „{name}“? Delete Theme Изтриване на тема Delete theme Изтриване на тема - Delete these {count} swatches and groups? Изтриване на тези {count} образца и групи? Delete these {n} graphic styles? Изтриване на тези {n} графични стила? Delete this saved preset Изтриване на тази запазена предварителна настройка Delete this {n} graphic style? Изтриване на този {n} графичен стил? @@ -3618,6 +3617,7 @@ imageTrace Outline Контур @plural {n} item|{n} items {n} обект|{n} обекта @plural Color Table ({n} color)|Color Table ({n} colors) Цветна таблица ({n} цвят)|Цветна таблица ({n} цвята) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Изтриване на този графичен стил ({n})?|Изтриване на тези графични стилове ({n})? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Изтриване на този {n} образец или група?|Изтриване на тези {n} образца и групи? @plural {n} Layer|{n} Layers {n} слой|{n} слоя @plural {n} Object|{n} Objects {n} обект|{n} обекта @plural {n} area highlighted|{n} areas highlighted {n} осветена област|{n} осветени области diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d32d915036..f356047ee3 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1917,7 +1917,6 @@ lighting Light Svjetlo Weight: Debljina: Art using a deleted global swatch keeps its colour. Crtež koji koristi izbrisani globalni uzorak boje zadržava svoju boju. Color Group: {name} Grupa boja: {name} - Delete these {count} swatches and groups? Izbrisati ove uzorke boja i grupe ({count})? Delete “{name}”? Izbrisati „{name}”? Document Swatches Uzorci boja dokumenta Edit or Apply Color Group Uredi ili primijeni grupu boja @@ -4088,6 +4087,7 @@ imageTrace Outline Obris @plural {n} item|{n} items {n} stavka|{n} stavke|{n} stavki @plural Color Table ({n} color)|Color Table ({n} colors) Tabela boja ({n} boja)|Tabela boja ({n} boje)|Tabela boja ({n} boja) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Izbrisati ovaj {n} grafički stil?|Izbrisati ova {n} grafička stila?|Izbrisati ovih {n} grafičkih stilova? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Izbrisati {n} uzorak boje ili grupu?|Izbrisati {n} uzorka boja i grupe?|Izbrisati {n} uzoraka boja i grupa? @plural {n} Layer|{n} Layers {n} sloj|{n} sloja|{n} slojeva @plural {n} Object|{n} Objects {n} objekat|{n} objekta|{n} objekata @plural {n} area highlighted|{n} areas highlighted Istaknuto {n} područje|Istaknuta {n} područja|Istaknuto {n} područja diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index ae721b931e..34722c0b16 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1050,7 +1050,6 @@ Delete the library “{name}”? Voleu suprimir la biblioteca “{name}”? Delete Theme Suprimeix el tema Delete theme Suprimeix el tema - Delete these {count} swatches and groups? Voleu suprimir aquestes {count} mostres i grups? Delete these {n} graphic styles? Voleu suprimir aquests {n} estils gràfics? Delete this saved preset Suprimeix aquest preajust desat Delete this {n} graphic style? Voleu suprimir aquest {n} estil gràfic? @@ -4678,6 +4677,7 @@ @plural agrees with {n} default shortcut|agrees with {n} default shortcuts coincideix amb {n} drecera per defecte|coincideix amb {n} dreceres per defecte @plural Color Table ({n} color)|Color Table ({n} colors) Taula de colors ({n} color)|Taula de colors ({n} colors) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Voleu suprimir aquest {n} estil gràfic?|Voleu suprimir aquests {n} estils gràfics? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Voleu suprimir aquesta {n} mostra o grup?|Voleu suprimir aquestes {n} mostres i grups? @plural {n} area highlighted|{n} areas highlighted {n} àrea ressaltada|{n} àrees ressaltades @plural {n} color|{n} colors {n} color|{n} colors @plural {n} commit|{n} commits {n} commit|{n} commits diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index f21ad521cd..b5fbc21540 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1944,7 +1944,6 @@ lighting Light Světlo Weight: Tloušťka: Art using a deleted global swatch keeps its colour. Kresba, která používá odstraněnou globální položku vzorníku, si barvu ponechá. Color Group: {name} Skupina barev: {name} - Delete these {count} swatches and groups? Odstranit tyto položky vzorníku a skupiny ({count})? Delete “{name}”? Odstranit „{name}“? Document Swatches Vzorník dokumentu Edit or Apply Color Group Upravit nebo použít skupinu barev @@ -4122,6 +4121,7 @@ imageTrace Outline Obrys @plural {n} item|{n} items {n} položka|{n} položky|{n} položek @plural Color Table ({n} color)|Color Table ({n} colors) Tabulka barev ({n} barva)|Tabulka barev ({n} barvy)|Tabulka barev ({n} barev) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Odstranit {n} grafický styl?|Odstranit {n} grafické styly?|Odstranit {n} grafických stylů? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Odstranit {n} položku vzorníku nebo skupinu?|Odstranit {n} položky vzorníku a skupiny?|Odstranit {n} položek vzorníku a skupin? @plural {n} Layer|{n} Layers {n} vrstva|{n} vrstvy|{n} vrstev @plural {n} Object|{n} Objects {n} objekt|{n} objekty|{n} objektů @plural {n} area highlighted|{n} areas highlighted Zvýrazněna {n} oblast|Zvýrazněny {n} oblasti|Zvýrazněno {n} oblastí diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b310616e3a..4642b364bc 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1755,7 +1755,6 @@ lighting Light Lys Weight: Vægt: Art using a deleted global swatch keeps its colour. Grafik, der bruger en slettet global farveprøve, bevarer sin farve. Color Group: {name} Farvegruppe: {name} - Delete these {count} swatches and groups? Slet disse {count} farveprøver og grupper? Delete “{name}”? Slet »{name}«? Document Swatches Dokumentfarveprøver Edit or Apply Color Group Redigér eller anvend farvegruppe @@ -3854,6 +3853,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} element|{n} elementer @plural Color Table ({n} color)|Color Table ({n} colors) Farvetabel ({n} farve)|Farvetabel ({n} farver) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Vil du slette denne {n} grafikstil?|Vil du slette disse {n} grafikstile? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Slet denne {n} farveprøve eller gruppe?|Slet disse {n} farveprøver og grupper? @plural {n} Layer|{n} Layers {n} lag|{n} lag @plural {n} Object|{n} Objects {n} objekt|{n} objekter @plural {n} area highlighted|{n} areas highlighted {n} område fremhævet|{n} områder fremhævet diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 5b29c93e2d..320960d0ef 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -726,7 +726,6 @@ font-technology Variable Variabel Delete the graphic style “{name}”? Grafikstil „{name}“ löschen? Delete Theme Thema löschen Delete theme Thema löschen - Delete these {count} swatches and groups? Diese {count} Farbfelder und Gruppen löschen? Delete these {n} graphic styles? Diese {n} Grafikstile löschen? Delete this saved preset Diese gespeicherte Vorgabe löschen Delete this {n} graphic style? Diesen {n} Grafikstil löschen? @@ -3605,6 +3604,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} Element|{n} Elemente @plural Color Table ({n} color)|Color Table ({n} colors) Farbtabelle ({n} Farbe)|Farbtabelle ({n} Farben) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Diesen {n} Grafikstil löschen?|Diese {n} Grafikstile löschen? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? {n} Farbfeld oder Gruppe löschen?|Diese {n} Farbfelder und Gruppen löschen? @plural {n} Layer|{n} Layers {n} Ebene|{n} Ebenen @plural {n} Object|{n} Objects {n} Objekt|{n} Objekte @plural {n} area highlighted|{n} areas highlighted {n} Bereich hervorgehoben|{n} Bereiche hervorgehoben diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 2909355306..7dfc4f3e67 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -706,7 +706,6 @@ font-technology Variable Μεταβλητές Delete the graphic style “{name}”? Να διαγραφεί το στυλ γραφικών «{name}»; Delete Theme Διαγραφή θέματος Delete theme Διαγραφή θέματος - Delete these {count} swatches and groups? Να διαγραφούν αυτά τα {count} δείγματα χρωμάτων και οι ομάδες; Delete these {n} graphic styles? Να διαγραφούν αυτά τα {n} στυλ γραφικών; Delete this saved preset Διαγραφή αυτής της αποθηκευμένης προεπιλογής Delete this {n} graphic style? Να διαγραφεί αυτό το {n} στυλ γραφικών; @@ -2017,6 +2016,7 @@ imageTrace Outline Περίγραμμα @plural {n} item|{n} items {n} στοιχείο|{n} στοιχεία @plural Color Table ({n} color)|Color Table ({n} colors) Πίνακας χρωμάτων ({n} χρώμα)|Πίνακας χρωμάτων ({n} χρώματα) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Να διαγραφεί αυτό το {n} στυλ γραφικών;|Να διαγραφούν αυτά τα {n} στυλ γραφικών; +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Να διαγραφεί αυτό το {n} δείγμα χρώματος ή ομάδα;|Να διαγραφούν αυτά τα {n} δείγματα χρωμάτων και οι ομάδες; @plural {n} Layer|{n} Layers {n} επίπεδο|{n} επίπεδα @plural {n} Object|{n} Objects {n} αντικείμενο|{n} αντικείμενα @plural {n} area highlighted|{n} areas highlighted {n} περιοχή επισημάνθηκε|{n} περιοχές επισημάνθηκαν diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index bc21e2e6c4..454557e044 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -747,7 +747,6 @@ font-technology Variable Variables Delete the graphic style “{name}”? ¿Eliminar el estilo gráfico “{name}”? Delete Theme Eliminar tema Delete theme Eliminar tema - Delete these {count} swatches and groups? ¿Eliminar estas {count} muestras y grupos? Delete these {n} graphic styles? ¿Eliminar estos {n} estilos gráficos? Delete this saved preset Eliminar este preajuste guardado Delete this {n} graphic style? ¿Eliminar {n} estilo gráfico? @@ -3690,6 +3689,7 @@ imageTrace Outline Contorno @plural {n} item|{n} items {n} elemento|{n} elementos @plural Color Table ({n} color)|Color Table ({n} colors) Tabla de colores ({n} color)|Tabla de colores ({n} colores) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? ¿Eliminar {n} estilo gráfico?|¿Eliminar estos {n} estilos gráficos? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? ¿Eliminar {n} muestra o grupo?|¿Eliminar estas {n} muestras y grupos? @plural {n} Layer|{n} Layers {n} capa|{n} capas @plural {n} Object|{n} Objects {n} objeto|{n} objetos @plural {n} area highlighted|{n} areas highlighted {n} área resaltada|{n} áreas resaltadas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 7941c911ba..ede17d2aca 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1906,7 +1906,6 @@ lighting Light Valo Weight: Paksuus: Art using a deleted global swatch keeps its colour. Poistettua globaalia värimallia käyttävä kuvitus säilyttää värinsä. Color Group: {name} Väriryhmä: {name} - Delete these {count} swatches and groups? Poistetaanko nämä {count} värimallia ja ryhmää? Delete “{name}”? Poistetaanko ”{name}”? Document Swatches Asiakirjan värimallit Edit or Apply Color Group Muokkaa tai käytä väriryhmää @@ -4040,6 +4039,7 @@ imageTrace Outline Ääriviiva @plural {n} item|{n} items {n} kohde|{n} kohdetta @plural Color Table ({n} color)|Color Table ({n} colors) Väritaulukko ({n} väri)|Väritaulukko ({n} väriä) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Poistetaanko tämä {n} grafiikkatyyli?|Poistetaanko nämä {n} grafiikkatyyliä? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Poistetaanko tämä {n} värimalli tai ryhmä?|Poistetaanko nämä {n} värimallia ja ryhmää? @plural {n} Layer|{n} Layers {n} taso|{n} tasoa @plural {n} Object|{n} Objects {n} objekti|{n} objektia @plural {n} area highlighted|{n} areas highlighted {n} alue korostettu|{n} aluetta korostettu diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index c59ae9ad42..e6c5ef0be5 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -749,7 +749,7 @@ font-technology Variable Variables Delete the graphic style “{name}”? Supprimer le style graphique « {name} » ? Delete Theme Supprimer le thème Delete theme Supprimer le thème - Delete these {count} swatches and groups? Supprimer ces {count} nuances et groupes ? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Supprimer {n} nuance ou groupe ?|Supprimer ces {n} nuances et groupes ? Delete these {n} graphic styles? Supprimer ces {n} styles graphiques ? Delete this saved preset Supprimer ce paramètre prédéfini enregistré Delete this {n} graphic style? Supprimer {n} style graphique ? diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 3b1de01a5a..eb4e09e41a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -972,7 +972,6 @@ font-technology Variable Változó Delete the library “{name}”? Törlöd ezt a könyvtárat: „{name}”? Delete Theme Téma törlése Delete theme Téma törlése - Delete these {count} swatches and groups? {count} színminta és csoport törlése? Delete these {n} graphic styles? {n} grafikai stílus törlése? Delete this saved preset A mentett előbeállítás törlése Delete this {n} graphic style? {n} grafikai stílus törlése? @@ -4443,6 +4442,7 @@ theme Appearance Kinézet imageTrace Outline Körvonal @plural Color Table ({n} color)|Color Table ({n} colors) Színtábla ({n} szín) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? {n} grafikai stílus törlése? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? {n} színminta és csoport törlése? @plural {n} area highlighted|{n} areas highlighted Kiemelt terület: {n} @plural {n} color|{n} colors {n} szín @plural {n} fill|{n} fills {n} kitöltés diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 9184b86356..e43dc998ae 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1755,7 +1755,6 @@ lighting Light Cahaya Weight: Ketebalan: Art using a deleted global swatch keeps its colour. Karya seni yang memakai swatch global terhapus tetap mempertahankan warnanya. Color Group: {name} Grup warna: {name} - Delete these {count} swatches and groups? Hapus {count} swatch dan grup ini? Delete “{name}”? Hapus “{name}”? Document Swatches Swatch dokumen Edit or Apply Color Group Edit atau terapkan grup warna @@ -3854,6 +3853,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} item @plural Color Table ({n} color)|Color Table ({n} colors) Tabel warna ({n} warna) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Hapus {n} gaya grafis ini? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Hapus {n} swatch dan grup ini? @plural {n} Layer|{n} Layers {n} lapisan @plural {n} Object|{n} Objects {n} objek @plural {n} area highlighted|{n} areas highlighted {n} area disorot diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 605a4145bf..eefe97ac7f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -747,7 +747,6 @@ font-technology Variable Variabili Delete the graphic style “{name}”? Eliminare lo stile grafico “{name}”? Delete Theme Elimina tema Delete theme Elimina tema - Delete these {count} swatches and groups? Eliminare questi {count} campioni e gruppi? Delete these {n} graphic styles? Eliminare questi {n} stili grafici? Delete this saved preset Elimina questo preset salvato Delete this {n} graphic style? Eliminare {n} stile grafico? @@ -3726,6 +3725,7 @@ imageTrace Outline Contorno @plural {n} item|{n} items {n} elemento|{n} elementi @plural Color Table ({n} color)|Color Table ({n} colors) Tabella colori ({n} colore)|Tabella colori ({n} colori) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Eliminare {n} stile grafico?|Eliminare questi {n} stili grafici? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Eliminare {n} campione o gruppo?|Eliminare questi {n} campioni e gruppi? @plural {n} Layer|{n} Layers {n} livello|{n} livelli @plural {n} Object|{n} Objects {n} oggetto|{n} oggetti @plural {n} area highlighted|{n} areas highlighted {n} area evidenziata|{n} aree evidenziate diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 2542ac6636..51b72cd238 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1297,7 +1297,6 @@ font-technology Variable バリアブル Delete Workspace ワークスペースを削除 Delete the graphic style “{name}”? グラフィックスタイル「{name}」を削除しますか? Delete theme テーマを削除 - Delete these {count} swatches and groups? これら {count} 個のスウォッチとグループを削除しますか? Delete this saved preset この保存済みプリセットを削除 Delete {kind} Style {kind}スタイルを削除 Delete “{name}”? 「{name}」を削除しますか? @@ -3709,6 +3708,7 @@ file-filter Templates テンプレート imageTrace Outline アウトライン @plural Color Table ({n} color)|Color Table ({n} colors) カラーテーブル ({n} 色) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? {n} 個のグラフィックスタイルを削除しますか? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? これら {n} 個のスウォッチとグループを削除しますか? @plural {n} Layer|{n} Layers {n} レイヤー @plural {n} Object|{n} Objects {n} オブジェクト @plural {n} area highlighted|{n} areas highlighted {n} 個の範囲を強調表示 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index ab961a7108..7ae614f12b 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1658,7 +1658,6 @@ lighting Light სინათლე Weight: სისქე: Art using a deleted global swatch keeps its colour. წაშლილი გლობალური ფერის ნიმუშის მქონე ნახატი თავის ფერს ინარჩუნებს. Color Group: {name} ფერთა ჯგუფი: {name} - Delete these {count} swatches and groups? წაიშალოს ეს ფერის ნიმუშები და ჯგუფები ({count})? Delete “{name}”? წაიშალოს „{name}“? Document Swatches დოკუმენტის ფერის ნიმუშები Edit or Apply Color Group ფერთა ჯგუფის რედაქტირება ან გამოყენება @@ -3620,6 +3619,7 @@ font-technology Variable ცვლადი @plural {n} item|{n} items ელემენტი: {n} @plural Color Table ({n} color)|Color Table ({n} colors) ფერების ცხრილი (ფერი: {n}) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? წაიშალოს გრაფიკული სტილები ({n})? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? წაიშალოს ეს ფერის ნიმუშები და ჯგუფები ({n})? @plural {n} Layer|{n} Layers შრე: {n} @plural {n} Object|{n} Objects ობიექტი: {n} @plural {n} area highlighted|{n} areas highlighted გამოკვეთილი არე: {n} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index cbfe1c6f2a..23e55a28fd 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1288,7 +1288,6 @@ font-technology Variable 가변 Delete Workspace 작업 영역 삭제 Delete the graphic style “{name}”? 그래픽 스타일 “{name}”을(를) 삭제하시겠습니까? Delete theme 테마 삭제 - Delete these {count} swatches and groups? 견본과 그룹 {count}개를 삭제하시겠습니까? Delete this saved preset 저장된 이 프리셋 삭제 Delete {kind} Style {kind} 스타일 삭제 Delete “{name}”? “{name}”을(를) 삭제하시겠습니까? @@ -3698,6 +3697,7 @@ file-filter Templates 템플릿 imageTrace Outline 윤곽선 @plural Color Table ({n} color)|Color Table ({n} colors) 색상 표 ({n}색)|색상 표 ({n}색) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? 그래픽 스타일 {n}개를 삭제하시겠습니까?|그래픽 스타일 {n}개를 삭제하시겠습니까? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? 견본과 그룹 {n}개를 삭제하시겠습니까? @plural {n} Layer|{n} Layers 레이어 {n}개|레이어 {n}개 @plural {n} Object|{n} Objects 개체 {n}개|개체 {n}개 @plural {n} area highlighted|{n} areas highlighted 강조된 영역 {n}개|강조된 영역 {n}개 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 65a2d54408..c269832419 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1769,7 +1769,6 @@ lighting Light Licht Weight: Dikte: Art using a deleted global swatch keeps its colour. Artwork met een verwijderd globaal staal behoudt zijn kleur. Color Group: {name} Kleurgroep: {name} - Delete these {count} swatches and groups? Deze {count} stalen en groepen verwijderen? Delete “{name}”? „{name}” verwijderen? Document Swatches Documentstalen Edit or Apply Color Group Kleurgroep bewerken of toepassen @@ -3868,6 +3867,7 @@ imageTrace Outline Contour @plural {n} item|{n} items {n} item|{n} items @plural Color Table ({n} color)|Color Table ({n} colors) Kleurentabel ({n} kleur)|Kleurentabel ({n} kleuren) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Deze {n} grafische stijl verwijderen?|Deze {n} grafische stijlen verwijderen? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Deze {n} staal of groep verwijderen?|Deze {n} stalen en groepen verwijderen? @plural {n} Layer|{n} Layers {n} laag|{n} lagen @plural {n} Object|{n} Objects {n} object|{n} objecten @plural {n} area highlighted|{n} areas highlighted {n} gebied gemarkeerd|{n} gebieden gemarkeerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 7eb02958a1..65cb40b345 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1864,7 +1864,6 @@ lighting Light Światło Weight: Grubość: Art using a deleted global swatch keeps its colour. Kompozycja używająca usuniętej próbki globalnej zachowa swój kolor. Color Group: {name} Grupa kolorów: {name} - Delete these {count} swatches and groups? Usunąć te próbki i grupy ({count})? Delete “{name}”? Usunąć „{name}”? Document Swatches Próbki dokumentu Edit or Apply Color Group Edytuj lub zastosuj grupę kolorów @@ -3948,6 +3947,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} element|{n} elementy|{n} elementów @plural Color Table ({n} color)|Color Table ({n} colors) Tablica kolorów ({n} kolor)|Tablica kolorów ({n} kolory)|Tablica kolorów ({n} kolorów) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Usunąć {n} styl graficzny?|Usunąć {n} style graficzne?|Usunąć {n} stylów graficznych? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Usunąć {n} próbkę lub grupę?|Usunąć {n} próbki i grupy?|Usunąć {n} próbek i grup? @plural {n} Layer|{n} Layers {n} warstwa|{n} warstwy|{n} warstw @plural {n} Object|{n} Objects {n} obiekt|{n} obiekty|{n} obiektów @plural {n} area highlighted|{n} areas highlighted Wyróżniono {n} obszar|Wyróżniono {n} obszary|Wyróżniono {n} obszarów diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index bd4b760a56..8fd2b3ba5e 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -663,7 +663,6 @@ Delete Workspace Excluir Espaço de Trabalho Delete the graphic style “{name}”? Excluir o estilo gráfico “{name}”? Delete theme Excluir tema - Delete these {count} swatches and groups? Excluir estas {count} amostras e grupos? Delete this saved preset Excluir este predefinido salvo Delete {kind} Style Excluir Estilo de {kind} Delete “{name}”? Excluir “{name}”? @@ -3028,6 +3027,7 @@ imageTrace Outline Contorno @plural {n} item|{n} items {n} item|{n} itens @plural Color Table ({n} color)|Color Table ({n} colors) Tabela de Cores ({n} cor)|Tabela de Cores ({n} cores) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Excluir este {n} estilo gráfico?|Excluir estes {n} estilos gráficos? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Excluir esta {n} amostra ou grupo?|Excluir estas {n} amostras e grupos? @plural {n} Layer|{n} Layers {n} Camada|{n} Camadas @plural {n} Object|{n} Objects {n} Objeto|{n} Objetos @plural {n} area highlighted|{n} areas highlighted {n} área realçada|{n} áreas realçadas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index c1e796308b..379cf8a93e 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -745,7 +745,6 @@ font-technology Variable Вариативные Delete the graphic style “{name}”? Удалить графический стиль «{name}»? Delete Theme Удалить тему Delete theme Удалить тему - Delete these {count} swatches and groups? Удалить эти образцы и группы ({count})? Delete these {n} graphic styles? Удалить эти графические стили ({n})? Delete this saved preset Удалить этот сохранённый набор Delete this {n} graphic style? Удалить этот графический стиль ({n})? @@ -3722,6 +3721,7 @@ imageTrace Outline Контур @plural {n} item|{n} items {n} элемент|{n} элемента|{n} элементов @plural Color Table ({n} color)|Color Table ({n} colors) Цветовая таблица ({n} цвет)|Цветовая таблица ({n} цвета)|Цветовая таблица ({n} цветов) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Удалить этот графический стиль ({n})?|Удалить эти графические стили ({n})?|Удалить эти графические стили ({n})? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Удалить {n} образец или группу?|Удалить {n} образца и группы?|Удалить {n} образцов и групп? @plural {n} Layer|{n} Layers {n} слой|{n} слоя|{n} слоёв @plural {n} Object|{n} Objects {n} объект|{n} объекта|{n} объектов @plural {n} area highlighted|{n} areas highlighted {n} область выделена|{n} области выделено|{n} областей выделено diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 3da858206d..df96962c15 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -734,7 +734,6 @@ font-technology Variable Variabla Delete the graphic style “{name}”? Radera grafikstilen ”{name}”? Delete Theme Radera tema Delete theme Radera tema - Delete these {count} swatches and groups? Radera dessa {count} färgrutor och grupper? Delete these {n} graphic styles? Radera dessa {n} grafikstilar? Delete this saved preset Radera den här sparade förinställningen Delete this {n} graphic style? Radera denna {n} grafikstil? @@ -3618,6 +3617,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} objekt|{n} objekt @plural Color Table ({n} color)|Color Table ({n} colors) Färgtabell ({n} färg)|Färgtabell ({n} färger) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Radera {n} grafisk stil?|Radera de här {n} grafiska stilarna? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Radera {n} färgruta eller grupp?|Radera dessa {n} färgrutor och grupper? @plural {n} Layer|{n} Layers {n} lager|{n} lager @plural {n} Object|{n} Objects {n} objekt|{n} objekt @plural {n} area highlighted|{n} areas highlighted {n} område framhävt|{n} områden framhävda diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ab17bb0530..d099149f07 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -726,7 +726,6 @@ font-technology Variable Değişken Delete the graphic style “{name}”? “{name}” grafik stili silinsin mi? Delete Theme Temayı Sil Delete theme Temayı sil - Delete these {count} swatches and groups? Bu {count} renk örnekleri ve grupları silinsin mi? Delete these {n} graphic styles? Bu {n} grafik stilleri silinsin mi? Delete this saved preset Bu kayıtlı ön ayarı silin Delete this {n} graphic style? Bu {n} grafik stili silinsin mi? @@ -3512,6 +3511,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} öğe @plural Color Table ({n} color)|Color Table ({n} colors) Renk Tablosu ({n} renk) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Bu {n} grafik stili silinsin mi? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Bu {n} renk örneği ve grup silinsin mi? @plural {n} Layer|{n} Layers {n} Katman @plural {n} Object|{n} Objects {n} Nesne @plural {n} area highlighted|{n} areas highlighted {n} alan vurgulandı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index ebf801d5f6..632d9c7326 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -741,7 +741,6 @@ font-technology Variable Варіативні Delete the graphic style “{name}”? Видалити графічний стиль «{name}»? Delete Theme Видалити тему Delete theme Видалити тему - Delete these {count} swatches and groups? Видалити ці зразки та групи ({count})? Delete these {n} graphic styles? Видалити ці графічні стилі ({n})? Delete this saved preset Видалити цей збережений набір Delete this {n} graphic style? Видалити цей графічний стиль ({n})? @@ -3719,6 +3718,7 @@ imageTrace Outline Контур @plural {n} item|{n} items {n} елемент|{n} елементи|{n} елементів @plural Color Table ({n} color)|Color Table ({n} colors) Таблиця кольорів ({n} колір)|Таблиця кольорів ({n} кольори)|Таблиця кольорів ({n} кольорів) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Видалити цей графічний стиль ({n})?|Видалити ці графічні стилі ({n})?|Видалити ці графічні стилі ({n})? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Видалити {n} зразок або групу?|Видалити {n} зразки та групи?|Видалити {n} зразків і груп? @plural {n} Layer|{n} Layers {n} шар|{n} шари|{n} шарів @plural {n} Object|{n} Objects {n} об’єкт|{n} об’єкти|{n} об’єктів @plural {n} area highlighted|{n} areas highlighted Підсвічено {n} область|Підсвічено {n} області|Підсвічено {n} областей diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index d41165b25e..f0c495d4f9 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -868,7 +868,6 @@ font-technology Variable Biến thiên Delete the library “{name}”? Xóa thư viện “{name}”? Delete Theme Xóa bộ màu Delete theme Xóa bộ màu - Delete these {count} swatches and groups? Xóa {count} mẫu màu và nhóm này? Delete these {n} graphic styles? Xóa {n} kiểu đồ họa này? Delete this saved preset Xóa thiết lập sẵn đã lưu này Delete this {n} graphic style? Xóa {n} kiểu đồ họa này? @@ -4084,6 +4083,7 @@ gradient-kind Radial Hướng tâm imageTrace Outline Đường viền @plural Color Table ({n} color)|Color Table ({n} colors) Bảng màu ({n} màu) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Xóa {n} kiểu đồ họa này? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Xóa {n} mẫu màu và nhóm này? @plural {n} area highlighted|{n} areas highlighted {n} vùng được tô sáng @plural {n} color|{n} colors {n} màu @plural {n} fill|{n} fills {n} tô diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 0cf85b50dc..61defa0208 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -690,7 +690,6 @@ Delete the graphic style “{name}”? 要删除图形样式“{name}”吗? Delete Theme 删除主题 Delete theme 删除主题 - Delete these {count} swatches and groups? 要删除这 {count} 个色板和编组吗? Delete these {n} graphic styles? 要删除这 {n} 个图形样式吗? Delete this saved preset 删除此已存储的预设 Delete this {n} graphic style? 要删除这 {n} 个图形样式吗? @@ -3565,6 +3564,7 @@ imageTrace Outline 轮廓 @plural {n} item|{n} items {n} 个项目 @plural Color Table ({n} color)|Color Table ({n} colors) 颜色表 ({n} 色) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? 要删除这 {n} 个图形样式吗? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? 要删除这 {n} 个色板和编组吗? @plural {n} Layer|{n} Layers {n} 个图层 @plural {n} Object|{n} Objects {n} 个对象 @plural {n} area highlighted|{n} areas highlighted 已标示 {n} 个区域 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 47a38972c5..423e780b0d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -709,7 +709,6 @@ font-technology Variable 可變 Delete the graphic style “{name}”? 要刪除繪圖樣式「{name}」嗎? Delete Theme 刪除主題 Delete theme 刪除主題 - Delete these {count} swatches and groups? 要刪除這 {count} 個色票和群組嗎? Delete these {n} graphic styles? 要刪除這 {n} 個繪圖樣式嗎? Delete this saved preset 刪除此已儲存的預設集 Delete this {n} graphic style? 要刪除這 {n} 個繪圖樣式嗎? @@ -4542,6 +4541,7 @@ imageTrace Outline 輪廓 @plural {n} item|{n} items {n} 個項目 @plural Color Table ({n} color)|Color Table ({n} colors) 色彩表 ({n} 色) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? 要刪除這 {n} 個繪圖樣式嗎? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? 要刪除這 {n} 個色票和群組嗎? @plural {n} Layer|{n} Layers {n} 個圖層 @plural {n} Object|{n} Objects {n} 個物件 @plural {n} area highlighted|{n} areas highlighted 已標示 {n} 個區域 diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index 6e9a56fd9b..be275c108b 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -42,7 +42,7 @@ pub(super) fn delete(app: &mut VectorcraftApp, names: Vec, now: bool) { } let message = match names.as_slice() { [n] => crate::i18n::fmt(tl!("Delete “{name}”?"), &[("name", n)]), - _ => crate::i18n::fmt(tl!("Delete these {count} swatches and groups?"), &[("count", &names.len().to_string())]), + _ => crate::i18n::tn(names.len() as u64, "Delete this {n} swatch or group?", "Delete these {n} swatches and groups?"), }; crate::dialogs::confirm::ask(app, &message, tl!("Art using a deleted global swatch keeps its colour."), "swatch.delete", params); } diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index c659413703..9f6f036e5a 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -265,6 +265,26 @@ fn delete_asks_then_removes_the_selection_and_unlinks_art() { assert_eq!(deletable(&["[None]".into(), REGISTRATION.into(), "Grays".into()]), ["Grays"]); } +/// The prompt for several swatches and groups gives the form the language's plural rule picks for the count. +#[test] +fn deleting_several_swatches_uses_each_count_form() { + let mut app = app(); + let mut prompt = |code: &str, count: usize| { + crate::i18n::set_current(crate::i18n::Lang::from_code(code).unwrap()); + let names: Vec = (1..=count).map(|n| format!("Swatch {n}")).collect(); + delete(&mut app, names, false); + let message = app.ui.dialog.as_ref().map(|d| d.str("message")); + crate::dialogs::cancel(&mut app); + crate::i18n::set_current(crate::i18n::Lang::EN); + message + }; + assert_eq!(prompt("pl", 2), Some("Usunąć 2 próbki i grupy?".to_string())); + assert_eq!(prompt("pl", 5), Some("Usunąć 5 próbek i grup?".to_string())); + assert_eq!(prompt("uk", 21), Some("Видалити 21 зразок або групу?".to_string())); + assert_eq!(prompt("uk", 22), Some("Видалити 22 зразки та групи?".to_string())); + assert_eq!(prompt("uk", 25), Some("Видалити 25 зразків і груп?".to_string())); +} + #[test] fn new_swatch_dialog_prefills_the_active_colour_and_saves_into_the_selected_group() { let mut app = app(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a4207f302d..416501d553 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -912,6 +912,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **CSS swatch libraries:** fractional linear and radial gradient stop positions are preserved, so nearby stops such as 12.5% and 12.890625% remain distinct instead of collapsing to 13%. Reference: [CSS Images 3 color stops](https://www.w3.org/TR/css-images-3/#color-stop-syntax). The original synthetic regression is `palette_io::tests::css_preserves_fractional_gradient_stop_positions` in `crates/color/src/palette_io.rs`. Scores and hours are unchanged. - **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate. Editing, renaming, deleting or merging a global swatch also changes the colors linked to it in graph designs, the art of brushes and the tile that pattern editing's Cancel puts back, in the same undo step as the rest of the art; Default Swatches with replace unlinks them there too. + The prompt for deleting several swatches and groups uses the interface language's plural form for the count. Evidence: `deleting_several_swatches_uses_each_count_form` in `crates/ui-egui/src/panels/swatches/tests.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels. - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. - **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given. From 541a6c33f0647c93bdb436ca64a3d925b78afe29 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 00:05:16 -0700 Subject: [PATCH 013/260] Swatches: the Ukrainian, Russian and Bosnian delete prompt for 21 or 31 items names swatches and groups In these languages a count ending in 1 (other than 11) takes the singular form, which read as one swatch or one group. That form now names swatches and groups with the count in parentheses. --- crates/ui-egui/src/i18n/bs.tsv | 2 +- crates/ui-egui/src/i18n/ru.tsv | 2 +- crates/ui-egui/src/i18n/uk.tsv | 2 +- crates/ui-egui/src/panels/swatches/tests.rs | 4 +++- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index f356047ee3..1c0416e677 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4087,7 +4087,7 @@ imageTrace Outline Obris @plural {n} item|{n} items {n} stavka|{n} stavke|{n} stavki @plural Color Table ({n} color)|Color Table ({n} colors) Tabela boja ({n} boja)|Tabela boja ({n} boje)|Tabela boja ({n} boja) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Izbrisati ovaj {n} grafički stil?|Izbrisati ova {n} grafička stila?|Izbrisati ovih {n} grafičkih stilova? -@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Izbrisati {n} uzorak boje ili grupu?|Izbrisati {n} uzorka boja i grupe?|Izbrisati {n} uzoraka boja i grupa? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Izbrisati uzorke boja i grupe ({n})?|Izbrisati {n} uzorka boja i grupe?|Izbrisati {n} uzoraka boja i grupa? @plural {n} Layer|{n} Layers {n} sloj|{n} sloja|{n} slojeva @plural {n} Object|{n} Objects {n} objekat|{n} objekta|{n} objekata @plural {n} area highlighted|{n} areas highlighted Istaknuto {n} područje|Istaknuta {n} područja|Istaknuto {n} područja diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 379cf8a93e..b605f92778 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3721,7 +3721,7 @@ imageTrace Outline Контур @plural {n} item|{n} items {n} элемент|{n} элемента|{n} элементов @plural Color Table ({n} color)|Color Table ({n} colors) Цветовая таблица ({n} цвет)|Цветовая таблица ({n} цвета)|Цветовая таблица ({n} цветов) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Удалить этот графический стиль ({n})?|Удалить эти графические стили ({n})?|Удалить эти графические стили ({n})? -@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Удалить {n} образец или группу?|Удалить {n} образца и группы?|Удалить {n} образцов и групп? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Удалить образцы и группы ({n})?|Удалить {n} образца и группы?|Удалить {n} образцов и групп? @plural {n} Layer|{n} Layers {n} слой|{n} слоя|{n} слоёв @plural {n} Object|{n} Objects {n} объект|{n} объекта|{n} объектов @plural {n} area highlighted|{n} areas highlighted {n} область выделена|{n} области выделено|{n} областей выделено diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 632d9c7326..9454d2f364 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3718,7 +3718,7 @@ imageTrace Outline Контур @plural {n} item|{n} items {n} елемент|{n} елементи|{n} елементів @plural Color Table ({n} color)|Color Table ({n} colors) Таблиця кольорів ({n} колір)|Таблиця кольорів ({n} кольори)|Таблиця кольорів ({n} кольорів) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Видалити цей графічний стиль ({n})?|Видалити ці графічні стилі ({n})?|Видалити ці графічні стилі ({n})? -@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Видалити {n} зразок або групу?|Видалити {n} зразки та групи?|Видалити {n} зразків і груп? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Видалити зразки та групи ({n})?|Видалити {n} зразки та групи?|Видалити {n} зразків і груп? @plural {n} Layer|{n} Layers {n} шар|{n} шари|{n} шарів @plural {n} Object|{n} Objects {n} об’єкт|{n} об’єкти|{n} об’єктів @plural {n} area highlighted|{n} areas highlighted Підсвічено {n} область|Підсвічено {n} області|Підсвічено {n} областей diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 9f6f036e5a..c649e282ba 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -280,7 +280,9 @@ fn deleting_several_swatches_uses_each_count_form() { }; assert_eq!(prompt("pl", 2), Some("Usunąć 2 próbki i grupy?".to_string())); assert_eq!(prompt("pl", 5), Some("Usunąć 5 próbek i grup?".to_string())); - assert_eq!(prompt("uk", 21), Some("Видалити 21 зразок або групу?".to_string())); + assert_eq!(prompt("uk", 21), Some("Видалити зразки та групи (21)?".to_string())); + assert_eq!(prompt("ru", 21), Some("Удалить образцы и группы (21)?".to_string())); + assert_eq!(prompt("bs", 21), Some("Izbrisati uzorke boja i grupe (21)?".to_string())); assert_eq!(prompt("uk", 22), Some("Видалити 22 зразки та групи?".to_string())); assert_eq!(prompt("uk", 25), Some("Видалити 25 зразків і груп?".to_string())); } From d0a903d5d7cae4ab055718e33d5d67ea6739f575 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 23:31:32 -0700 Subject: [PATCH 014/260] DXF export: ellipses and unevenly scaled circles are written as ELLIPSE A closed path of four cubics that is the four-cubic circle under an affine map (an ellipse, or a circle scaled out of proportion) is written as a native ELLIPSE in R13 and later, with its center, major axis and minor to major ratio. The check maps the path back onto the unit circle and runs the existing circle recognition on it. R12 keeps the existing fallback, and ellipses with a ratio under 1e-6 stay splines. The ratio and end parameter are written in full so that a thin ellipse keeps its size and a whole turn reads back closed. Part of #1299. --- crates/cad/src/scene.rs | 91 +++++++++++++++++++++++++- crates/cad/src/tests.rs | 127 +++++++++++++++++++++++++++++++++++-- docs/file-format-parity.md | 2 +- docs/gaps.md | 2 +- 4 files changed, 215 insertions(+), 7 deletions(-) diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index f75d437763..58e0350599 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -10,7 +10,7 @@ use kurbo::PathEl; use vectorcraft_color::Paint; use vectorcraft_doc::{AppearanceItem, Dash, Document, ImageObject, Node, NodeKind, StrokeLayer, SymbolBoxes, TextKind, TextObject, Unit}; use vectorcraft_effects::stroke; -use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Vec2}; use crate::aci::nearest_aci; use crate::writer::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, fixed}; @@ -184,6 +184,46 @@ fn circular_subpath(sub: &Sub) -> Option { Some(CircularSub { centre, radius, samples }) } +/// A closed subpath that is the four-cubic circle under an affine map: an ellipse, or a circle +/// scaled out of proportion. `u` and `v` are the conjugate semi-diameters through its first two +/// anchors. +struct EllipticalSub { + centre: Point, + u: Vec2, + v: Vec2, +} + +/// Fit a closed subpath of four cubics to one ellipse. Its anchors give the center and two +/// conjugate semi-diameters; the subpath mapped by their inverse must pass [`circular_subpath`] as +/// the unit circle, so the same tolerance and turn checks apply. +fn elliptical_subpath(sub: &Sub) -> Option { + if !sub.closed || sub.segs.len() != 4 { + return None; + } + let (a0, a1, a2) = (sub.start, sub.segs.first()?.end(), sub.segs.get(1)?.end()); + let centre = a0.midpoint(a2); + let (u, v) = (a0 - centre, a1 - centre); + let det = u.cross(v); + let scale2 = u.hypot2().max(v.hypot2()); + if !det.is_finite() || !scale2.is_finite() || det.abs() <= scale2 * 1e-9 { + return None; + } + let unit = |p: Point| { + let d = p - centre; + Point::new(d.cross(v) / det, u.cross(d) / det) + }; + let mut segs = Vec::with_capacity(4); + for seg in &sub.segs { + let Seg::Cubic(a, b, to) = *seg else { return None }; + segs.push(Seg::Cubic(unit(a), unit(b), unit(to))); + } + let circle = circular_subpath(&Sub { start: unit(sub.start), segs, closed: true })?; + if circle.centre.to_vec2().hypot() > 5e-4 || (circle.radius - 1.0).abs() > 5e-4 { + return None; + } + Some(EllipticalSub { centre, u, v }) +} + fn angle_deg(p: Point, centre: Point) -> f64 { (p.y - centre.y).atan2(p.x - centre.x).to_degrees().rem_euclid(360.0) } @@ -764,6 +804,8 @@ impl<'a> Scene<'a> { // Native circles/arcs are preferred by CAD/CAM software. In R12, however, a // stroked curve must stay on the flattened POLYLINE path so groups 40/41 retain // its width. Non-circular curves continue through the existing fallback. + } else if v.handles() && self.elliptical(&sub, style) { + // R13 and later write an ellipse as a native ELLIPSE. } else if v.handles() { self.spline(&sub, style); } else { @@ -901,6 +943,53 @@ impl<'a> Scene<'a> { true } + /// Write a recognized elliptical subpath as a native DXF ELLIPSE (R13 and later): its center, + /// the end of its major axis relative to the center, and the minor to major ratio. Returns + /// false when the curve is not an ellipse, leaving the caller to write it as a spline. + fn elliptical(&mut self, sub: &Sub, style: &EntityStyle) -> bool { + let Some(last) = sub.segs.last().map(|s| s.end()) else { return false }; + if !sub.closed || last.distance(sub.start) > 1e-9 { + return false; + } + let Some(ellipse) = elliptical_subpath(sub) else { return false }; + let centre = self.to_dxf * ellipse.centre; + let u = self.to_dxf * (ellipse.centre + ellipse.u) - centre; + let v = self.to_dxf * (ellipse.centre + ellipse.v) - centre; + // The semi-axes are the square roots of the eigenvalues of [[a, b], [b, d]] = u u^T + v v^T. + let (a, b, d) = (u.x * u.x + v.x * v.x, u.x * u.y + v.x * v.y, u.y * u.y + v.y * v.y); + let mean = (a + d) / 2.0; + let spread = ((a - d) / 2.0).hypot(b); + let (major, minor) = ((mean + spread).sqrt(), (mean - spread).max(0.0).sqrt()); + let angle = 0.5 * (2.0 * b).atan2(a - d); + let axis = Vec2::new(major * angle.cos(), major * angle.sin()); + let ratio = (minor / major).min(1.0); + // A thinner ellipse stays a spline: DXF readers such as ezdxf need a ratio of 1e-6 or more. + if !centre.x.is_finite() || !centre.y.is_finite() || !axis.x.is_finite() || !axis.y.is_finite() || !ratio.is_finite() || ratio < 1e-6 { + return false; + } + + // The drawing extents take the ellipse's bounding box: half-widths hypot(u.x, v.x) and + // hypot(u.y, v.y) about the center. + let (c, eu, ev) = (ellipse.centre, ellipse.u, ellipse.v); + let (hx, hy) = (eu.x.hypot(ev.x), eu.y.hypot(ev.y)); + for p in [Point::new(c.x - hx, c.y), Point::new(c.x + hx, c.y), Point::new(c.x, c.y - hy), Point::new(c.x, c.y + hy)] { + self.pt(p); + } + + let layer = self.layer.clone(); + let h = self.handle(); + self.e.entity("ELLIPSE", h, fixed::MODEL_RECORD, &layer, style, "AcDbEllipse"); + self.e.xyz(10, centre.x, centre.y); + self.e.xyz(11, axis.x, axis.y); + self.e.normal(); + // The ratio and the end parameter are written in full: rounded to six decimals, a thin + // ellipse's minor axis would change size, and a whole turn would read back as an open curve. + self.e.raw(40, &ratio.to_string()); + self.e.num(41, 0.0); + self.e.raw(42, &std::f64::consts::TAU.to_string()); + true + } + /// A curved subpath as one cubic B-spline whose clamped knots repeat at every joint, so it /// passes through every anchor (straight segments become straight cubics). fn spline(&mut self, sub: &Sub, style: &EntityStyle) { diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index d0abd13e84..3f5c73024a 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, CharStyle, Dash, Document, ImageBlob, ImageObject, Node, NodeKind, TextObject, Unit}; -use vectorcraft_geom::{Affine, PathData, Point, Rect, shapes}; +use vectorcraft_geom::{Affine, ParamCurve, PathData, Point, Rect, Shape, shapes}; use crate::*; @@ -208,10 +208,129 @@ fn circles_and_circular_arcs_are_native_dxf_entities() { assert_eq!((all(&e[1], 10), all(&e[1], 20), all(&e[1], 40)), (vec![120.0], vec![50.0], vec![30.0]), "{version:?}"); assert_eq!((all(&e[1], 50), all(&e[1], 51)), (vec![0.0], vec![90.0]), "{version:?}"); } +} - // An actual ellipse is not close enough to a circle and remains a spline. - let ellipse = doc_with(|d| vec![path(d, shapes::ellipse(Rect::new(20.0, 20.0, 100.0, 60.0)), Paint::None, Paint::solid(Color::BLACK), 1.0)]); - assert_eq!(kinds(&export(&ellipse, &opts(&ellipse)).unwrap()), ["SPLINE"]); +/// The path `p` with `xf` applied. +fn transformed(p: &PathData, xf: Affine) -> PathData { + PathData::from_bezpath(&(xf * p.to_bezpath())) +} + +fn close_to(a: &[f64], b: &[f64], tol: f64) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() <= tol) +} + +#[test] +fn ellipses_and_unevenly_scaled_circles_are_native_ellipses() { + let circle = shapes::ellipse(Rect::new(20.0, 20.0, 80.0, 80.0)); + let d = doc_with(|d| { + let stroke = || Paint::solid(Color::BLACK); + vec![ + // 80 × 40 pt about (60, 40): DXF center (60, 60), major axis (40, 0), ratio 0.5. + path(d, shapes::ellipse(Rect::new(20.0, 20.0, 100.0, 60.0)), Paint::None, stroke(), 1.0), + // A 60 pt circle scaled 150% across about (50, 50): 90 × 60 pt, ratio 2/3. + path( + d, + transformed(&circle, Affine::translate((50.0, 50.0)) * Affine::scale_non_uniform(1.5, 1.0) * Affine::translate((-50.0, -50.0))), + Paint::None, + stroke(), + 1.0, + ), + // The first ellipse turned 30° about its center, filled: the outline is the ellipse too. + path( + d, + transformed(&shapes::ellipse(Rect::new(20.0, 20.0, 100.0, 60.0)), Affine::rotate_about(30f64.to_radians(), Point::new(60.0, 40.0))), + Paint::solid(Color::BLACK), + Paint::None, + 0.0, + ), + ] + }); + for version in DxfVersion::ALL.into_iter().filter(|version| *version >= DxfVersion::R13) { + let out = export(&d, &DxfOptions { version, ..opts(&d) }).unwrap(); + let e = entities(&out); + assert_eq!(e.iter().map(|x| kind(x)).collect::>(), ["ELLIPSE", "ELLIPSE", "ELLIPSE", "HATCH"], "{version:?}"); + let ellipse = |x: &Pairs| (all(x, 10), all(x, 20), all(x, 11), all(x, 21), all(x, 40), all(x, 41), all(x, 42)); + let (cx, cy, mx, my, ratio, start, end) = ellipse(&e[0]); + assert_eq!((cx, cy, mx, my, ratio), (vec![60.0], vec![60.0], vec![40.0], vec![0.0], vec![0.5]), "{version:?}"); + assert!(close_to(&start, &[0.0], 1e-9) && close_to(&end, &[std::f64::consts::TAU], 1e-12), "{version:?}: a whole turn"); + let (cx, cy, mx, my, ratio, ..) = ellipse(&e[1]); + assert!(close_to(&[cx, cy, mx, my, ratio].concat(), &[50.0, 50.0, 45.0, 0.0, 2.0 / 3.0], 1e-6), "{version:?}: {:?}", e[1]); + // Turned 30° counterclockwise on screen, so clockwise with DXF's y up. + let (cx, cy, mx, my, ratio, ..) = ellipse(&e[2]); + let (cos, sin) = (30f64.to_radians().cos(), 30f64.to_radians().sin()); + assert!(close_to(&[cx, cy, mx, my, ratio].concat(), &[60.0, 60.0, 40.0 * cos, -40.0 * sin, 0.5], 1e-6), "{version:?}: {:?}", e[2]); + assert!(e[0].contains(&(100, "AcDbEllipse".into())), "{version:?}"); + } + // R12 has no ELLIPSE: the curves are flattened polylines. + let r12 = kinds(&export(&d, &DxfOptions { version: DxfVersion::R12, ..opts(&d) }).unwrap()); + assert!(!r12.iter().any(|k| k == "ELLIPSE") && r12.iter().any(|k| k == "POLYLINE"), "{r12:?}"); + // A thin ellipse keeps its ratio in full (six decimals would write 0.000002). + let thin = doc_with(|d| vec![path(d, shapes::ellipse(Rect::new(0.0, 50.0, 200.0, 50.0003)), Paint::None, Paint::solid(Color::BLACK), 1.0)]); + let e = entities(&export(&thin, &opts(&thin)).unwrap()); + assert_eq!(kind(&e[0]), "ELLIPSE"); + assert!(close_to(&all(&e[0], 40), &[1.5e-6], 1e-10), "{:?}", e[0]); +} + +#[test] +fn exported_ellipses_read_back_as_the_same_ellipse() { + let xf = Affine::rotate_about(30f64.to_radians(), Point::new(60.0, 40.0)); + let d = doc_with(|d| { + vec![path(d, transformed(&shapes::ellipse(Rect::new(20.0, 20.0, 100.0, 60.0)), xf), Paint::None, Paint::solid(Color::BLACK), 1.0)] + }); + let out = export(&d, &opts(&d)).unwrap(); + assert_eq!(kinds(&out), ["ELLIPSE"]); + let o = ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() }; + let back = import(&out.bytes, &o).unwrap().document; + let mut paths = vec![]; + back.walk(|n| { + if let NodeKind::Path { path, .. } = &n.kind { + paths.push(path.to_bezpath()); + } + }); + assert_eq!(paths.len(), 1); + assert!(paths[0].elements().last().is_some_and(|el| matches!(el, kurbo::PathEl::ClosePath)), "the ellipse reads back closed"); + // Every point of the curve read back lies on the 80 × 40 pt ellipse turned 30°, once both are centered. + let bp = &paths[0]; + let found = bp.bounding_box().center(); + let inverse = xf.inverse(); + let original = Point::new(60.0, 40.0); + for seg in bp.segments() { + for i in 0..=16 { + let p = seg.eval(f64::from(i) / 16.0) - found.to_vec2() + original.to_vec2(); + let q = inverse * p; + let r = ((q.x - 60.0) / 40.0).hypot((q.y - 40.0) / 20.0); + assert!((r - 1.0).abs() < 1e-3, "{p:?} is off the ellipse ({r})"); + } + } +} + +#[test] +fn closed_four_cubic_shapes_that_are_not_writable_ellipses_stay_splines() { + // A rounded square: four cubics through the ellipse's anchors with longer handles. + let (c, r, k) = (Point::new(50.0, 50.0), 30.0, 30.0 * 0.8); + let mut squircle = vectorcraft_geom::BezPath::new(); + squircle.move_to(Point::new(c.x + r, c.y)); + squircle.curve_to(Point::new(c.x + r, c.y - k), Point::new(c.x + k, c.y - r), Point::new(c.x, c.y - r)); + squircle.curve_to(Point::new(c.x - k, c.y - r), Point::new(c.x - r, c.y - k), Point::new(c.x - r, c.y)); + squircle.curve_to(Point::new(c.x - r, c.y + k), Point::new(c.x - k, c.y + r), Point::new(c.x, c.y + r)); + squircle.curve_to(Point::new(c.x + k, c.y + r), Point::new(c.x + r, c.y + k), Point::new(c.x + r, c.y)); + squircle.close_path(); + // An egg: one half wider than the other. + let egg = shapes::ellipse(Rect::new(110.0, 20.0, 190.0, 60.0)).to_bezpath(); + let mut els: Vec = egg.elements().to_vec(); + if let Some(kurbo::PathEl::CurveTo(a, b, _)) = els.get_mut(1) { + a.x -= 10.0; + b.x -= 10.0; + } + let d = doc_with(|d| { + vec![ + path(d, PathData::from_bezpath(&squircle), Paint::None, Paint::solid(Color::BLACK), 1.0), + path(d, PathData::from_bezpath(&kurbo::BezPath::from_vec(els)), Paint::None, Paint::solid(Color::BLACK), 1.0), + // An ellipse thinner than the smallest ratio DXF readers take (5e-7 against 1e-6). + path(d, shapes::ellipse(Rect::new(0.0, 90.0, 200.0, 90.0001)), Paint::None, Paint::solid(Color::BLACK), 1.0), + ] + }); + assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE", "SPLINE", "SPLINE"]); } #[test] diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index dc23c77b7e..ffab9f5859 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -98,7 +98,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CID-keyed CJK type not read; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as ``, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`) | -| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). CNC preset and VCarve QA remain open | +| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; closed four-cubic ellipses, and circles scaled out of proportion, export as ELLIPSE in R13–2018; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). CNC preset and VCarve QA remain open | | DWG | open, export | no | no | no open spec; DXF instead | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) | | PSD | open, place, export | yes (merged image, every mode and depth) | yes (layered, max editability) | placing as layers (Photoshop Import Options) missing; the embedded ICC profile's tags are 4-byte aligned (#1584) | diff --git a/docs/gaps.md b/docs/gaps.md index e42ecaed02..0b31e2a484 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -254,7 +254,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done:** Numeric fields keep a text drag's start when the pointer gains focus and movement exceeds the click threshold (#1326, in part). A completed focus click selects the whole value; keyboard focus, double-click and numeric stepping remain regression-tested. Short movements still classified as clicks can select all; that case remains open. -- **Done:** DXF reads control-point SPLINE closure (#1299 follow-up after #1320); open curves keep their open state. DXF export now recognizes circular cubic paths conservatively and writes native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE, and a non-circular ellipse keeps the existing fallback. CNC preset and VCarve QA remain open. Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture. Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. +- **Done:** DXF reads control-point SPLINE closure (#1299 follow-up after #1320); open curves keep their open state. DXF export now recognizes circular cubic paths conservatively and writes native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE. A closed four-cubic ellipse, or a circle scaled out of proportion, is written as a native ELLIPSE in R13 and later; R12 keeps the existing fallback. CNC preset and VCarve QA remain open. Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture. Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. - **Done:** Simplify and Add Anchor Points clear stale component selections on rewritten paths; Simplify previews and reports original/new point counts (#1272). - **Done:** Object › Path › Simplify opens its slider at the Auto-Simplify level for the selection and previews that result, as the [manual-simplify page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html) describes; simplifying only a Direct Selection part of a path is done too (G1). From d318a775607dceb0ad5e8ed7c7d11fa5cf029996 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 23:32:34 -0700 Subject: [PATCH 015/260] DXF export: Alter Paths for Appearance outlines only strokes a CAD line can't draw Alter Paths for Appearance wrote every stroke as its filled outline, so a 1 pt circle became two circles and a hatch, and an open arc became a closed outline and a hatch: two cut lines where a CAM program expects one. The option now outlines only the strokes a line can't draw: the ones Preserve Appearance outlines, strokes wider than the widest lineweight (2.11 mm, to the hundredth), and every stroke in R13 and R14, which have no lineweights. Other strokes stay CIRCLE, ARC, SPLINE and LWPOLYLINE entities with their lineweights; R12 keeps them as POLYLINEs with their width. A dashed stroke whose offset starts part way into its pattern is now outlined with Preserve Appearance and with Alter Paths: a linetype always starts at the start of its pattern, so the dashes were written in the wrong place. --- crates/cad/src/lib.rs | 7 ++- crates/cad/src/scene.rs | 35 ++++++++++++-- crates/cad/src/tests.rs | 71 +++++++++++++++++++++++++++-- crates/engine/src/cmd/fileio/dxf.rs | 4 +- docs/gaps.md | 1 + docs/mcp.md | 6 ++- 6 files changed, 112 insertions(+), 12 deletions(-) diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index 4afe84e332..3fc4bcb3b0 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -233,7 +233,8 @@ impl RasterFormat { #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Preserve { /// Type becomes glyph outlines; strokes a plain CAD line can't draw (aligned inside or - /// outside, width profiles, arrowheads, fitted dashes) become their filled outlines; brush + /// outside, width profiles, arrowheads, fitted dashes, dashes offset into their pattern) + /// become their filled outlines; brush /// strokes become their brush art. #[default] Appearance, @@ -277,7 +278,9 @@ pub struct DxfOptions { pub colors: ColorDepth, pub raster: RasterFormat, pub preserve: Preserve, - /// Alter Paths for Appearance: every stroke is written as the filled area it paints. + /// Alter Paths for Appearance: a stroke a CAD line can't draw (one [`Preserve::Appearance`] + /// outlines, one wider than the widest lineweight, or any stroke in R13 and R14, which have + /// no lineweights) is written as the filled area it paints. pub alter_paths: bool, /// Type is written as glyph outlines (always with [`Preserve::Appearance`]). pub outline_text: bool, diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index 58e0350599..a292d5a7f5 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -273,6 +273,17 @@ const MAX_ENTITIES: u32 = 10_000_000; const MAX_COORD: f64 = 1e9; const MAX_POINTS: usize = 4_000_000; +/// Do the dashes of `d` start at the start of their pattern, as a linetype's do? A pattern of +/// odd length repeats twice in its linetype. +fn starts_with_pattern(d: &Dash) -> bool { + if !d.is_dashed() || !d.offset.is_finite() { + return true; + } + let period = d.pattern.iter().sum::<f64>() * if d.pattern.len() % 2 == 1 { 2.0 } else { 1.0 }; + let phase = d.offset.rem_euclid(period); + phase.min(period - phase) <= period * 1e-9 +} + /// `bp` flattened into polygons (each closing implicitly), consecutive repeats dropped. fn polygons(bp: &BezPath) -> Vec<Vec<Point>> { // Far outside any drawing, a curve flattens to millions of points at this tolerance. @@ -652,8 +663,7 @@ impl<'a> Scene<'a> { /// The DXF lineweight nearest to `width` points (scaled with the drawing when asked). fn lineweight(&mut self, width: f64) -> i32 { - let scale = if self.o.scale_lineweights { self.o.scale } else { 1.0 }; - let hundredths = width * 2540.0 / 72.0 * scale; + let hundredths = self.hundredths(width); let max = LINEWEIGHTS[LINEWEIGHTS.len() - 1]; if hundredths > f64::from(max) + 5.0 { self.warn(WIDE_LINES); @@ -661,6 +671,21 @@ impl<'a> Scene<'a> { LINEWEIGHTS.into_iter().min_by(|a, b| (f64::from(*a) - hundredths).abs().total_cmp(&(f64::from(*b) - hundredths).abs())).unwrap_or(max) } + /// `width` points in hundredths of a millimetre, the unit of DXF lineweights (scaled with + /// the drawing when asked). + fn hundredths(&self, width: f64) -> f64 { + let scale = if self.o.scale_lineweights { self.o.scale } else { 1.0 }; + width * 2540.0 / 72.0 * scale + } + + /// Can a CAD line draw a plain stroke `width` points wide in this version? R12 polylines + /// carry their width, R13 and R14 have no lineweights, and from 2000 a lineweight holds up + /// to 2.11 mm, to the hundredth. + fn line_keeps_width(&self, width: f64) -> bool { + let v = self.o.version; + !v.handles() || (v.r2000() && self.hundredths(width).round() <= f64::from(LINEWEIGHTS[LINEWEIGHTS.len() - 1])) + } + /// A linetype for dash pattern `d` (one per distinct pattern). fn linetype(&mut self, d: &Dash) -> String { let mut lengths: Vec<f64> = d.pattern.iter().map(|v| v * self.k).collect(); @@ -713,7 +738,11 @@ impl<'a> Scene<'a> { } let Some(rgb) = self.paint_rgb(&st.paint) else { return }; let plain = stroke::is_plain(st); - if self.o.alter_paths || (appearance && !plain) { + // A linetype has no phase: dashes that start part way into their pattern need outlines. + let lined = plain && st.dash.as_ref().is_none_or(starts_with_pattern); + // Alter Paths for Appearance outlines a stroke only when a line can't draw it. + let altered = self.o.alter_paths && !(lined && self.line_keeps_width(st.width)); + if altered || (appearance && !lined) { let region = stroke::outline_region(&PathData::from_bezpath(bp), rule, st); let style = self.style(rgb, st.opacity, None, None); self.area(®ion.to_bezpath(), FillRule::NonZero, &style, true); diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index 3f5c73024a..aff8489c44 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -611,14 +611,44 @@ fn dashes_become_linetypes_and_opacity_transparency() { #[test] fn alter_paths_writes_strokes_as_filled_outlines() { - let d = shapes_doc(); - let out = export(&d, &DxfOptions { alter_paths: true, ..opts(&d) }).unwrap(); - // Each fill and stroke: its outlines, then its hatch. let fill = ["LWPOLYLINE", "HATCH"]; let rect_stroke = ["LWPOLYLINE", "LWPOLYLINE", "HATCH"]; + // Strokes a lineweight draws stay lines: the rectangle, the circle and an open arc. + let mut d = shapes_doc(); + let c = Point::new(150.0, 95.0); + let k = 20.0 * shapes::KAPPA; + let mut arc = vectorcraft_geom::BezPath::new(); + arc.move_to(Point::new(c.x + 20.0, c.y)); + arc.curve_to(Point::new(c.x + 20.0, c.y - k), Point::new(c.x + k, c.y - 20.0), Point::new(c.x, c.y - 20.0)); + let arc = path(&mut d, PathData::from_bezpath(&arc), Paint::None, Paint::solid(Color::BLACK), 1.0); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, arc).unwrap(); + let out = export(&d, &DxfOptions { alter_paths: true, ..opts(&d) }).unwrap(); + assert_eq!(kinds(&out), [&fill[..], &["LWPOLYLINE", "CIRCLE", "ARC"]].concat()); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + // R12 polylines carry any width, so its strokes stay lines too. + let r12 = export(&d, &DxfOptions { alter_paths: true, version: DxfVersion::R12, ..opts(&d) }).unwrap(); + assert!(!kinds(&r12).iter().any(|k| k == "HATCH")); + assert!(entities(&r12).iter().any(|e| kind(e) == "POLYLINE" && get(e, 40) == Some("2"))); + // R13 and R14 have no lineweights: every stroke becomes its outline, then its hatch. + let d = shapes_doc(); + let out = export(&d, &DxfOptions { alter_paths: true, version: DxfVersion::R14, ..opts(&d) }).unwrap(); assert_eq!(kinds(&out), [&fill[..], &rect_stroke, &["CIRCLE", "CIRCLE", "HATCH"]].concat()); // The rectangle's stroke: an outer and an inner boundary. assert_eq!(get(&entities(&out)[4], 91), Some("2")); + // A stroke wider than the widest lineweight (2.11 mm) is outlined at its true width. + let wide = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), Paint::None, Paint::solid(Color::BLACK), 8.0)]); + let out = export(&wide, &DxfOptions { alter_paths: true, ..opts(&wide) }).unwrap(); + assert_eq!(kinds(&out), rect_stroke); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let lines = export(&wide, &opts(&wide)).unwrap(); + assert_eq!(kinds(&lines), ["LWPOLYLINE"]); + assert!(lines.warnings.iter().any(|w| w.contains("2.11 mm"))); + // To the hundredth of a millimetre: 6 pt (2.117 mm) is outlined, 5.98 pt (2.110 mm) is a line. + for (width, expected) in [(6.0, &rect_stroke[..]), (5.98, &["LWPOLYLINE"][..])] { + let d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), Paint::None, Paint::solid(Color::BLACK), width)]); + assert_eq!(kinds(&export(&d, &DxfOptions { alter_paths: true, ..opts(&d) }).unwrap()), expected, "{width} pt"); + } // Preserve Appearance outlines only the strokes a line can't draw. let mut d = shapes_doc(); let rect = d.layers[0].children().and_then(|c| c.first()).map(|n| n.id).unwrap(); @@ -629,6 +659,41 @@ fn alter_paths_writes_strokes_as_filled_outlines() { let editable = export(&d, &DxfOptions { preserve: Preserve::Editability, ..opts(&d) }).unwrap(); assert_eq!(kinds(&editable), ["LWPOLYLINE", "HATCH", "LWPOLYLINE", "CIRCLE"]); assert!(editable.warnings.iter().any(|w| w.contains("stroke alignment"))); + // With Maximize Editability, Alter Paths outlines that stroke and keeps the circle a line. + let altered = export(&d, &DxfOptions { preserve: Preserve::Editability, alter_paths: true, ..opts(&d) }).unwrap(); + assert_eq!(kinds(&altered), [&fill[..], &rect_stroke, &["CIRCLE"]].concat()); + assert!(altered.warnings.is_empty(), "{:?}", altered.warnings); +} + +#[test] +fn dashes_that_start_part_way_into_their_pattern_are_outlined() { + let dashed = |offset: f64| { + doc_with(|d| { + let mut n = path(d, shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), Paint::None, Paint::solid(Color::BLACK), 1.0); + if let Some(st) = n.appearance.stroke_mut() { + st.dash = Some(Dash { pattern: vec![6.0, 3.0, 2.0], offset, align_corners: false }); + } + vec![n] + }) + }; + // A linetype starts at the start of its pattern: an offset of a whole period (the odd + // pattern twice) keeps the line, any other offset needs the dashes' outlines and a hatch. + for (offset, outlined) in [(0.0, false), (22.0, false), (4.0, true), (11.0, true)] { + let d = dashed(offset); + let k = kinds(&export(&d, &opts(&d)).unwrap()); + if outlined { + assert!(k.len() > 2 && k.last().is_some_and(|k| k == "HATCH"), "offset {offset}: {k:?}"); + } else { + assert_eq!(k, ["LWPOLYLINE"], "offset {offset}"); + } + let altered = kinds(&export(&d, &DxfOptions { alter_paths: true, ..opts(&d) }).unwrap()); + assert_eq!(altered, k, "offset {offset}, Alter Paths"); + } + // Maximize Editability keeps the line and its linetype. + let d = dashed(4.0); + let editable = export(&d, &DxfOptions { preserve: Preserve::Editability, ..opts(&d) }).unwrap(); + assert_eq!(kinds(&editable), ["LWPOLYLINE"]); + assert_eq!(get(&entities(&editable)[0], 6), Some("DASHED1")); } fn text_doc(text: &str, size: f64) -> Document { diff --git a/crates/engine/src/cmd/fileio/dxf.rs b/crates/engine/src/cmd/fileio/dxf.rs index a569f1b4c8..4320cbb9ca 100644 --- a/crates/engine/src/cmd/fileio/dxf.rs +++ b/crates/engine/src/cmd/fileio/dxf.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export DXF", [], None, - "{path?, version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (every stroke as its filled outline), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}", + "{path?, version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}", has_doc, export_dxf )] @@ -64,7 +64,7 @@ pub(super) const OPTIONS: &[FormatOption] = &[ name: "alterPaths", ty: "boolean", default: "false", - description: "Alter Paths for Appearance: every stroke as its filled outline", + description: "Alter Paths for Appearance: strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14", }, FormatOption { name: "outlineText", ty: "boolean", default: "false", description: "type as glyph outlines (always with preserve: appearance)" }, FormatOption { name: "selectedOnly", ty: "boolean", default: "false", description: "only the selected objects, in their layers" }, diff --git a/docs/gaps.md b/docs/gaps.md index 0b31e2a484..1fb18246a5 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -254,6 +254,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done:** Numeric fields keep a text drag's start when the pointer gains focus and movement exceeds the click threshold (#1326, in part). A completed focus click selects the whole value; keyboard focus, double-click and numeric stepping remain regression-tested. Short movements still classified as clicks can select all; that case remains open. +- **Done:** DXF reads control-point SPLINE closure (#1299 follow-up after #1320); open curves keep their open state. DXF export now recognizes circular cubic paths conservatively and writes native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE, and a non-circular ellipse keeps the existing fallback. Alter Paths for Appearance outlines only the strokes a CAD line can't draw (aligned, profiled, offset dashes, wider than 2.11 mm, or in R13 and R14), so a 1 pt circle or arc stays a CIRCLE or ARC. CNC preset and VCarve QA remain open. Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture. Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. - **Done:** DXF reads control-point SPLINE closure (#1299 follow-up after #1320); open curves keep their open state. DXF export now recognizes circular cubic paths conservatively and writes native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE. A closed four-cubic ellipse, or a circle scaled out of proportion, is written as a native ELLIPSE in R13 and later; R12 keeps the existing fallback. CNC preset and VCarve QA remain open. Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture. Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. - **Done:** Simplify and Add Anchor Points clear stale component selections on rewritten paths; Simplify previews and reports original/new point counts (#1272). diff --git a/docs/mcp.md b/docs/mcp.md index 76f8648ac3..4a37804b6e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3841,8 +3841,10 @@ from the bottom-left corner of the first artboard (or `artboard`), in drawing un 1 mm = 1 unit, which sets `$INSUNITS`); `scaleLineweights` scales the lineweights with them. `colors` is `8`, `16` or `256` indexed colours, or `true` (default; true colour with the nearest index, DXF 2004 and later). `preserve: "appearance"` (default) writes type as glyph outlines and the strokes a CAD line can't draw (inside or outside, -width profiles, arrowheads) as filled outlines; `"editability"` keeps type as text and every stroke a line. -`alterPaths` writes every stroke as its filled outline, `outlineText` outlines type, `selectedOnly` writes only the +width profiles, arrowheads, dashes offset into their pattern) as filled outlines; `"editability"` keeps type as text +and every stroke a line. `alterPaths` writes as filled outlines those strokes (with `"editability"` too), strokes +wider than the widest lineweight (2.11 mm), and every stroke in R13 and R14, which have no lineweights; it keeps other +strokes as lines. `outlineText` outlines type, `selectedOnly` writes only the selected objects in their layers (every export takes it), and `useArtboards: true` writes one drawing per chosen artboard holding the art over it. What DXF can't hold (gradients and patterns as one colour, blending, opacity masks, raster effects, clipping) comes back in `warnings`. In R13 and later, an image that can't be decoded is left out with From baaffd63e791c88c71f060121bdb9e9d0533624d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 22:25:03 -0700 Subject: [PATCH 016/260] Blob Brush: Tool Options set the brush's Angle and Roundness Blob Brush Tool Options gain Angle (-180 to 180 degrees, 0 by default) and Roundness (0 to 100 percent, 100 by default), with a preview of the tip and three dabs; a drag in the preview square sets the Angle. The elliptical tip keeps its angle on the page along a stroke, a 0 percent tip is drawn 0.1 percent as wide as it is long, and Size set to Pressure still varies its size. path.blob takes angle and roundness, and both values are kept with the tool's options. While a non-round tip drags, the Blob Brush shows the outline of the area it covers with its length label, and an Alt drag that smooths shows the Smooth tool's thin line. --- crates/engine/src/cmd/draw2/commands.rs | 2 +- crates/engine/src/cmd/draw2/freehand.rs | 30 +++++++-- crates/engine/src/tests/draw2.rs | 68 ++++++++++++++++++++ crates/engine/src/tests/toolsettings.rs | 15 +++++ crates/tools/src/draw2.rs | 22 ++++++- crates/tools/src/draw2/gesture.rs | 42 ++++++++---- crates/tools/src/draw2/gesture/tests.rs | 47 ++++++++++++++ crates/tools/src/settings.rs | 2 +- crates/ui-egui/src/dialogs/freehand.rs | 54 +++++++++++++++- crates/ui-egui/src/dialogs/freehand/tests.rs | 25 ++++++- docs/control-protocol.md | 3 +- docs/mcp.md | 2 +- docs/target-app-parity.md | 5 +- 13 files changed, 286 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index d34a79afb4..6946463e3e 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> { "Blob Brush", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}", + "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}", has_doc, blob ), diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 6267c8e2c9..56ff0f3a53 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -373,8 +373,22 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> { if !(size.is_finite() && size > 0.0) { return Err(bad(C, "size must be positive")); } - let pressure = size_pressure(p, &samples, C)?; + let angle = number_or(p, "angle", 0.0, C)?; + let roundness = number_or(p, "roundness", 100.0, C)?; + if !angle.is_finite() || !roundness.is_finite() { + return Err(bad(C, "angle and roundness must be finite")); + } + let angle = angle.clamp(-180.0, 180.0); + let roundness = roundness.clamp(0.0, 100.0); + let tip = vectorcraft_tools::draw2::blob_tip(angle, roundness); + let squash = tip.inverse(); + // Width profiles use distance along the spine, so measure pressure on the same squashed + // points that the outline reads for a non-round tip. + let mapped_samples: Vec<(Point, Option<f64>)> = + if roundness < 100.0 { samples.iter().map(|(pt, pressure)| (squash * *pt, *pressure)).collect() } else { samples.clone() }; + let pressure = size_pressure(p, &mapped_samples, C)?; let pts: Vec<Point> = samples.into_iter().map(|(pt, _)| pt).collect(); + let mapped_pts: Vec<Point> = mapped_samples.into_iter().map(|(pt, _)| pt).collect(); // The widest the brush gets: the area merges look in. let reach = pressure.as_ref().map_or(size, |(_, v)| size + v); // With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil @@ -384,9 +398,12 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> { None | Some(Value::Null) => None, Some(_) => Some(number_or(p, "fidelity", 0.0, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0)), }; - let spine = |tol: Option<f64>| match tol { - Some(tol) => PathData::single(fit_freehand(&pts, tol, false)), - None => PathData::single(SubPath::polyline(&pts, false)), + let spine = |tol: Option<f64>| { + let path = match tol { + Some(tol) => PathData::single(fit_freehand(&pts, tol, false)), + None => PathData::single(SubPath::polyline(&pts, false)), + }; + if roundness < 100.0 { path.transformed(squash) } else { path } }; let region = match (&pressure, pts.len() > 1) { (Some((prof, variation)), true) => { @@ -400,15 +417,16 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> { } } // A click: one dab as wide as the pen pressed. - (Some((prof, variation)), false) => brush_region(&pts, vectorcraft_tools::draw2::pressure_size(size, *variation, prof.at(0.0))), + (Some((prof, variation)), false) => brush_region(&mapped_pts, vectorcraft_tools::draw2::pressure_size(size, *variation, prof.at(0.0))), (None, _) => { let fitted = fidelity .filter(|_| pts.len() > 1) .map(|tol| po::outline_stroke(&spine(Some(tol)), size, Cap::Round, Join::Round, 4.0)) .filter(|r| !r.is_empty()); - fitted.unwrap_or_else(|| brush_region(&pts, size)) + fitted.unwrap_or_else(|| brush_region(&mapped_pts, size)) } }; + let region = if roundness < 100.0 { region.transformed(tip) } else { region }; if region.is_empty() { return Err(EngineError::Other("empty brush stroke".into())); } diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 935ae78a91..47adaf47cd 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -38,6 +38,74 @@ fn paths(s: &Session) -> Vec<(NodeId, PathData)> { v } +#[test] +fn blob_tip_angle_changes_horizontal_extent_and_stays_page_oriented() { + let bounds = |points: serde_json::Value, angle: i32, roundness: i32| { + let mut s = session(); + s.execute("path.blob", &json!({"points": points, "size": 40, "angle": angle, "roundness": roundness, "merge": false})).unwrap(); + paths(&s)[0].1.control_bounds().unwrap() + }; + let flat = bounds(json!([[100, 200], [300, 200]]), 0, 25); + let tilted = bounds(json!([[100, 200], [300, 200]]), 45, 25); + assert!(flat.height() < 15.0, "flat tip height: {}", flat.height()); + assert!(tilted.height() > 25.0, "tilted tip height: {}", tilted.height()); + let vertical = bounds(json!([[200, 100], [200, 300]]), 45, 25); + assert!((vertical.width() - tilted.height()).abs() < 2.0); + let round = bounds(json!([[100, 200], [300, 200]]), 45, 100); + assert!((round.height() - 40.0).abs() < 2.0); +} + +#[test] +fn blob_pressure_peak_stays_at_the_sample_with_a_flat_tip() { + use kurbo::ParamCurveNearest; + use vectorcraft_geom::Point; + + let mut s = session(); + s.execute( + "path.blob", + &json!({"points": [[100, 100, 0.0], [200, 100, 1.0], [200, 200, 0.0]], + "size": 10, "sizeMode": "pressure", "sizeVariation": 8, + "roundness": 25, "merge": false}), + ) + .unwrap(); + let outline = &paths(&s)[0].1; + let near_peak = Point::new(200.0, 110.0); + let past_peak = Point::new(200.0, 140.0); + let distance = |p: Point| outline.to_bezpath().segments().map(|seg| seg.nearest(p, 0.01).distance_sq.sqrt()).fold(f64::INFINITY, f64::min); + assert!(distance(near_peak) > distance(past_peak), "pressure must narrow after the corner sample"); +} + +#[test] +fn blob_tip_zero_and_invalid_values_are_safe() { + let mut s = session(); + s.execute("path.blob", &json!({"points": [[100, 100], [300, 100]], "size": 40, "roundness": 0})).unwrap(); + let b = paths(&s)[0].1.control_bounds().unwrap(); + assert!(b.height().is_finite() && b.height() > 0.0); + for (key, value) in [("angle", json!("NaN")), ("roundness", json!("oops"))] { + let mut p = json!({"points": [[100, 100], [300, 100]]}); + p[key] = value; + assert!(s.execute("path.blob", &p).is_err(), "{key}: {p}"); + } + s.execute("path.blob", &json!({"points": [[100, 200], [300, 200]], "angle": 1e300, "roundness": -1e300, "merge": false})).unwrap(); + assert!(paths(&s)[1].1.control_bounds().unwrap().height().is_finite()); +} + +#[test] +fn blob_pressure_size_works_with_flat_tip() { + let mut s = session(); + s.execute( + "path.blob", + &json!({"points": [[100, 100, 0], [200, 100, 1]], "size": 40, "sizeMode": "pressure", "sizeVariation": 15, "roundness": 25, "merge": false}), + ) + .unwrap(); + let variable = paths(&s)[0].1.control_bounds().unwrap(); + let mut fixed = session(); + fixed.execute("path.blob", &json!({"points": [[100, 100], [200, 100]], "size": 40, "roundness": 25, "merge": false})).unwrap(); + let baseline = paths(&fixed)[0].1.control_bounds().unwrap(); + assert!(variable.height() > baseline.height(), "{} <= {}", variable.height(), baseline.height()); + assert!(variable.height() < 20.0, "flat tip height: {}", variable.height()); +} + fn path(s: &Session, id: NodeId) -> PathData { s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone() } diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index f23c19c2ff..d1224e05da 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -14,6 +14,21 @@ fn select(s: &mut Session, tool: &str) { s.select_tool(tool, ViewInfo::default()).unwrap(); } +#[test] +fn blob_tip_options_report_and_persist() { + let mut s = session(); + select(&mut s, "blobBrush"); + assert_eq!((s.tool_options()["angle"].as_f64(), s.tool_options()["roundness"].as_f64()), (Some(0.0), Some(100.0))); + s.set_tool_option("angle", &json!(45)); + s.set_tool_option("roundness", &json!(0)); + select(&mut s, "selection"); + let saved = serde_json::to_string(&s.prefs).unwrap(); + let mut next = session(); + next.apply_prefs(serde_json::from_str(&saved).unwrap()); + select(&mut next, "blobBrush"); + assert_eq!((next.tool_options()["angle"].as_f64(), next.tool_options()["roundness"].as_f64()), (Some(45.0), Some(0.0))); +} + #[test] fn options_survive_a_tool_switch() { let mut s = session(); diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index be2019a383..23e61e602c 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -234,10 +234,20 @@ pub fn polyline(pts: &[Point]) -> BezPath { /// whose long axis runs at `angle` degrees counter-clockwise on the page (y-down document space) /// and whose short axis is `roundness` percent of the long one (kept within 1–100). pub fn eraser_tip(angle: f64, roundness: f64) -> Affine { + ellipse_tip(angle, roundness.clamp(1.0, 100.0)) +} + +/// Map a round brush tip to a page-oriented ellipse. 0 percent Roundness is drawn as +/// 0.1 percent so its inverse is defined. +pub fn blob_tip(angle: f64, roundness: f64) -> Affine { + ellipse_tip(angle, roundness.clamp(0.1, 100.0)) +} + +fn ellipse_tip(angle: f64, roundness: f64) -> Affine { let t = angle.to_radians(); let u = Vec2::new(t.cos(), -t.sin()); let v = Vec2::new(-u.y, u.x); - let r = roundness.clamp(1.0, 100.0) / 100.0; + let r = roundness / 100.0; let (xx, xy, yy) = (u.x * u.x + r * v.x * v.x, u.x * u.y + r * v.x * v.y, u.y * u.y + r * v.y * v.y); Affine::new([xx, xy, xy, yy, 0.0, 0.0]) } @@ -246,7 +256,15 @@ pub fn eraser_tip(angle: f64, roundness: f64) -> Affine { /// `roundness`) covers along `pts`: a round stroke along the points squashed by the tip's map, /// stretched back. pub fn eraser_area(pts: &[Point], size: f64, angle: f64, roundness: f64) -> PathData { - let stretch = eraser_tip(angle, roundness); + swept_tip_area(pts, size, eraser_tip(angle, roundness)) +} + +/// The filled area covered by a Blob Brush's page-oriented elliptical tip. +pub fn blob_area(pts: &[Point], size: f64, angle: f64, roundness: f64) -> PathData { + swept_tip_area(pts, size, blob_tip(angle, roundness)) +} + +fn swept_tip_area(pts: &[Point], size: f64, stretch: Affine) -> PathData { let squash = stretch.inverse(); let mut round: Vec<Point> = pts.iter().map(|p| squash * *p).collect(); if let [p] = round[..] { diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 6036a06d95..045a3304ea 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -24,7 +24,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{NodeId, NodeKind}; use vectorcraft_geom::Point; -use super::{FEEDBACK, eraser_area, points_json, polyline}; +use super::{FEEDBACK, blob_area, eraser_area, points_json, polyline}; use crate::guides::DrawSnap; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -71,9 +71,9 @@ pub struct GestureTool { pub size_pressure: bool, /// Blob Brush and Eraser Tool Options' Size Variation, in points. pub size_variation: f64, - /// The angle of the Eraser tip's long axis, in degrees counter-clockwise from horizontal. + /// The angle of the Blob Brush or Eraser tip's long axis, in degrees counter-clockwise from horizontal. pub angle: f64, - /// The Eraser tip's short axis in percent of its long one (100: round). + /// The Blob Brush or Eraser tip's short axis in percent of its long one (100: round). pub roundness: f64, /// Fill new pencil/brush strokes. pub fill: bool, @@ -439,6 +439,8 @@ impl GestureTool { "sizeMode": if self.size_pressure { "pressure" } else { "fixed" }, "sizeVariation": self.size_variation, "fidelity": self.fidelity, + "angle": self.angle, + "roundness": self.roundness, "keepSelected": self.keep_selected, "mergeOnlySelection": self.merge_only_selection }), @@ -691,15 +693,27 @@ impl Tool for GestureTool { _ => 1.0, }; let color = if self.id == "eraser" { [0x80, 0x80, 0x80] } else { FEEDBACK }; - // A tip that is not round shows the outline of the area it covers. - // shortcut: at its Size even with Pressure; the release erases at the pen's widths. - if self.id == "eraser" && self.roundness < 100.0 { - let area = eraser_area(&self.points, self.size, self.angle, self.roundness); - o.push(Overlay::Path { path: area.to_bezpath(), color, width: 1.0, dashed: false }); - return o; - } - // With Size set to Pressure, each step of the drag shows as wide as the pen pressed there. - if let Some(pressures) = self.size_pressures() { + // A tip that is not round shows the outline of the area it covers, each step of the drag + // as wide as the pen pressed there with Size set to Pressure. + if matches!(self.id, "eraser" | "blobBrush") && self.roundness < 100.0 && !self.smoothing { + let area = |pts: &[Point], size| { + if self.id == "blobBrush" { + blob_area(pts, size, self.angle, self.roundness) + } else { + eraser_area(pts, size, self.angle, self.roundness) + } + }; + if let Some(pressures) = self.size_pressures() { + for (seg, p) in self.points.windows(2).zip(pressures.windows(2)) { + let pressure = f64::from(p[0] + p[1]) / 2.0; + let size = super::pressure_size(self.size, self.size_variation, pressure); + o.push(Overlay::Path { path: area(seg, size).to_bezpath(), color, width: 1.0, dashed: false }); + } + } else { + o.push(Overlay::Path { path: area(&self.points, self.size).to_bezpath(), color, width: 1.0, dashed: false }); + } + } else if let Some(pressures) = self.size_pressures() { + // With Size set to Pressure, each step of the drag shows as wide as the pen pressed there. for (seg, p) in self.points.windows(2).zip(pressures.windows(2)) { let pressure = f64::from(p[0] + p[1]) / 2.0; let width = super::pressure_size(self.size, self.size_variation, pressure) * cx.zoom; @@ -785,6 +799,8 @@ impl Tool for GestureTool { "size": self.size, "sizeMode": if self.size_pressure { "pressure" } else { "fixed" }, "sizeVariation": self.size_variation, + "angle": self.angle, + "roundness": self.roundness, "keepSelected": self.keep_selected, "mergeOnlySelection": self.merge_only_selection }) @@ -810,7 +826,7 @@ impl Tool for GestureTool { }, "sizeVariation" if self.varies_size() => self.size_variation = v.as_f64().unwrap_or(self.size_variation).clamp(0.0, 1000.0), "angle" => self.angle = v.as_f64().unwrap_or(self.angle).clamp(-180.0, 180.0), - "roundness" => self.roundness = v.as_f64().unwrap_or(self.roundness).clamp(1.0, 100.0), + "roundness" => self.roundness = v.as_f64().unwrap_or(self.roundness).clamp(if self.id == "blobBrush" { 0.0 } else { 1.0 }, 100.0), "fill" => self.fill = v.as_bool().unwrap_or(self.fill), "altSmooth" => self.alt_smooth = v.as_bool().unwrap_or(self.alt_smooth), "livePreview" if self.id == "pencil" => self.live_preview = v.as_bool().unwrap_or(self.live_preview), diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 17e905156e..1d6cc8acef 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -1391,6 +1391,53 @@ fn the_eraser_sends_its_tip_and_shows_the_area_it_covers() { assert!((b.y0 - 140.0).abs() < 0.1 && (b.y1 - 160.0).abs() < 0.1, "{b:?}"); } +/// The Blob Brush's Angle and Roundness (Blob Brush Tool Options, 0° and 100% by default) go with +/// its stroke, kept within −180–180° and 0–100%; while it drags, a tip that is not round shows the +/// outline of the area it covers with the length label, and an Alt drag that smooths shows the +/// Smooth tool's thin line. +#[test] +fn the_blob_brush_sends_its_tip_and_shows_the_area_it_covers() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let cx = ToolContext { measurement_labels: true, ..cx(&d, &s, &p) }; + let mut t = GestureTool::new("blobBrush"); + assert_eq!((t.options()["angle"].as_f64(), t.options()["roundness"].as_f64()), (Some(0.0), Some(100.0))); + t.set_option("size", &json!(20)); + for (angle, roundness, sent) in [(45.0, 25.0, (45.0, 25.0)), (400.0, -5.0, (180.0, 0.0)), (-400.0, 250.0, (-180.0, 100.0))] { + t.set_option("angle", &json!(angle)); + t.set_option("roundness", &json!(roundness)); + assert_eq!((t.options()["angle"].as_f64(), t.options()["roundness"].as_f64()), (Some(sent.0), Some(sent.1))); + let acts = drag(&mut t, &cx, &[(50.0, 150.0), (250.0, 150.0)], Mods::default()); + assert!( + matches!(&acts[2][0], Action::Exec(c, v) if c == "path.blob" && v["size"] == 20.0 && v["angle"] == sent.0 && v["roundness"] == sent.1), + "{acts:?}" + ); + } + // A tip 20 pt long and 5 pt wide, standing upright: along a horizontal drag from x 50 to + // x 150 the outline reaches 2.5 pt either side of the drag and 10 pt above and below its ends. + t.set_option("angle", &json!(90)); + t.set_option("roundness", &json!(25)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 150.0)); + let o = t.overlays(&cx); + let Some(Overlay::Path { path, width, .. }) = o.iter().find(|o| matches!(o, Overlay::Path { .. })) else { panic!("{o:?}") }; + assert_eq!(*width, 1.0); + let b = vectorcraft_geom::Shape::bounding_box(path); + assert!((b.x0 - 47.5).abs() < 0.1 && (b.x1 - 152.5).abs() < 0.1, "{b:?}"); + assert!((b.y0 - 140.0).abs() < 0.1 && (b.y1 - 160.0).abs() < 0.1, "{b:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { .. })), "{o:?}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)); + let alt = Mods { alt: true, ..Default::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 150.0).with_mods(alt)); + let o = t.overlays(&cx); + let [Overlay::Path { path, width, .. }] = &o[..] else { panic!("{o:?}") }; + assert_eq!(*width, 1.0); + assert!(vectorcraft_geom::Shape::bounding_box(path).height() < 0.1, "{o:?}"); +} + #[test] fn smooth_needs_selection_and_brackets_resize() { let (d, _) = doc_with_rect(); diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 328ca4a80b..97d2b327c3 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -42,7 +42,7 @@ const ROWS: &[Row] = &[ (&["blobBrush", "eraser"], None, &["size", "sizeMode", "sizeVariation"]), (&["blobBrush"], None, &["fidelity", "keepSelected", "mergeOnlySelection"]), // Eraser Tool Options' tip shape. - (&["eraser"], None, &["angle", "roundness"]), + (&["blobBrush", "eraser"], None, &["angle", "roundness"]), // Live Paint Selection Tool Options (`builder::LivePaintSelectionTool`). (&["livePaintSelection"], None, &["selectFills", "selectStrokes", "color", "width"]), (&["polygon"], None, &["sides"]), diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index 783e79093a..85d8630567 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -6,7 +6,7 @@ //! Fields: `tool`; `fidelity` (points; Pencil, Paintbrush, Smooth and Blob Brush), `fill` (Pencil and //! Paintbrush), `keepSelected` (Pencil, Paintbrush and Blob Brush), `mergeOnlySelection` (Blob //! Brush), `closeWithin` and `editWithin` (screen pixels, 0 turns it off; Pencil and Paintbrush), -//! `angle` (degrees) and `roundness` (percent; Eraser), `livePreview` (Pencil: the stroke shows +//! `angle` (degrees) and `roundness` (percent; Blob Brush and Eraser), `livePreview` (Pencil: the stroke shows //! with its fill and stroke while it is drawn, or as a thin line until the release), `size` //! (points; Blob Brush and Eraser), and `sizeMode` (`fixed` or `pressure`) and `sizeVariation` //! (points; Blob Brush and Eraser: with Pressure the tip is Size − Variation wide at the lightest @@ -206,7 +206,11 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { number(ui, d, ("angle", tl!("Angle:")), "°", 0, (-180.0, 180.0)); } if d.fields.contains_key("roundness") { - number(ui, d, ("roundness", tl!("Roundness:")), "%", 0, (1.0, 100.0)); + let min = if d.str("tool") == "blobBrush" { 0.0 } else { 1.0 }; + number(ui, d, ("roundness", tl!("Roundness:")), "%", 0, (min, 100.0)); + } + if d.str("tool") == "blobBrush" { + blob_tip_preview(ui, d); } if d.fields.contains_key("sizeMode") { blob_size(ui, d); @@ -245,6 +249,52 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } +/// Side of the Blob Brush tip preview's square, in points. +const TIP_PREVIEW: f32 = 64.0; + +/// The Blob Brush's tip preview: a square with the tip at its Angle and Roundness and a line along +/// its long axis (a drag in the square sets the Angle), and beside it three dabs of the tip, the +/// middle one darker. +fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { + let t = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(egui::vec2(CONTENT_W, TIP_PREVIEW), egui::Sense::hover()); + let square = egui::Rect::from_min_size(rect.min, egui::vec2(TIP_PREVIEW, TIP_PREVIEW)); + let response = ui.interact(square, ui.scope_id().with("freehand-tip-angle"), egui::Sense::drag()); + if response.dragged() + && let Some(p) = response.interact_pointer_pos() + { + let delta = p - square.center(); + if delta.length_sq() > 1.0 { + d.fields.insert("angle".into(), json!(f64::from((-delta.y).atan2(delta.x)).to_degrees().round())); + } + } + let painter = ui.painter_at(rect); + painter.rect_filled(square, 2.0, t.input); + painter.rect_stroke(square, 2.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); + let a = d.f64("angle", 0.0).clamp(-180.0, 180.0).to_radians(); + // The long axis on screen (y down: a positive angle tilts it up to the right) and the short one. + let u = egui::vec2(a.cos() as f32, -a.sin() as f32); + let v = egui::vec2(-u.y, u.x); + let long = 18.0; + let short = long * (d.f64("roundness", 100.0).clamp(0.0, 100.0) as f32 / 100.0).max(0.01); + let dab = |center: egui::Pos2, color: egui::Color32| { + let points = (0..32) + .map(|i| { + let s = std::f32::consts::TAU * i as f32 / 32.0; + center + u * (long * s.cos()) + v * (short * s.sin()) + }) + .collect(); + painter.add(egui::Shape::convex_polygon(points, color, egui::Stroke::NONE)); + }; + let center = square.center(); + dab(center, t.text); + painter.line_segment([center, center + u * 25.0], egui::Stroke::new(1.0, t.accent)); + let strip = square.right() + 2.5 * long; + for (i, color) in [t.text_dim, t.text, t.text_dim].into_iter().enumerate() { + dab(egui::pos2(strip + i as f32 * 1.5 * long, center.y), color); + } +} + /// OK: set the tool's options. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { let values: Map<String, Value> = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 6d316ef024..0136d25c51 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -7,6 +7,27 @@ fn app() -> VectorcraftApp { app } +#[test] +fn blob_tip_fields_confirm_and_cancel() { + let mut app = app(); + app.run("tool.options", json!({"tool": "blobBrush"})).unwrap(); + let text = painted(&mut app); + assert!(text.contains("Angle:") && text.contains("Roundness:"), "{text}"); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((d.f64("angle", -1.0), d.f64("roundness", -1.0)), (0.0, 100.0)); + d.fields.insert("angle".into(), json!(45)); + d.fields.insert("roundness".into(), json!(0)); + super::super::confirm(&mut app).unwrap(); + assert_eq!( + (app.session.tool_options_of("blobBrush")["angle"].as_f64(), app.session.tool_options_of("blobBrush")["roundness"].as_f64()), + (Some(45.0), Some(0.0)) + ); + app.run("tool.options", json!({"tool": "blobBrush"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("roundness".into(), json!(75)); + app.ui.dialog = None; + assert_eq!(app.session.tool_options_of("blobBrush")["roundness"], json!(0.0)); +} + /// The labels the open dialog paints. fn painted(app: &mut VectorcraftApp) -> String { crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) @@ -118,8 +139,8 @@ fn each_tool_shows_its_options_and_ok_sets_them() { assert!(text.contains("Size:"), "{tool}: {text}"); assert_eq!(text.contains("Fidelity:"), blob, "{tool}: {text}"); assert_eq!((text.contains("Keep selected"), text.contains("Merge only with selection")), (blob, blob), "{tool}: {text}"); - // The Eraser also has Angle and Roundness. - assert_eq!((text.contains("Angle:"), text.contains("Roundness:")), (!blob, !blob), "{tool}: {text}"); + // Both tools have Angle and Roundness. + assert!(text.contains("Angle:") && text.contains("Roundness:"), "{tool}: {text}"); app.ui.dialog.as_mut().unwrap().fields.insert("size".into(), json!(24)); super::super::confirm(&mut app).unwrap(); assert_eq!(app.session.tool_options_of(tool)["size"].as_f64(), Some(24.0), "{tool}"); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index fc2e265b6d..2f2a86d26f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -814,7 +814,8 @@ Paintbrush, Blob Brush; on by default for the Pencil and Paintbrush and off for the path a stroke draws, continues or merges into is not selected afterwards), `mergeOnlySelection` (Blob Brush; off by default, and while it is on a stroke merges only with selected blobs), `closeWithin` and `editWithin` (screen pixels, 0 turns it off; Pencil, Paintbrush), `size` (pt; Blob Brush, Eraser), and `angle` -(°, −180 to 180; 0) and `roundness` (%, 1 to 100; 100) of the Eraser's tip (Eraser). `ui.dialog.confirm` runs +(°, −180 to 180; 0) and `roundness` (%, 0 to 100 for the Blob Brush, where 0 is drawn as 0.1, and 1 to 100 for +the Eraser; 100) of the tip (Blob Brush, Eraser); the tip keeps its angle on the page along a stroke. `ui.dialog.confirm` runs `tool.setOption {tool, values}`. `ui.pointer` events also take `holdMs` (0..60000): the pointer then holds still that long, button down, before the diff --git a/docs/mcp.md b/docs/mcp.md index 4a37804b6e..add4788c4a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2642,7 +2642,7 @@ naming the key; the document does not change and no undo step is recorded: `t`, `path.reshapeSegment` and `object.blend.spine.reshapeSegment`; `x`, `y` and `t` in `path.curvatureEdit`; `x` and `y` in `path.convertAnchor`; `t` in `path.insertAnchor`; `fidelity` and the `within` of `redraw` in `path.freehand` (and in `brush.freehand`, which runs it); `size`, `sizeVariation`, `angle` and `roundness` in `path.eraseRegion`; -`size`, `sizeVariation` and `fidelity` in `path.blob`; `width` in `path.eraseSegments`; +`size`, `sizeVariation`, `angle`, `roundness` and `fidelity` in `path.blob`; `width` in `path.eraseSegments`; `radius` and `fidelity` in `path.smoothRegion`; `tolerance` in `path.joinScrub`; `dx` and `dy` in `path.moveAnchors`; and `dx`, `dy`, `tol` and `radius` in `path.reshape`. A null is read as a key left out. `path.convertAnchor` refuses an `x` without a `y`, or a `y` without an `x`, with "x and y must be given together". `path.freehand`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9eb17cc09e..02a030972b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -379,10 +379,10 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Area | Weight | Done | Missing (main items) | One agent (h) | |---|---:|---:|---|---:| | Selection, transform & align tools | 6 | 85% | Free Transform/Scale/Reflect along a rotated box, Global Edit of similar groups, transform nuances (the rotated persistent bounding box is done) | 4–6 | -| Drawing tools | 7 | 85% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, the freehand Tool Options' Keep selected, Alt to the Smooth tool, Blob Brush Merge Only with Selection and brush angle/roundness, Touch Type, Live Corners' Relative rounding (Curvature point display improved, #1236 in part) | 8–13 | +| Drawing tools | 7 | 85% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, the freehand Tool Options' Keep selected, Alt to the Smooth tool, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding (Curvature point display improved, #1236 in part) | 8–13 | | Selection, transform & align tools | 6 | 85% | Free Transform/Scale/Reflect along a rotated box, Global Edit of similar groups, transform nuances (the rotated persistent bounding box is done; no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of similar groups, transform nuances (the rotated persistent bounding box is done) | 4–6 | -| Drawing tools | 7 | 86% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection and brush angle/roundness, Touch Type, Live Corners' Relative rounding | 7–12 | +| Drawing tools | 7 | 86% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | freeform and mixed spot/process gradients in SVG/PDF (exported as stops or process colours), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | | Strokes, brushes, width profiles | 5 | 90% | the Art brush's Overlap, auto-generated Pattern brush corners and new tile art in Pattern Brush Options (Brush Options for every brush type done), more built-in brush libraries (four generated in code are done), pen pressure on macOS (the windowing layer reports none there), brushes driven by pen tilt, bearing and barrel rotation (6D art pens) | 8–15 | @@ -737,6 +737,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Shape Builder pieces on dense hatches (lines at exact 0.25 or 0.5 pt steps across another line) come back one per stretch between crossings, with no speck where the sweep cut a line's two passes a rounding error apart: the planar map contracts the stub between such cuts into one vertex, bounded by each cluster's extent so a run of tiny level segments keeps its length (`crates/pathops/src/planar.rs` tests `a_dense_hatch_at_exact_binary_steps_cuts_each_line_once_per_crossing`, `a_run_of_tiny_level_segments_is_not_contracted_as_stubs`, `a_line_crossed_where_its_two_passes_part_is_cut_once`). The planar map's edge-source grid stays linear in memory on any input: a segment is filed once per cell it crosses, and the grid holds at most a budget of cell references (a few dozen per item plus a few rows' worth), past which the remaining items go to a short scanned list and are still found, so thousands of coincident segments cannot make the index quadratic (`crates/pathops/src/planar.rs` test `rect_index_holds_a_bounded_number_of_references`). The Blob Brush Tool Options have Keep selected and Merge only with selection, both off by default: while Keep selected is off, the blob a stroke draws or merges into is not selected afterwards, and while Merge only with selection is on, a stroke merges only with selected blobs of its color that it touches (`path.blob` `keepSelected` and `mergeOnlySelection`). + The Blob Brush Tool Options also have Angle and Roundness, as the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list them: Angle from −180° to 180° (0° by default) and Roundness from 0% to 100% (100%, a round tip, by default). The elliptical tip keeps its angle on the page along a stroke, a 0% tip is drawn 0.1% as wide as it is long, and the dialog shows the tip and three dabs of it. The values are kept with the tool's options (`path.blob` `angle` and `roundness`). Not done: the Random and pen-driven variations of Angle and Roundness. The Blob Brush Tool Options also have Fidelity, as the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list it: the Pencil's logarithmic slider from Accurate (0.01 pt) to Smooth (20 pt) and its field (up to 100 pt), 1.5 pt by default and kept with the tool's options. The brush follows the stroke fitted at the Fidelity, as a Pencil stroke is fitted: a low value follows the drag closely, jitter included, and a higher one gives smoother curves (`path.blob` `fidelity`). A Blob Brush stroke merges with the topmost path of its fill color and no stroke that it touches, and with the other such paths it touches in the same group or layer that are next to that path in stacking order with no other kind of object between them; matching paths in other groups or layers are left alone, as the Blob Brush tool guidelines in [Paint with fills and strokes](https://web.archive.org/web/20241219085603/https://helpx.adobe.com/illustrator/using/painting-fills-strokes.html) describe (`path.blob`). - **Ruler guides as layer objects:** a guide goes on the current layer, shows, hides, locks and is deleted with it, is listed in the Layers panel (its row selects it) and moves to another layer (`guide.setLayer`, or its row dragged onto that layer's rows); guides on a hidden or locked layer can't be selected, moved or deleted, Duplicate copies a layer's guides and Merge Selected and Flatten Artwork keep them on the merged layer; guides from files saved before guides had layers go on the top visible, unlocked layer when the document opens. Not done: guides stacked among the art of their layer (they are listed above it), a guide row's own eye and lock. Lock Guides also locks the objects made into guides: they can't be selected, moved or deleted (#1543); they are drawn in the guide colour and style of Preferences, and a dragged selection snaps to ruler guides with Smart Guides on (#1583, fixes #1534). The Transform panel shows a selected ruler guide's X or Y, and typing a value moves it (#1659, part of #1597). This is not established by the documentation we could find: the public help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) describe selecting and dragging unlocked guides and the panels' X and Y for a selection, not a guide's position in a panel, and the one public statement of it is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. It is kept as a convenience pending the owner's decision, with no parity claim and nothing counted towards a score. From d9fefde06188463d51d6b6278aa4f8605ad9f03e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 01:05:24 -0700 Subject: [PATCH 017/260] Appearance: Reduce to Basic Appearance keeps the selected fill or stroke row Reduce to Basic Appearance kept the topmost visible fill and stroke even when another fill or stroke row was selected in the Appearance panel. It now keeps the selected row in place of the topmost one of its kind, and in each other selected object the row equal to it. With ids, or with no selected row, it keeps the topmost ones as before. --- crates/engine/src/cmd/appearance.rs | 23 +++++++++++--- crates/engine/src/tests/appearance.rs | 44 +++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index de4885564c..df691490ff 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -71,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> { "Reduce to Basic Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} keep only the topmost visible fill and stroke, without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects", + "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects", has_doc, reduce_basic ), @@ -614,11 +614,26 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> { let ids = require_targets(s, p, "appearance.reduceToBasic")?; // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); + // The Appearance panel's active row (a row of the first selected object's stack, and in each + // other target the row equal to it there), when the command acts on that selection. + let active = match s.appearance_item() { + Some(index) + if p.get("ids").is_none() && p.get("id").is_none() && !targets_contents(p)? && s.doc()?.selection.subjects().first() == ids.first() => + { + items_per_target(&before, &ids, &[index], true) + } + _ => vec![Vec::new(); ids.len()], + }; super::overprint::edit_counted(s, "Reduce to Basic Appearance", |d| { - for id in &ids { + for (id, at) in ids.iter().zip(&active) { if let Some(n) = d.node_mut(*id) { - // The topmost visible fill and stroke stay, without their own transparency or effects. - let top = |fill: bool| n.appearance.items.iter().rev().find(|i| i.visible() && i.is_fill() == fill).cloned(); + // The active row stays when it is a visible fill or stroke; otherwise the topmost + // visible one of each kind does. Both lose their own transparency and effects. + let picked = at.first().and_then(|i| n.appearance.items.get(*i)).filter(|i| i.visible()).cloned(); + let top = |fill: bool| match &picked { + Some(i) if i.is_fill() == fill => Some(i.clone()), + _ => n.appearance.items.iter().rev().find(|i| i.visible() && i.is_fill() == fill).cloned(), + }; let (fill, stroke) = (top(true), top(false)); // Other objects always keep a fill row (None when there was none); a group only // keeps the rows it had. diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index 7d8cb2e0fb..4906228129 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -400,6 +400,50 @@ fn clear_and_reduce_to_basic() { assert_eq!(node(&s, id).opacity, 0.4); } +/// Reduce to Basic Appearance keeps the Appearance panel's active fill or stroke row instead of the +/// topmost one of its kind, in each selected object with the same stack. With `ids` it keeps the +/// topmost ones. +#[test] +fn reduce_to_basic_keeps_the_active_row() { + let mut s = session(); + let a = rect(&mut s, 50.0); + let b = rect(&mut s, 200.0); + let c = rect(&mut s, 300.0); + let stack = |s: &mut Session| { + run(s, "appearance.addFill", json!({})); + run(s, "appearance.addStroke", json!({})); // [Fill, Stroke, Fill, Stroke] + run(s, "appearance.setItem", json!({"index": 0, "color": "#00ff00"})); + run(s, "appearance.setItem", json!({"index": 2, "color": "#ff0000"})); + run(s, "appearance.setItem", json!({"index": 1, "weight": 7})); + }; + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + stack(&mut s); + // The lower, green fill row is active: both objects keep it and their top stroke. + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "appearance.reduceToBasic", json!({})); + for id in [a, b] { + let n = node(&s, id); + assert!(n.appearance.is_basic(), "{:?}", n.appearance); + assert_eq!(fill_paint(&n, 0).color().unwrap().to_hex(), "#00ff00"); + assert_eq!(stroke(&n, 1).width, 1.0); + } + // The lower stroke row is active: it stays, with the top fill. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "appearance.setActiveItem", json!({"index": 1})); + run(&mut s, "appearance.reduceToBasic", json!({})); + let n = node(&s, a); + assert_eq!(fill_paint(&n, 0).color().unwrap().to_hex(), "#ff0000"); + assert_eq!(stroke(&n, 1).width, 7.0); + // Given ids, the topmost fill and stroke stay. + run(&mut s, "select.set", json!({"ids": [c.0]})); + stack(&mut s); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "appearance.reduceToBasic", json!({"ids": [c.0]})); + let n = node(&s, c); + assert_eq!(fill_paint(&n, 0).color().unwrap().to_hex(), "#ff0000"); + assert_eq!(stroke(&n, 1).width, 1.0); +} + /// How many steps there are to undo and to redo, and whether the document has unsaved changes. fn history(s: &Session) -> (usize, usize, bool) { let st = s.doc().unwrap(); From f677c60abae62a270986df7585f0c387a288af05 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 18:49:05 -0700 Subject: [PATCH 018/260] Perspective Selection: Shift constrains a move to the plane's axes and diagonals Holding Shift while dragging objects with the Perspective Selection tool snaps the move, in the plane's own coordinates, to the nearest plane axis or 45 degree diagonal. This applies to plain moves and to Alt and Ctrl+Alt copies. The preview, the final move and the measurement label use the snapped point. Pressing or releasing Shift, pressing 5 and pressing 1 to 4 during the drag recompute the preview from the pointer; a move perpendicular to the plane is not constrained. --- crates/engine/src/tests/persp_select.rs | 67 +++++++++++++++ crates/engine/src/tooling.rs | 5 ++ crates/tools/src/distort/perspective.rs | 81 ++++++++++++++++++- crates/tools/src/distort/perspective/tools.rs | 53 ++++++++---- docs/target-app-parity.md | 1 + 5 files changed, 191 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/tests/persp_select.rs b/crates/engine/src/tests/persp_select.rs index 3b848d927d..a6f912b732 100644 --- a/crates/engine/src/tests/persp_select.rs +++ b/crates/engine/src/tests/persp_select.rs @@ -111,6 +111,73 @@ fn alt_drag_copies_and_the_copy_stays_attached() { assert!(s.doc().unwrap().doc.node(copy).is_none()); } +#[test] +fn shift_drag_moves_on_a_plane_axis() { + let (mut s, id) = persp_session(); + s.select_tool("perspectiveSelection", ViewInfo::default()).unwrap(); + let before = plane_pts(&s, id, Plane::Right, 0.0); + let h = grid(&s).homography(Plane::Right).unwrap(); + let start = bounds_of(&before).center(); + let (from, to) = (h.apply(start).unwrap(), h.apply(start + Vec2::new(80.0, 20.0)).unwrap()); + let n = undo_len(&s); + drag(&mut s, &[from, to, to], Mods { shift: true, ..Default::default() }); + assert_eq!(undo_len(&s), n + 1); + for (a, b) in before.iter().zip(plane_pts(&s, id, Plane::Right, 0.0)) { + assert!((b - *a - Vec2::new(80.0, 0.0)).hypot() < 1e-6, "shift move: {a:?} → {b:?}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(plane_pts(&s, id, Plane::Right, 0.0), before); +} + +#[test] +fn shift_drag_keeps_its_displacement_after_a_plane_key() { + let (mut s, id) = persp_session(); + let v = ViewInfo::default(); + s.select_tool("perspectiveSelection", v).unwrap(); + let before = plane_pts(&s, id, Plane::Right, 0.0); + let h = grid(&s).homography(Plane::Right).unwrap(); + let start = bounds_of(&before).center(); + let (from, to) = (h.apply(start).unwrap(), h.apply(start + Vec2::new(80.0, 20.0)).unwrap()); + let shift = Mods { shift: true, ..Default::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, from.x, from.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, to.x, to.y), v).unwrap(); + s.tool_key(ToolKey::Digit(2), shift, v).unwrap(); + assert_eq!(grid(&s).plane, Plane::Ground); + s.pointer(&PointerEvent::new(PointerKind::Up, to.x, to.y).with_mods(shift), v).unwrap(); + for (a, b) in before.iter().zip(plane_pts(&s, id, Plane::Right, 0.0)) { + assert!((b - *a - Vec2::new(80.0, 0.0)).hypot() < 1e-6, "plane key: {a:?} → {b:?}"); + } +} + +#[test] +fn cmd_alt_shift_drag_copies_on_a_plane_axis() { + let (mut s, id) = persp_session(); + let v = ViewInfo::default(); + s.select_tool("directSelection", v).unwrap(); + s.select_tool("perspectiveSelection", v).unwrap(); + let before = plane_pts(&s, id, Plane::Right, 0.0); + let count = s.doc().unwrap().doc.node_count(); + let h = grid(&s).homography(Plane::Right).unwrap(); + let start = bounds_of(&before).center(); + let (from, to) = (h.apply(start).unwrap(), h.apply(start + Vec2::new(80.0, 20.0)).unwrap()); + let n = undo_len(&s); + drag(&mut s, &[from, to, to], Mods { cmd: true, alt: true, shift: true, ..Default::default() }); + assert_eq!(undo_len(&s), n + 1); + assert_eq!(s.doc().unwrap().doc.node_count(), count + 1); + let copy = *s.doc().unwrap().selection.objects.first().unwrap(); + assert_ne!(copy, id); + assert_eq!(s.doc().unwrap().selection.objects, vec![copy]); + assert_eq!(plane_pts(&s, id, Plane::Right, 0.0), before); + assert_eq!(attached(&s, copy), Some((Plane::Right, 0.0))); + for (a, b) in before.iter().zip(plane_pts(&s, copy, Plane::Right, 0.0)) { + assert!((b - *a - Vec2::new(80.0, 0.0)).hypot() < 1e-6, "shift copy: {a:?} → {b:?}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.node_count(), count); + assert_eq!(plane_pts(&s, id, Plane::Right, 0.0), before); + assert_eq!(s.doc().unwrap().selection.objects, vec![id]); +} + #[test] fn cmd_alt_drag_copies_on_the_perspective_plane() { let (mut s, id) = persp_session(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 8229979d02..90f4ff61ce 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -457,6 +457,11 @@ impl Session { // 1–4 pick the active perspective plane while the grid is shown. if let Some(plane) = self.plane_key(key) { self.execute("perspective.plane.set", &serde_json::json!({ "plane": plane.id() }))?; + if self.tool_id() == "perspectiveSelection" { + let acts = self.with_tool_cx(view, |t, cx| t.key(cx, key, mods)); + self.take_tool_panic()?; + return self.apply_actions(acts); + } return Ok(vec![]); } let acts = self.with_tool_cx(view, |t, cx| t.key(cx, key, mods)); diff --git a/crates/tools/src/distort/perspective.rs b/crates/tools/src/distort/perspective.rs index 9a9863e554..2542e6a1a5 100644 --- a/crates/tools/src/distort/perspective.rs +++ b/crates/tools/src/distort/perspective.rs @@ -1204,11 +1204,90 @@ mod tests { let Action::Preview(cmd, v) = &acts[0] else { panic!("{acts:?}") }; assert_eq!((cmd.as_str(), &v["perpendicular"], &v["to"]), ("perspective.move", &json!(true), &json!([mid.x + 20.0, mid.y]))); assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("dZ")))); - assert!(t.key(&c, ToolKey::Digit(3), Mods::default()).is_empty()); + assert!(matches!(t.key(&c, ToolKey::Digit(3), Mods::default()).as_slice(), [Action::Preview(cmd, _)] if cmd == "perspective.move")); assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, mid.x + 20.0, mid.y)), vec![Action::Commit]); assert!(!t.busy()); } + #[test] + fn selection_move_shift_snaps_in_each_plane() { + for plane in Plane::ALL { + let g = grid(2); + let h = g.homography(plane).unwrap(); + let from = h.apply(Point::new(50.0, 50.0)).unwrap(); + let mut d = Document::new(800.0, 600.0); + let layer = d.layers[0].id; + let id = d.alloc_id(); + d.insert( + Some(layer), + 0, + vectorcraft_doc::Node::path( + id, + vectorcraft_geom::shapes::rectangle(Rect::new(from.x - 20.0, from.y - 20.0, from.x + 20.0, from.y + 20.0)), + vectorcraft_doc::Appearance::default_art(), + ), + ) + .unwrap(); + g.store(&mut d); + set_attachment(d.node_mut(id).unwrap(), plane, 0.0); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let c = cx(&d, &s, &p); + let hi = h.inverse().unwrap(); + let start = hi.apply(from).unwrap(); + for (raw, expected) in [ + (Vec2::new(60.0, 12.0), Vec2::new(60.0, 0.0)), + (Vec2::new(12.0, 60.0), Vec2::new(0.0, 60.0)), + (Vec2::new(40.0, 50.0), Vec2::new(45.0, 45.0)), + ] { + let to = h.apply(start + raw).unwrap(); + let mut t = PerspectiveSelectionTool::default(); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, from.x, from.y)); + let acts = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(Mods { shift: true, ..Default::default() })); + let Some(Action::Preview(cmd, v)) = acts.last() else { panic!("{acts:?}") }; + assert_eq!(cmd, "perspective.move"); + let endpoint = Point::new(v["to"][0].as_f64().unwrap(), v["to"][1].as_f64().unwrap()); + let delta = hi.apply(endpoint).unwrap() - start; + assert!((delta - expected).hypot() < 1e-6, "{plane:?}: {delta:?} != {expected:?}"); + } + } + } + + #[test] + fn selection_move_recomputes_shift_copy_and_perpendicular() { + let (mut d, id) = doc_with_rect(); + grid(2).store(&mut d); + set_attachment(d.node_mut(id).unwrap(), Plane::Right, 0.0); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let c = cx(&d, &s, &p); + let h = PerspectiveGrid::current(&d).homography(Plane::Right).unwrap(); + let from = d.node(id).unwrap().geometric_bounds().unwrap().center(); + let start = h.inverse().unwrap().apply(from).unwrap(); + let to = h.apply(start + Vec2::new(60.0, 12.0)).unwrap(); + let mut t = PerspectiveSelectionTool::default(); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, from.x, from.y)); + let plain = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + let Some(Action::Preview(_, raw)) = plain.last() else { panic!("{plain:?}") }; + assert_eq!(raw["to"], json!([to.x, to.y])); + let shifted = + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(Mods { shift: true, alt: true, ..Default::default() })); + let Some(Action::Preview(_, snapped)) = shifted.last() else { panic!("{shifted:?}") }; + assert_eq!(snapped["copy"], json!(true)); + assert_ne!(snapped["to"], raw["to"]); + let perpendicular = t.key(&c, ToolKey::Digit(5), Mods { shift: true, alt: true, ..Default::default() }); + let Some(Action::Preview(_, depth)) = perpendicular.last() else { panic!("{perpendicular:?}") }; + assert_eq!(depth["to"], raw["to"]); + let in_plane = t.key(&c, ToolKey::Digit(5), Mods { shift: true, alt: true, ..Default::default() }); + let Some(Action::Preview(_, snapped_again)) = in_plane.last() else { panic!("{in_plane:?}") }; + assert_eq!(snapped_again["to"], snapped["to"]); + let released = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + let Some(Action::Preview(_, raw_again)) = released.last() else { panic!("{released:?}") }; + assert_eq!(raw_again["to"], raw["to"]); + } + #[test] fn escape_cancels_a_perspective_selection_drag() { let (mut d, id) = doc_with_rect(); diff --git a/crates/tools/src/distort/perspective/tools.rs b/crates/tools/src/distort/perspective/tools.rs index 541e7a8f97..9e9454b304 100644 --- a/crates/tools/src/distort/perspective/tools.rs +++ b/crates/tools/src/distort/perspective/tools.rs @@ -119,17 +119,18 @@ enum SelDrag { #[default] Idle, /// Pressed on an object: moves `ids` once the pointer leaves the drag threshold. `perp`: along - /// the plane's normal (5 pressed while dragging); `copy`: Alt at the last event. - Move { ids: Vec<NodeId>, from: Point, last: Point, began: bool, perp: bool, copy: bool }, + /// the plane's normal (5 pressed while dragging); `copy` and `shift`: modifiers at the last event. + Move { ids: Vec<NodeId>, from: Point, last: Point, began: bool, perp: bool, copy: bool, shift: bool }, /// Dragging `handle` of the perspective bounding box `rect` (plane space, on `plane` at `depth`). Scale { ids: Vec<NodeId>, plane: Plane, depth: f64, rect: Rect, handle: BoxHandle }, /// Dragging a plane widget. Plane(PlaneDrag), } -/// The Perspective Selection tool: selects, moves (Alt copies; press 5 while dragging to move -/// perpendicular to the plane) and scales (bounding-box handles; Shift proportional, Alt from the -/// centre) objects within their perspective planes; the arrow keys nudge them in perspective. +/// The Perspective Selection tool: selects, moves (Shift constrains to plane-space 45° directions, +/// Alt copies; press 5 while dragging to move perpendicular to the plane) and scales (bounding-box +/// handles; Shift proportional, Alt from the center) objects within their perspective planes; the +/// arrow keys nudge them in perspective. #[derive(Default)] pub struct PerspectiveSelectionTool { drag: SelDrag, @@ -163,21 +164,36 @@ pub(super) fn resize_cursor(d: Vec2) -> Cursor { impl PerspectiveSelectionTool { /// The `perspective.move` preview for the move drag (and its measurement label). fn move_preview(&mut self, cx: &ToolContext) -> Option<Action> { - let SelDrag::Move { ids, from, last, perp, copy, .. } = &self.drag else { return None }; + let SelDrag::Move { ids, from, last, perp, copy, shift, .. } = &self.drag else { return None }; let g = PerspectiveGrid::current(cx.doc); - let mut v = json!({"ids": crate::json_ids(ids), "from": [from.x, from.y], "to": [last.x, last.y], "copy": copy, "perpendicular": perp}); + let at = ids.first().and_then(|id| g.attachment_of(cx.doc, *id)).or((g.plane != Plane::None).then_some((g.plane, g.offset(g.plane)))); + let to = if *shift && !*perp { + at.and_then(|(plane, depth)| { + let h = g.homography_at(plane, depth)?; + let hi = h.inverse()?; + let start = hi.apply(*from)?; + let delta = hi.apply(*last)? - start; + let angle = (delta.y.atan2(delta.x) / std::f64::consts::FRAC_PI_4).round() * std::f64::consts::FRAC_PI_4; + let direction = Vec2::new(angle.cos(), angle.sin()); + let distance = delta.x * direction.x + delta.y * direction.y; + h.apply(start + direction * distance).filter(|p| p.x.is_finite() && p.y.is_finite()) + }) + .unwrap_or(*last) + } else { + *last + }; + let mut v = json!({"ids": crate::json_ids(ids), "from": [from.x, from.y], "to": [to.x, to.y], "copy": copy, "perpendicular": perp}); if g.plane != Plane::None { v["plane"] = json!(g.plane.id()); } - let at = ids.first().and_then(|id| g.attachment_of(cx.doc, *id)).or((g.plane != Plane::None).then_some((g.plane, g.offset(g.plane)))); self.measure = at.and_then(|(pl, depth)| { let text = if *perp { - format!("dZ: {}", cx.len(g.depth_at(pl, depth, *from, *last)? - depth)) + format!("dZ: {}", cx.len(g.depth_at(pl, depth, *from, to)? - depth)) } else { - let d = g.plane_delta(pl, depth, *from, *last)?; + let d = g.plane_delta(pl, depth, *from, to)?; cx.offset_label(d.x, d.y) }; - Some((*last, text)) + Some((to, text)) }); Some(Action::Preview("perspective.move".into(), v)) } @@ -223,19 +239,19 @@ impl Tool for PerspectiveSelectionTool { { acts.push(Action::Exec("perspective.plane.set".into(), json!({"plane": pl.id()}))); } - self.drag = SelDrag::Move { ids, from: p, last: p, began: false, perp: false, copy: m.alt }; + self.drag = SelDrag::Move { ids, from: p, last: p, began: false, perp: false, copy: m.alt, shift: m.shift }; acts } (PointerKind::Drag, SelDrag::Move { ids, from, began, perp, .. }) => { if !began && p.distance(from) < cx.tol(3.0) { - self.drag = SelDrag::Move { ids, from, last: p, began, perp, copy: m.alt }; + self.drag = SelDrag::Move { ids, from, last: p, began, perp, copy: m.alt, shift: m.shift }; return vec![]; } let mut out = vec![]; if !began { out.push(Action::Begin(if m.alt { "Copy in Perspective" } else { "Move in Perspective" }.into())); } - self.drag = SelDrag::Move { ids, from, last: p, began: true, perp, copy: m.alt }; + self.drag = SelDrag::Move { ids, from, last: p, began: true, perp, copy: m.alt, shift: m.shift }; out.extend(self.move_preview(cx)); out } @@ -289,10 +305,17 @@ impl Tool for PerspectiveSelectionTool { _ => vec![Action::Cancel], }; } - if let (ToolKey::Digit(5), SelDrag::Move { perp, began, .. }) = (key, &mut self.drag) { + if let (ToolKey::Digit(5), SelDrag::Move { perp, began, shift, .. }) = (key, &mut self.drag) { *perp = !*perp; + *shift = mods.shift; return if *began { self.move_preview(cx).into_iter().collect() } else { vec![] }; } + if matches!(key, ToolKey::Digit(1..=4)) + && let SelDrag::Move { began: true, shift, .. } = &mut self.drag + { + *shift = mods.shift; + return self.move_preview(cx).into_iter().collect(); + } let (dx, dy) = match key { ToolKey::Left => (-1, 0), ToolKey::Right => (1, 0), diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 02a030972b..51c0373344 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1104,6 +1104,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur An Alt-drag with the Selection, Direct Selection, Group Selection, Rotate, Scale, Reflect or Shear tool copies the selection on its first move, and the moves after it transform those copies; the previews of the Move, Rotate, Scale, Reflect and Shear dialogs with Copy and Preview on copy the selection once in the same way (#1429). An Alt-drag of objects in perspective with the Perspective Selection tool, and an Alt-drag of a plane widget with that tool or the Perspective Grid tool, copy the objects on the first move, and the moves after it move those copies (#1429). With the Perspective Selection tool, Ctrl+Alt-drag (Command+Option-drag on macOS) also copies objects on their perspective plane; Alt/Option-drag continues to do so. + With the Perspective Selection tool, holding Shift while moving or copying on a plane constrains the displacement to the nearest plane axis or 45° diagonal; releasing Shift resumes the raw pointer position, and 5 still moves perpendicular to the plane. When the desktop app opens a document on a thread of its own (#1245), that thread also reads the document's linked files and lays out its type, and the UI thread only adds the finished document: in release builds, the step left on the UI thread takes 0.02 ms instead of 1.04 s for a document with 12 linked 3000 × 2000 TIFFs, and it takes 0.1 ms instead of 0.85 s for one with 300 Auto Size area type objects, every second one in three columns. The Layers panel's Delete Selection, Duplicate Selection, Collect in New Layer, Merge Selected, Flatten Artwork, Release to Layers (Sequence) and row drags also take time in proportion to the size of the document, and so do Cut Artboard and Duplicate Artboard with their art and each move of an Alt-drag of one artboard with the Artboard tool while Move/Copy Artwork with Artboard is on (#1429). In Outline view the renderer draws paths and compound paths from the geometry it keeps for them between frames, and it culls the members of clip groups by the bounds it keeps for them. Layers with Preview off and the outlines of Image Trace objects are drawn the same way. From 9dcbe3688e38393a56d4f9a722bfd0643d436f6c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 00:14:07 -0700 Subject: [PATCH 019/260] Swatches: the French one-item delete prompt keeps the no-break space before ? --- crates/ui-egui/src/i18n/fr.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e6c5ef0be5..fae329cc5b 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -749,7 +749,7 @@ font-technology Variable Variables Delete the graphic style “{name}”? Supprimer le style graphique « {name} » ? Delete Theme Supprimer le thème Delete theme Supprimer le thème -@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Supprimer {n} nuance ou groupe ?|Supprimer ces {n} nuances et groupes ? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Supprimer {n} nuance ou groupe ?|Supprimer ces {n} nuances et groupes ? Delete these {n} graphic styles? Supprimer ces {n} styles graphiques ? Delete this saved preset Supprimer ce paramètre prédéfini enregistré Delete this {n} graphic style? Supprimer {n} style graphique ? From 9e8e091c8655f525bc3b96ae165baa96f6096640 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 00:00:47 -0700 Subject: [PATCH 020/260] Find Font: Find leaves out hidden and locked text select.font (the Find Font dialog's Find button) selected every text object using the font, including hidden or locked text and text in a hidden or locked group or layer. It now selects only text that is visible and unlocked through every group and layer, and not on a locked artboard. Text on a visible, unlocked template layer is still found. A font used only by hidden or locked text selects nothing. --- crates/engine/src/cmd/fonts.rs | 63 +++++++++++++++++++++++++++++++--- 1 file changed, 58 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 0aaa8ba39c..6b134afb60 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -38,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> { "Select Text by Font", [], None, - "{family, style?} select the text objects using the font → {count}", + "{family, style?} select the text objects using the font that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard → {count}", has_doc, select_font ), @@ -454,16 +454,21 @@ fn select_font(s: &mut Session, p: &Value) -> Result<Value> { let style = str_param(p, "style").map(str::to_string); let ids = scope(s, false)?; let d = &s.doc()?.doc; + // Only text the Selection tool can reach: not hidden or locked, in a hidden or locked group + // or layer, or on a locked artboard. + let editable = d.editable(); let hits: Vec<NodeId> = ids .into_iter() .filter(|id| { - text(d, *id).is_some_and(|t| { - t.runs.iter().any(|r| { - r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|x| r.style.font_style.eq_ignore_ascii_case(x)) + editable(*id) + && text(d, *id).is_some_and(|t| { + t.runs.iter().any(|r| { + r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|x| r.style.font_style.eq_ignore_ascii_case(x)) + }) }) - }) }) .collect(); + drop(editable); let n = hits.len(); s.select(|_, sel| sel.set(hits))?; Ok(json!({ "count": n })) @@ -568,6 +573,54 @@ mod tests { assert!(s.execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Nope"}})).is_err()); let _ = a; } + + /// Select Text by Font leaves out hidden and locked text, and text inside a hidden or locked + /// group or layer. Text on a visible, unlocked template layer is selected. + #[test] + fn select_font_skips_hidden_and_locked_text() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let text = |s: &mut Session, y: i32, font: &str| { + s.execute("text.create", &json!({"x": 10, "y": y, "text": "Serif", "font": font})).unwrap()["id"].as_u64().unwrap() + }; + let mut ids = vec![]; + for y in [20, 40, 60, 80, 100] { + ids.push(text(&mut s, y, "Source Serif 4")); + } + // Inter is used only by hidden or locked text. + let only_hidden = text(&mut s, 120, "Inter"); + for (id, group, cmd) in [ + (ids[1], false, "object.hide"), + (ids[2], false, "object.lock"), + (ids[3], true, "object.hide"), + (ids[4], true, "object.lock"), + (only_hidden, false, "object.hide"), + ] { + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + if group { + s.execute("object.group", &json!({})).unwrap(); + } + s.execute(cmd, &json!({})).unwrap(); + } + let mut layer_text = |props: &[Value]| { + let layer = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap(); + let id = text(&mut s, 140, "Source Serif 4"); + for p in props { + let mut p = p.clone(); + p["id"] = json!(layer); + s.execute("layer.setProps", &p).unwrap(); + } + id + }; + layer_text(&[json!({"visible": false})]); + layer_text(&[json!({"locked": true})]); + // Template on locks the layer; unlocking it makes its text selectable again. + let template = layer_text(&[json!({"template": true}), json!({"locked": false})]); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 2); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(ids[0]), NodeId(template)]); + assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 0); + assert!(s.doc().unwrap().selection.objects.is_empty()); + } } #[cfg(test)] From 9571ae0a462b678c591304ec43cdce538b34b166 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 23:48:53 -0700 Subject: [PATCH 021/260] Outline Stroke, Expand: hidden and locked objects stay hidden and locked The art that replaces an outlined or expanded path did not take the path's hidden, locked or Knockout Shape state. Outline Stroke on a hidden path, or Expand on a group with a hidden member, made the new art visible (a filled and stroked path became half visible: the outline shown, the fill copy hidden), and a locked member's art was unlocked. The replacement now takes the path's visibility, lock and Knockout Shape state, and the fill copies and clipping paths inside it are shown and unlocked, so showing or unlocking the new art shows or unlocks all of it. This covers Outline Stroke, and Expand's strokes, gradient fills and pattern fills. --- crates/engine/src/cmd/pathops.rs | 5 +++- crates/engine/src/tests/objexpand.rs | 29 +++++++++++++++++++++++ crates/engine/src/tests/outlinestroke.rs | 30 ++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index ae9670b55d..56a223e133 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -888,11 +888,13 @@ pub(crate) fn outline_strokes(d: &mut Document, brushes: &[vectorcraft_brush::Br } /// A plain copy of path `l` (new ids, no transparency, name or mask) painted with `items`. +/// The copy is shown and unlocked. pub(crate) fn styled_copy(d: &mut Document, l: &Node, items: Vec<AppearanceItem>) -> Node { let mut f = d.reid(l); f.appearance = Appearance { items, ..Default::default() }.into(); f.opacity = 1.0; f.blend = BlendMode::Normal; + (f.visible, f.locked, f.knockout_shape) = (true, false, false); f.name = None; f.extras_mut().mask = None; if let NodeKind::Path { live, .. } = &mut f.kind { @@ -903,7 +905,7 @@ pub(crate) fn styled_copy(d: &mut Document, l: &Node, items: Vec<AppearanceItem> /// What stands for object `l` once its appearance became `parts` (paint order): the one part (in a /// group when it has effects of its own) or a group of them, with `l`'s transparency, name, opacity -/// mask and effects. `None` without parts. +/// mask, effects, and hidden, locked and knockout-shape states. `None` without parts. pub(crate) fn assemble(d: &mut Document, l: &Node, mut parts: Vec<Node>) -> Option<Node> { let root = match parts.len() { 0 => return None, @@ -911,6 +913,7 @@ pub(crate) fn assemble(d: &mut Document, l: &Node, mut parts: Vec<Node>) -> Opti _ => Node::group(d.alloc_id(), parts.into_iter().map(Arc::new).collect()), }; let mut root = with_transparency(d, root, l.opacity, l.blend); + (root.visible, root.locked, root.knockout_shape) = (l.visible, l.locked, l.knockout_shape); root.name = l.name.clone(); root.extras_mut().mask = l.extras().mask.clone(); root.appearance.effects = l.appearance.effects.clone(); diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index 2c9e4ef22b..59b8db8909 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -159,6 +159,35 @@ fn eight_strips_match_the_gradient_samples() { assert!(matches!(selected(&s).appearance.fill_paint(), Paint::Gradient(_))); } +#[test] +fn expanding_a_group_keeps_its_hidden_and_locked_members_hidden_and_locked() { + // A hidden stroked square with a gradient fill, a locked square with a pattern fill and a + // plain square, grouped. + let mut s = session(); + let pat = pattern_rect(&mut s, Rect::new(20.0, 100.0, 80.0, 160.0), false); + let grad = gradient_rect(&mut s, Rect::new(20.0, 20.0, 80.0, 80.0), white_black(), true); + let plain = NodeId(run(&mut s, "shape.rectangle", json!({"x": 100, "y": 20, "width": 40, "height": 40}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [pat.0, grad.0, plain.0]})); + run(&mut s, "object.group", json!({})); + s.edit("t", |d, _| { + d.node_mut(grad).unwrap().visible = false; + d.node_mut(pat).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + run(&mut s, "object.expand", json!({})); + let g = selected(&s); + let ch = g.children().unwrap(); + assert_eq!(ch.len(), 3); + assert!(!clip_parts(&ch[0]).1.is_empty() && ch[0].locked && ch[0].visible, "the pattern's tiles stay locked: {:?}", ch[0]); + assert!(!ch[1].visible && !ch[1].locked, "the gradient square's art stays hidden: {:?}", ch[1]); + assert!(ch[2].visible && !ch[2].locked); + // Showing or unlocking the new art shows or unlocks all of it. + for c in ch[..2].iter().flat_map(|c| c.children().unwrap().iter()) { + c.walk(&mut |n| assert!(n.visible && !n.locked, "{n:?}")); + } +} + #[test] fn a_radial_gradient_becomes_concentric_ellipses() { let mut s = session(); diff --git a/crates/engine/src/tests/outlinestroke.rs b/crates/engine/src/tests/outlinestroke.rs index 17a6b5a09f..fad35ad434 100644 --- a/crates/engine/src/tests/outlinestroke.rs +++ b/crates/engine/src/tests/outlinestroke.rs @@ -122,6 +122,36 @@ fn every_stroke_is_outlined_in_paint_order() { assert_eq!(d.layers[0].children().unwrap()[0].appearance.items.len(), 3); } +/// The art that stands for an outlined path keeps the path's hidden, locked and knockout-shape +/// states, so a hidden member of a selected group stays hidden. +#[test] +fn outlined_art_keeps_the_hidden_locked_and_knockout_shape_states() { + let mut s = session(); + // A filled and stroked square (a fill copy and an outline) and a stroked line (one outline). + let sq = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + let ln = line(&mut s, json!({"weight": 4})); + s.execute("select.set", &json!({"ids": [sq.0, ln.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.edit("t", |d, _| { + d.node_mut(sq).unwrap().visible = false; + let l = d.node_mut(ln).unwrap(); + l.locked = true; + l.knockout_shape = true; + Ok(()) + }) + .unwrap(); + let g = outline(&mut s); + let ch = g.children().unwrap(); + assert_eq!(ch.len(), 2); + let (sq, ln) = (&ch[0], &ch[1]); + assert!(!sq.visible && !sq.locked, "the square's art stays hidden: {sq:?}"); + assert_eq!(sq.children().map(|c| c.len()), Some(2), "a fill copy and the outline"); + assert!(sq.children().unwrap().iter().all(|c| c.visible && !c.locked), "showing it shows all of it: {sq:?}"); + assert!(ln.visible && ln.locked && ln.knockout_shape, "the line's outline stays locked: {ln:?}"); +} + /// The live effect on a stroke item outlines that stroke (its own weight), not the top stroke. #[test] fn the_live_effect_outlines_the_stroke_it_sits_on() { From 06e8d711ae9cfa92b907fe782d2bdeb6f1d9129b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 23:18:01 -0700 Subject: [PATCH 022/260] DXF export: an open path of one straight segment is written as a LINE An open path with a single straight segment was written as a two-vertex LWPOLYLINE (POLYLINE before R14). It is now a LINE entity from its start to its end point. A stroke with a weight in R12, R13 and R14 keeps its polyline, since a LINE has no width. Closed paths and paths with more than one segment are unchanged. Part of #1299. --- crates/cad/src/import/tests.rs | 28 ++++++++++++++++ crates/cad/src/scene.rs | 22 ++++++++++--- crates/cad/src/tests.rs | 39 +++++++++++++++++++++++ crates/engine/src/cmd/fileio/tests_dxf.rs | 2 +- docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 6 files changed, 89 insertions(+), 7 deletions(-) diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index d0dde65c90..6bd3d1c106 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -1049,6 +1049,34 @@ fn drawings_the_export_writes_read_back() { } } +#[test] +fn a_lone_segment_reads_back_from_the_line_the_export_writes() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut b = kurbo::BezPath::new(); + b.move_to((20.0, 30.0)); + b.line_to((120.0, 70.0)); + let id = doc.alloc_id(); + let black = Appearance::basic(Paint::None, Paint::solid(Color::rgb8(0, 0, 0)), 1.0); + doc.insert(Some(layer), 0, Node::path(id, vectorcraft_geom::PathData::from_bezpath(&b), black)).unwrap(); + for version in crate::DxfVersion::ALL.into_iter().filter(|v| v.r2000()) { + let opts = crate::DxfOptions { version, unit: Unit::Points, region: doc.artboards[0].rect, ..crate::DxfOptions::default() }; + let out = crate::export(&doc, &opts).unwrap(); + assert!(std::str::from_utf8(&out.bytes).unwrap().contains("\nLINE\n"), "{version:?}"); + let back = open(&out.bytes, &points()); + let art = leaves(&back.document); + assert_eq!(art.len(), 1, "{version:?}"); + let path = art[0].path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1, "{version:?}"); + assert!(!path.subpaths[0].closed, "{version:?}"); + let shift = Affine::translate((0.0, 100.0 - height(&back.document))); + let points = path_points(&art[0]); + assert_eq!(points.len(), 17, "{version:?}: one segment"); + let ends = [shift * points[0], shift * points[16]]; + assert!(ends[0].distance(Point::new(20.0, 30.0)) < 1e-6 && ends[1].distance(Point::new(120.0, 70.0)) < 1e-6, "{version:?}: {ends:?}"); + } +} + #[test] fn closed_control_point_splines_stay_closed_through_export_and_import() { // (explicitly closed, ends where it starts): coincident endpoints alone do not close a path. diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index 7ab1d17f83..f75d437763 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -740,9 +740,9 @@ impl<'a> Scene<'a> { self.e.int(98, 0); } - /// Path `bp` as lines: polylines for straight subpaths (and for curves in R12, flattened), - /// cubic splines for curved ones. `width`: the stroke weight, which DXF before 2000 gives - /// polylines as a width. + /// Path `bp` as lines: a line for an open subpath of one straight segment, polylines for + /// other straight subpaths (and for curves in R12, flattened), cubic splines for curved ones. + /// `width`: the stroke weight, which DXF before 2000 gives polylines as a width. fn lines(&mut self, bp: &BezPath, style: &EntityStyle, width: f64) { let v = self.o.version; let width = (!v.r2000() && width > 0.0).then_some(width * self.k); @@ -755,7 +755,11 @@ impl<'a> Scene<'a> { if sub.closed && pts.len() > 2 && pts.last().is_some_and(|p| p.distance(sub.start) <= 1e-9) { pts.pop(); } - self.polyline(&pts, sub.closed, style, width); + // A LINE has no width, so a stroke before 2000 keeps its polyline width. + match (sub.closed, width, pts.as_slice()) { + (false, None, &[a, b]) => self.line(a, b, style), + _ => self.polyline(&pts, sub.closed, style, width), + } } else if (v.handles() || width.is_none()) && self.circular(&sub, style) { // Native circles/arcs are preferred by CAD/CAM software. In R12, however, a // stroked curve must stay on the flattened POLYLINE path so groups 40/41 retain @@ -778,6 +782,16 @@ impl<'a> Scene<'a> { } } + /// A line from `a` to `b` (document space). + fn line(&mut self, a: Point, b: Point, style: &EntityStyle) { + let (a, b) = (self.pt(a), self.pt(b)); + let layer = self.layer.clone(); + let h = self.handle(); + self.e.entity("LINE", h, fixed::MODEL_RECORD, &layer, style, "AcDbLine"); + self.e.xyz(10, a.x, a.y); + self.e.xyz(11, b.x, b.y); + } + /// A polyline through `pts` (document space): lightweight from R14, else a polyline with a /// vertex entity per point. fn polyline(&mut self, pts: &[Point], closed: bool, style: &EntityStyle, width: Option<f64>) { diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index 30a8d1a819..d0abd13e84 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -214,6 +214,45 @@ fn circles_and_circular_arcs_are_native_dxf_entities() { assert_eq!(kinds(&export(&ellipse, &opts(&ellipse)).unwrap()), ["SPLINE"]); } +#[test] +fn a_lone_straight_segment_is_a_line() { + let segment = |closed: bool, extra: Option<Point>| { + let mut b = vectorcraft_geom::BezPath::new(); + b.move_to(Point::new(20.0, 30.0)); + b.line_to(Point::new(120.0, 70.0)); + if let Some(p) = extra { + b.line_to(p); + } + if closed { + b.close_path(); + } + PathData::from_bezpath(&b) + }; + let d = doc_with(|d| vec![path(d, segment(false, None), Paint::None, Paint::solid(Color::BLACK), 1.0)]); + for version in DxfVersion::ALL.into_iter().filter(|v| v.r2000()) { + let e = entities(&export(&d, &DxfOptions { version, ..opts(&d) }).unwrap()); + assert_eq!(e.iter().map(|x| kind(x)).collect::<Vec<_>>(), ["LINE"], "{version:?}"); + assert_eq!(e[0].iter().rfind(|p| p.0 == 100).map(|p| p.1.as_str()), Some("AcDbLine"), "{version:?}"); + assert_eq!((all(&e[0], 10), all(&e[0], 20)), (vec![20.0], vec![70.0]), "{version:?}: y up from the artboard's bottom"); + assert_eq!((all(&e[0], 11), all(&e[0], 21)), (vec![120.0], vec![30.0]), "{version:?}"); + } + + // Without a width (R12 writes a fill as its outline), R12 writes a LINE too; a stroke weight + // before 2000 keeps its polyline width. + let filled = doc_with(|d| vec![path(d, segment(false, None), Paint::solid(Color::BLACK), Paint::None, 0.0)]); + let r12 = |d: &Document| kinds(&export(d, &DxfOptions { version: DxfVersion::R12, ..opts(d) }).unwrap()); + assert_eq!(r12(&filled), ["LINE"]); + assert_eq!(r12(&d), ["POLYLINE", "VERTEX", "VERTEX", "SEQEND"]); + let r14 = entities(&export(&d, &DxfOptions { version: DxfVersion::R14, ..opts(&d) }).unwrap()); + assert_eq!((kind(&r14[0]), get(&r14[0], 43)), ("LWPOLYLINE", Some("1"))); + + // A closed segment and two segments stay polylines. + for p in [segment(true, None), segment(false, Some(Point::new(150.0, 20.0)))] { + let d = doc_with(|d| vec![path(d, p, Paint::None, Paint::solid(Color::BLACK), 1.0)]); + assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["LWPOLYLINE"]); + } +} + #[test] fn r12_stroked_circles_keep_polyline_width() { let d = doc_with(|d| vec![path(d, shapes::ellipse(Rect::new(20.0, 20.0, 80.0, 80.0)), Paint::None, Paint::solid(Color::BLACK), 3.0)]); diff --git a/crates/engine/src/cmd/fileio/tests_dxf.rs b/crates/engine/src/cmd/fileio/tests_dxf.rs index eec800d74a..298adeb111 100644 --- a/crates/engine/src/cmd/fileio/tests_dxf.rs +++ b/crates/engine/src/cmd/fileio/tests_dxf.rs @@ -93,7 +93,7 @@ fn selected_only_exports_the_selection_in_its_layers() { let line = s.execute("shape.line", &json!({"x1": 0, "y1": 90, "x2": 90, "y2": 90})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [line]})).unwrap(); let dxf = text(&s.execute("document.export", &json!({"format": "dxf", "selectedOnly": true})).unwrap()); - assert_eq!(entities(&dxf), ["LWPOLYLINE"]); + assert_eq!(entities(&dxf), ["LINE"]); assert!(dxf.contains("\n 2\nTop\n") && !dxf.contains("\n 2\nLayer 1\n"), "only the selection's layer"); s.execute("select.none", &json!({})).unwrap(); let e = s.execute("document.export", &json!({"format": "dxf", "selectedOnly": true})).unwrap_err().to_string(); diff --git a/docs/mcp.md b/docs/mcp.md index 6fc3dd98bf..76f8648ac3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3832,7 +3832,8 @@ without its formatting, taking the style at the caret. `document.exportDxf` (also `document.export` / `export` with format `dxf`) writes a CAD drawing, ASCII DXF R12 to 2018 (`version`: `R12`, `R13`, `R14`, `2000`, `2004`, `2007`, `2010`, `2013`, `2018`; default `2018`). Each layer becomes a DXF layer (hidden layers switched off, locked ones locked, non-printing ones not plotted; template layers left out), -straight paths become polylines, curved ones cubic splines through every anchor, fills their outlines followed by +straight paths become polylines (an open path of one straight segment becomes a line, except for a stroke weight +before 2000), curved ones cubic splines through every anchor, fills their outlines followed by solid hatches (laser and cutter software reads the outlines and skips hatches; R12 has no hatches: the outlines alone), strokes lines with their lineweight and a linetype per dash pattern, and placed images image entities linked to PNG or JPEG files (`rasterFormat`) written next to the drawing (`linked` in the result). Coordinates are y up diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 416501d553..9eb17cc09e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1041,7 +1041,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - EPS and PostScript import keeps a CMYK image's ink amounts, as PDF import does: the samples of `image` and `colorimage` in a CMYK color space, and of a CMYK JPEG read through `DCTDecode`, come in as a CMYK TIFF, read through the image's Decode array, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask (`crates/eps/src/import/tests_images.rs`). Such images came in as RGB PNGs. - EPS and PostScript import reads image data through `CCITTFaxDecode`: Group 4 (ITU-T T.6) and Group 3 one-dimensional and mixed (ITU-T T.4) data, with the filter's `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1` parameters, decodes to 1-bit rows for `image` and `imagemask`. Damaged data keeps the rows decoded before it (damage in the first row is a PostScript `ioerror`), and parameters out of range or past the 256 MiB limit on decoded data are refused (`crates/eps/src/import/tests_images.rs`). Reading such a file stopped at an error naming the filter, and the file opened from a fallback, such as its preview or the art drawn before the image, or did not open. - EPS and PostScript `.ai` import undoes the TIFF predictor (`/Predictor 2`) of `FlateDecode` and `LZWDecode` data at 1, 2, 4 and 16 bits a component as well as 8: each component adds the same component of the pixel to its left within its bit width, 16-bit components add as big-endian numbers, and each row starts again (ISO 32000-1 §7.4.4.4; `crates/eps/src/import/tests_images.rs`, `crates/engine/src/cmd/fileio/tests_epsimport.rs`). At those depths the image drew the stored differences instead of its samples. - - DXF control-point SPLINE import honors its closed flag (#1299 follow-up after #1320 fixed export), including rational curves; open curves whose endpoints meet stay open. Own-fixture regressions cover controls/knots, fit-point fallback and all export versions (`crates/cad/src/import/tests.rs`, `crates/cad/src/tests.rs`); native save/read checked. Circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE, and a non-circular ellipse keeps the existing fallback (`crates/cad/src/tests.rs`); CNC preset and VCarve QA remain pending. + - DXF control-point SPLINE import honors its closed flag (#1299 follow-up after #1320 fixed export), including rational curves; open curves whose endpoints meet stay open. Own-fixture regressions cover controls/knots, fit-point fallback and all export versions (`crates/cad/src/import/tests.rs`, `crates/cad/src/tests.rs`); native save/read checked. Circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE, and a non-circular ellipse keeps the existing fallback (`crates/cad/src/tests.rs`); an open path of one straight segment exports as a LINE (R12 to R14 strokes with a weight stay polylines, which carry the width) and reads back as the same segment (`crates/cad/src/tests.rs`, `crates/cad/src/import/tests.rs`); CNC preset and VCarve QA remain pending. - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). From b493e601a91fbec9b893691c48fa4470f4bbdfc5 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 23:40:58 -0700 Subject: [PATCH 023/260] Docs: leave the DXF row of file-format-parity.md to #4796 The ELLIPSE note stays in docs/gaps.md; the open #4796 rewrites the same file-format-parity.md row. --- docs/file-format-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index ffab9f5859..dc23c77b7e 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -98,7 +98,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CID-keyed CJK type not read; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as `<title>`, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`) | -| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; closed four-cubic ellipses, and circles scaled out of proportion, export as ELLIPSE in R13–2018; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). CNC preset and VCarve QA remain open | +| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). CNC preset and VCarve QA remain open | | DWG | open, export | no | no | no open spec; DXF instead | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) | | PSD | open, place, export | yes (merged image, every mode and depth) | yes (layered, max editability) | placing as layers (Photoshop Import Options) missing; the embedded ICC profile's tags are 4-byte aligned (#1584) | From 958566468abb925cd45bfd6a9fcdf6346a9e07b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 00:29:28 -0700 Subject: [PATCH 024/260] DXF export: dashed polylines continue their linetype around vertices A polyline with a linetype now sets group 70 bit 128, so the dash pattern runs on through its vertices instead of restarting at each corner. This applies to LWPOLYLINE and the R12 POLYLINE. --- crates/cad/src/scene.rs | 3 ++- crates/cad/src/tests.rs | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index a292d5a7f5..34e69d6edb 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -872,7 +872,8 @@ impl<'a> Scene<'a> { let pts: Vec<Point> = pts.iter().map(|p| self.pt(*p)).collect(); let layer = self.layer.clone(); let h = self.handle(); - let flags = i64::from(closed); + // Bit 128: a linetype runs on through the vertices instead of restarting at each one. + let flags = i64::from(closed) | if style.linetype.is_some() { 128 } else { 0 }; if self.o.version.lwpolyline() { self.e.entity("LWPOLYLINE", h, fixed::MODEL_RECORD, &layer, style, "AcDbPolyline"); self.e.int(90, pts.len() as i64); diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index aff8489c44..f02047492a 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -696,6 +696,30 @@ fn dashes_that_start_part_way_into_their_pattern_are_outlined() { assert_eq!(get(&entities(&editable)[0], 6), Some("DASHED1")); } +#[test] +fn dashed_polylines_continue_their_pattern_around_corners() { + let rect = |dash: Option<Dash>| { + doc_with(|d| { + let mut n = path(d, shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), Paint::None, Paint::solid(Color::BLACK), 1.0); + if let Some(st) = n.appearance.stroke_mut() { + st.dash = dash.clone(); + } + vec![n] + }) + }; + let flags = |out: &DxfOutput| entities(out).first().and_then(|e| get(e, 70).map(str::to_string)); + // Group 70 bit 128 makes the linetype run on through the vertices instead of restarting + // at each one; a solid polyline keeps only its closed bit. + let dashed = rect(Some(Dash { pattern: vec![6.0, 3.0], offset: 0.0, align_corners: false })); + for o in [opts(&dashed), DxfOptions { alter_paths: true, ..opts(&dashed) }, DxfOptions { preserve: Preserve::Editability, ..opts(&dashed) }] { + assert_eq!(flags(&export(&dashed, &o).unwrap()).as_deref(), Some("129")); + } + let r12 = export(&dashed, &DxfOptions { version: DxfVersion::R12, ..opts(&dashed) }).unwrap(); + assert_eq!((kinds(&r12).first().map(String::as_str), flags(&r12).as_deref()), (Some("POLYLINE"), Some("129"))); + let solid = rect(None); + assert_eq!(flags(&export(&solid, &opts(&solid)).unwrap()).as_deref(), Some("1")); +} + fn text_doc(text: &str, size: f64) -> Document { doc_with(|d| { let style = CharStyle { size, fill: Paint::solid(Color::rgb(0.0, 0.5, 0.0)), ..CharStyle::default() }; From 2a5e2e8588e3f3bc497c621c83b291659a1ba00d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 22:40:49 -0700 Subject: [PATCH 025/260] Blob Brush: the tip preview draws 0% Roundness as thin as the brush The Tool Options tip preview floored the short axis at 1% of the long one, while the brush draws 0% Roundness at 0.1%. The preview now uses the same 0.1% minimum, with a test that compares it with the tip the brush draws. --- crates/ui-egui/src/dialogs/freehand.rs | 8 +++++++- crates/ui-egui/src/dialogs/freehand/tests.rs | 8 ++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index 85d8630567..bd6068638c 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -276,7 +276,7 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { let u = egui::vec2(a.cos() as f32, -a.sin() as f32); let v = egui::vec2(-u.y, u.x); let long = 18.0; - let short = long * (d.f64("roundness", 100.0).clamp(0.0, 100.0) as f32 / 100.0).max(0.01); + let short = long * blob_tip_short_ratio(d.f64("roundness", 100.0)); let dab = |center: egui::Pos2, color: egui::Color32| { let points = (0..32) .map(|i| { @@ -295,6 +295,12 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { } } +/// The preview tip's short axis as a fraction of its long axis: Roundness in percent, with 0 +/// percent drawn as 0.1 percent, the minimum the brush draws with. +fn blob_tip_short_ratio(roundness: f64) -> f32 { + (roundness.clamp(0.0, 100.0) as f32 / 100.0).max(0.001) +} + /// OK: set the tool's options. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { let values: Map<String, Value> = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 0136d25c51..81aeae9b5a 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -28,6 +28,14 @@ fn blob_tip_fields_confirm_and_cancel() { assert_eq!(app.session.tool_options_of("blobBrush")["roundness"], json!(0.0)); } +#[test] +fn the_tip_preview_is_as_flat_as_the_tip_the_brush_draws() { + for roundness in [-5.0, 0.0, 0.05, 0.1, 1.0, 50.0, 100.0, 120.0] { + let drawn = vectorcraft_tools::draw2::blob_tip(0.0, roundness).as_coeffs()[3] as f32; + assert!((blob_tip_short_ratio(roundness) - drawn).abs() < 1e-6, "roundness {roundness}: drawn {drawn}"); + } +} + /// The labels the open dialog paints. fn painted(app: &mut VectorcraftApp) -> String { crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) From b1ed0a512b207794dc8a42cea0448bd21a0c6c1b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 22:44:50 -0700 Subject: [PATCH 026/260] Brushes: opacity masks on art brush pieces bend with the art An art, scatter or pattern brush piece whose art carries a linked opacity mask was bent along the path while the mask's art kept its place in the brush's own coordinates, so the mask no longer covered the piece. The mask's art now bends and has its strokes scaled with the object it masks, on bent runs, on straight runs and where the brush narrows along the path. A mask whose art cannot bend becomes an empty group. The anchor budget for a brushed stroke counts the mask's art as well. --- crates/brush/src/warp.rs | 71 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 69 insertions(+), 2 deletions(-) diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index 99f7e63048..d66d5679fb 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -41,7 +41,8 @@ const MASK_STEPS: usize = 32; /// space, so the art keeps its curves (#3926). Where that cannot be done in no more anchors than /// chords would take, the path is flattened with `flat_tol` (art space) and subdivided so no chord /// is longer than `max_du` along x, as it always was. Stroke widths scale by `width_scale`. -/// Text, images and symbol instances can't bend and are dropped. +/// Text, images and symbol instances can't bend and are dropped. The art of a linked opacity mask +/// bends with the object it masks. pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, doc_tol: f64, width_scale: f64) -> Option<Node> { let mut out = n.clone(); out.appearance.scale_strokes(width_scale); @@ -63,9 +64,21 @@ pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max } _ => return None, } + map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale)); Some(out) } +/// Replace the art of `n`'s linked opacity mask, if it has one, with what `map` makes of it. Where +/// `map` draws nothing, the mask's art becomes an empty group. +fn map_mask(n: &mut Node, map: impl FnOnce(&Node) -> Option<Node>) { + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + && m.linked + { + let id = m.art.id; + m.art = Arc::new(map(&m.art).unwrap_or_else(|| Node::group(id, vec![]))); + } +} + /// Each subpath of `p` through `f`: fitted cubics when they take no more anchors than the chords /// would, else the chords. Points `f` cannot place (not finite) are left out of the chords. fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64) -> PathData { @@ -338,7 +351,8 @@ fn affine_fit(f: &dyn Fn(Point) -> Point, b: Rect, tol: f64) -> Option<Affine> { /// Everything else matches [`warp_node`] deliberately, so curves are the only difference between /// the two routes: the same node kinds are kept and the rest dropped, `live` is cleared on every /// path, an empty path or a group left with no children is dropped, and strokes are scaled by -/// `width_scale` at every level rather than by the transform's own factor. +/// `width_scale` at every level rather than by the transform's own factor, the art of linked +/// opacity masks included. fn affine_node(n: &Node, a: Affine, width_scale: f64) -> Option<Node> { let mut out = prepared(n, width_scale)?; out.transform(a, false); @@ -365,6 +379,7 @@ fn prepared(n: &Node, width_scale: f64) -> Option<Node> { } _ => return None, } + map_mask(&mut out, |art| prepared(art, width_scale)); Some(out) } @@ -416,6 +431,7 @@ fn widen_strokes(n: &Node, factor: &dyn Fn(&Node) -> f64) -> Node { if let NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Compound { children, .. } = &mut out.kind { *children = children.iter().map(|c| Arc::new(widen_strokes(c, factor))).collect(); } + map_mask(&mut out, |art| Some(widen_strokes(art, factor))); out } @@ -590,6 +606,9 @@ fn anchors_of(n: &Node) -> usize { if let Some(c) = n.children() { stack.extend(c.iter().map(Arc::as_ref)); } + if let Some(m) = &n.extras().mask { + stack.push(&m.art); + } } total } @@ -1133,4 +1152,52 @@ mod tests { } } } + + /// A linked opacity mask on brush art bends and widens with the art, on a bent run and on a + /// straight one, so a mask drawn over the art still covers it. An unlinked mask stays put. + #[test] + fn a_linked_opacity_mask_bends_with_the_art() { + let b = Rect::new(0.0, -20.0, 40.0, 20.0); + let stroked = |id: u64| { + Node::path( + NodeId(id), + vectorcraft_geom::shapes::ellipse(b), + Appearance::basic( + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + 2.0, + ), + ) + }; + let masked = |linked: bool| { + let mut n = stroked(0); + let mut mask = vectorcraft_doc::OpacityMask::new(stroked(1), true); + mask.linked = linked; + n.extras_mut().mask = Some(Box::new(mask)); + n + }; + let round = vectorcraft_geom::shapes::ellipse(Rect::new(0.0, 0.0, 400.0, 400.0)).to_bezpath(); + let bent_track = tracks(&round, 0.05).remove(0); + let mut line = BezPath::new(); + line.move_to((0.0, 0.0)); + line.line_to((320.0, 0.0)); + let straight_track = tracks(&line, 0.01).remove(0); + let along = AlongMap::linear(b.width(), 100.0, 140.0); + for (name, t) in [("bent", &bent_track), ("straight", &straight_track)] { + let out = bend(t, &masked(true), b, along, 2.0).expect("the art is drawn"); + let mask = out.extras().mask.as_ref().expect("the mask is kept"); + assert_eq!(mask.art.kind, out.kind, "{name} run: the mask's art bends with the art it was drawn over"); + assert_eq!(mask.art.appearance, out.appearance, "{name} run: the mask's strokes widen with the art's"); + + let out = bend(t, &masked(false), b, along, 2.0).expect("the art is drawn"); + let mask = out.extras().mask.as_ref().expect("the mask is kept"); + assert_eq!(*mask.art, stroked(1), "{name} run: an unlinked mask stays where it was"); + + let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5).expect("the art is drawn"); + let mask = out.extras().mask.as_ref().expect("the mask is kept"); + assert_eq!(mask.art.kind, out.kind, "{name} run, widened: the mask's art bends with the art"); + assert_eq!(mask.art.appearance, out.appearance, "{name} run, widened: the mask's strokes narrow with the art's"); + } + assert_eq!(anchors_of(&masked(true)), 8, "the anchor budget counts the mask's art"); + } } From 8aa8bb4d9d8a63ffbcd6e196d118b6e84a89f8f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 18:53:25 -0700 Subject: [PATCH 027/260] Render: a mask art root, symbol art root or thumbnail keeps its own opacity mask The renderer drew the root node of an opacity mask's art, of placed symbol art, of an art brush piece, of an Image Trace source image and of a node thumbnail without its own opacity mask. Make Opacity Mask uses the top object as the mask art, so a mask made from an object that already had an opacity mask ignored that inner mask. These roots now draw through the same masked group as any other node, still drawn whatever their visibility and bounds, and an incomplete inner mask still leaves out the outer object. --- crates/render/src/brush_fx.rs | 32 +++++++- crates/render/src/renderer.rs | 2 +- crates/render/src/renderer/nodes.rs | 46 +++++++---- crates/render/src/tests.rs | 121 ++++++++++++++++++++++++++++ 4 files changed, 184 insertions(+), 17 deletions(-) diff --git a/crates/render/src/brush_fx.rs b/crates/render/src/brush_fx.rs index cb370520fa..c19bfb6e6b 100644 --- a/crates/render/src/brush_fx.rs +++ b/crates/render/src/brush_fx.rs @@ -212,7 +212,7 @@ impl Renderer { self.draw_kept_node(ctx, f, p); self.fx_owner = owner; } else { - self.draw_node(ctx, f, p, true); + self.draw_forced_arc(ctx, f, p); } } (self.made_again, self.cur) = outer; @@ -260,6 +260,36 @@ mod tests { assert_eq!(again.pixels, img.pixels); } + #[test] + fn art_brush_piece_applies_its_root_mask() { + use vectorcraft_brush::{ArtBrush, ArtScale, Brush, BrushKind, Colorization}; + use vectorcraft_doc::OpacityMask; + + let mut d = doc_with_line(Some("Masked art"), 1.0); + let mut art = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(0.0, -5.0, 10.0, 5.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + let black = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + art.extras_mut().mask = Some(Box::new(OpacityMask::new(black, true))); + let brush = Brush { + name: "Masked art".into(), + kind: BrushKind::Art(ArtBrush { art, scale: ArtScale::Stretch, colorization: Colorization::None, ..Default::default() }), + }; + vectorcraft_brush::store(&mut d, &[brush]); + + let mut renderer = Renderer::new(); + for _ in 0..2 { + let img = render(&mut renderer, &d); + assert_eq!(img.pixel(100, 50), [255, 255, 255, 255]); + } + } + /// Object opacity fades a brushed stroke's art as a whole, with or without a dash and a fill: /// the same as the object at full opacity inside a group at that opacity. #[test] diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 26702d57b0..3593bf0413 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -361,7 +361,7 @@ impl Renderer { self.begin_frame(); (self.knockout, self.nested, self.backdrop, self.picture) = (false, 0, None, None); self.clip_paths.clear(); - self.draw_node(&mut ctx, &frame, n, true); + self.draw_forced_arc(&mut ctx, &frame, &Arc::new(n.clone())); let pm = self.finish(&mut ctx, vello_cpu::RasterizerSettings::default()); self.end_frame(); Some(Rendered { width: size, height: size, pixels: pm.data_as_u8_slice().to_vec() }) diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index edf3409ac2..6586be0b3b 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -157,23 +157,39 @@ impl Renderer { self.stats.drawn += 1; return; } - if let Some(m) = a.extras().mask.as_deref() - && !m.disabled - && !f.opts.outline - && !self.is_shape(a) - { - // A masked object is a non-isolated group of its own, drawn over its own pixels: the - // mask is rendered over those only. - let bounds = self.bounds_of(f.symbols, a); - let Some((r, sub)) = group::area(ctx, f, bounds) else { return }; - let Some(mask) = self.mask_values(&sub, m, r.w, r.h) else { return }; - let blends = a.blend != vectorcraft_color::BlendMode::Normal || (!a.isolate && self.blends_through(a)); - self.group(ctx, f, Composite { mask: Some(mask), blends, bounds, ..Default::default() }, &mut |r, c, fr| r.draw_arc_body(c, fr, a)); + if self.draw_masked_arc(ctx, f, a, false) { return; } self.draw_arc_body(ctx, f, a); } + /// Draw `a` through its opacity mask when it has one. Forced roots draw regardless of their + /// visibility and bounds. + fn draw_masked_arc(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc<Node>, force: bool) -> bool { + let Some(m) = a.extras().mask.as_deref().filter(|m| !m.disabled && !f.opts.outline && !self.is_shape(a)) else { return false }; + // A masked object is a non-isolated group of its own, drawn over its own pixels: the + // mask is rendered over those only. + let bounds = self.bounds_of(f.symbols, a); + let Some((r, sub)) = group::area(ctx, f, bounds) else { return true }; + let Some(mask) = self.mask_values(&sub, m, r.w, r.h) else { return true }; + let blends = a.blend != vectorcraft_color::BlendMode::Normal || (!a.isolate && self.blends_through(a)); + self.group(ctx, f, Composite { mask: Some(mask), blends, bounds, ..Default::default() }, &mut |r, c, fr| { + if force { + r.draw_node(c, fr, a, true); + } else { + r.draw_arc_body(c, fr, a); + } + }); + true + } + + /// Draw an `Arc` regardless of its visibility and bounds, applying its opacity mask. + pub(crate) fn draw_forced_arc(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc<Node>) { + if !self.draw_masked_arc(ctx, f, a, true) { + self.draw_node(ctx, f, a, true); + } + } + /// The coverage of opacity mask `m` per output pixel (row-major): its art rendered offscreen, /// as luminance ([`mask_value`]). pub(super) fn mask_values(&mut self, f: &Frame, m: &vectorcraft_doc::OpacityMask, w: u16, h: u16) -> Option<Vec<u8>> { @@ -489,7 +505,7 @@ impl Renderer { if kept { self.draw_kept_node(ctx, f, art); } else { - self.draw_node(ctx, f, art, true); + self.draw_forced_arc(ctx, f, art); } self.made_again = outer; } @@ -500,7 +516,7 @@ impl Renderer { pub(crate) fn draw_kept_node(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc<Node>) { let live = vectorcraft_doc::live::is_live(a).then(|| a.clone()); let outer = std::mem::replace(&mut self.live_root, live); - self.draw_node(ctx, f, a, true); + self.draw_forced_arc(ctx, f, a); self.live_root = outer; } @@ -518,7 +534,7 @@ impl Renderer { fn draw_trace_view(&mut self, ctx: &mut RenderContext, f: &Frame, children: &[Arc<Node>], view: TraceView, knockout: bool) { let Some((source, shapes)) = children.split_first() else { return }; if view.shows_source() && matches!(source.kind, NodeKind::Image(_)) { - self.draw_node(ctx, f, source, true); + self.draw_forced_arc(ctx, f, source); } if view.shows_result() { self.draw_children(ctx, f, shapes, knockout); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 6b6ec3e794..6f15ae3135 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -662,6 +662,39 @@ fn trace_source_draws_the_source_image_of_the_listed_objects() { } } +#[test] +fn trace_source_applies_the_hidden_image_mask() { + use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind, OpacityMask}; + + let mut png = Vec::new(); + image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut d = Document::new(100.0, 100.0); + d.images.insert("trace-source".into(), ImageBlob::new("image/png", png)); + let image = ImageObject { + key: "trace-source".into(), + width: 1, + height: 1, + xf: Affine::translate((10.0, 10.0)) * Affine::scale(80.0), + link: None, + placement: Default::default(), + pixels: None, + }; + let mut source = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image))); + source.visible = false; + let mask = rect_node(&mut d, Rect::new(10.0, 10.0, 50.0, 90.0), Paint::solid(Color::WHITE), Paint::None, 0.0); + source.extras_mut().mask = Some(Box::new(OpacityMask::new(mask, true))); + let result = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0); + let mut trace = Node::group(d.alloc_id(), vec![Arc::new(source), Arc::new(result)]); + trace.extras_mut().trace = Some(Box::new(serde_json::json!({ "view": "tracingResult" }))); + let trace_id = trace.id; + d.insert(Some(d.layers[0].id), 0, trace).unwrap(); + + let opts = RenderOptions { trace_views: true, trace_source: Some(Arc::new(vec![trace_id])), background: Some([255; 4]), ..Default::default() }; + let img = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts); + assert_eq!(img.pixel(30, 50), [255, 0, 0, 255]); + assert_eq!(img.pixel(70, 50), [255, 255, 255, 255]); +} + #[test] fn artboards_white_on_pasteboard() { let d = Document::new(50.0, 50.0); @@ -747,6 +780,94 @@ fn opacity_mask_without_clip_and_inverted() { assert_eq!(img.pixel(80, 50), [255, 0, 0, 255], "inverted clip background → visible"); } +#[test] +fn opacity_mask_art_root_applies_its_own_mask() { + use vectorcraft_doc::OpacityMask; + + let mut d = Document::new(100.0, 100.0); + let mut object = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let mut art = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::WHITE), Paint::None, 0.0); + let inner = rect_node(&mut d, Rect::new(10.0, 10.0, 50.0, 90.0), Paint::solid(Color::WHITE), Paint::None, 0.0); + art.extras_mut().mask = Some(Box::new(OpacityMask::new(inner, true))); + art.visible = false; + object.extras_mut().mask = Some(Box::new(OpacityMask::new(art, true))); + let object_id = object.id; + d.insert(Some(d.layers[0].id), 0, object).unwrap(); + + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut renderer = Renderer::new(); + let img = renderer.render(&d, 100, 100, Affine::IDENTITY, &opts); + assert_eq!(img.pixel(30, 50), [255, 0, 0, 255]); + assert_eq!(img.pixel(70, 50), [255, 255, 255, 255]); + let view = renderer.render(&d, 100, 100, Affine::IDENTITY, &RenderOptions { mask_view: Some(object_id), ..opts }); + assert_eq!(view.pixel(30, 50), [255, 255, 255, 255]); + assert_eq!(view.pixel(70, 50), [0, 0, 0, 255]); +} + +#[test] +fn undecodable_image_in_mask_art_root_mask_leaves_out_outer_object() { + use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind, OpacityMask}; + + let mut d = Document::new(100.0, 100.0); + d.images.insert("broken-root-mask-image".into(), ImageBlob::new("image/png", b"not a PNG".to_vec())); + let mut object = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let mut art = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::WHITE), Paint::None, 0.0); + let image = ImageObject { + key: "broken-root-mask-image".into(), + width: 20, + height: 20, + xf: Affine::translate((30.0, 30.0)), + link: None, + placement: Default::default(), + pixels: None, + }; + art.extras_mut().mask = Some(Box::new(OpacityMask::new(Node::new(d.alloc_id(), NodeKind::Image(Box::new(image))), false))); + object.extras_mut().mask = Some(Box::new(OpacityMask::new(art, true))); + let object_id = object.id; + d.insert(Some(d.layers[0].id), 0, object).unwrap(); + + let opts = RenderOptions { background: Some([255; 4]), ..Default::default() }; + let mut renderer = Renderer::new(); + let img = renderer.render(&d, 100, 100, Affine::IDENTITY, &opts); + assert_eq!(img.pixel(70, 50), [255, 255, 255, 255]); + let view = renderer.render(&d, 100, 100, Affine::IDENTITY, &RenderOptions { mask_view: Some(object_id), ..opts }); + assert_eq!(view.pixel(70, 50), [0, 0, 0, 255]); +} + +#[test] +fn placed_symbol_art_root_applies_its_own_mask() { + use vectorcraft_doc::{NodeKind, OpacityMask}; + + for grouped in [true, false] { + let mut d = Document::new(100.0, 100.0); + let red = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let mut art = if grouped { Node::group(d.alloc_id(), vec![Arc::new(red)]) } else { red }; + let inner = rect_node(&mut d, Rect::new(10.0, 10.0, 50.0, 90.0), Paint::solid(Color::WHITE), Paint::None, 0.0); + art.extras_mut().mask = Some(Box::new(OpacityMask::new(inner, true))); + d.symbols.push(vectorcraft_doc::Symbol { name: "Masked".into(), art: Arc::new(art) }); + let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Masked".into(), xf: Affine::IDENTITY }); + d.insert(Some(d.layers[0].id), 0, instance).unwrap(); + + let img = render(&d); + assert_eq!(img.pixel(30, 50), [255, 0, 0, 255], "grouped {grouped}"); + assert_eq!(img.pixel(70, 50), [255, 255, 255, 255], "grouped {grouped}"); + } +} + +#[test] +fn node_thumbnail_applies_the_root_mask() { + use vectorcraft_doc::OpacityMask; + + let mut d = Document::new(100.0, 100.0); + let mut node = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let mask = rect_node(&mut d, Rect::new(10.0, 10.0, 50.0, 90.0), Paint::solid(Color::WHITE), Paint::None, 0.0); + node.extras_mut().mask = Some(Box::new(OpacityMask::new(mask, true))); + + let img = Renderer::new().render_node_thumbnail(&d, &node, 100, Some([255; 4])).unwrap(); + assert_eq!(img.pixel(25, 50), [255, 0, 0, 255]); + assert_eq!(img.pixel(75, 50), [255, 255, 255, 255]); +} + #[test] fn opacity_mask_with_undecodable_image_leaves_out_object() { use vectorcraft_doc::{Effect, ImageBlob, ImageObject, NodeKind, OpacityMask}; From dd83e063a4811149794ce8192267a347bad88f11 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 18:40:38 -0700 Subject: [PATCH 028/260] Render: pattern tiles draw undecoded-image marks when the view does Pattern tiles were drawn with the default render options, so an image whose pixels cannot be decoded drew nothing inside a pattern fill even when the render marks undecoded images, as the canvas does. Tiles now follow the caller's mark_undecoded_images setting, and the tile cache keys on it. An opacity mask with such a pattern now treats the mark as part of the mask, as it does for an undecodable image outside a pattern. --- crates/render/src/pattern.rs | 30 ++++++++----- crates/render/src/renderer/nodes.rs | 2 - crates/render/src/tests.rs | 68 +++++++++++++++++++++++++++-- 3 files changed, 85 insertions(+), 15 deletions(-) diff --git a/crates/render/src/pattern.rs b/crates/render/src/pattern.rs index ab1270317e..f23786b49e 100644 --- a/crates/render/src/pattern.rs +++ b/crates/render/src/pattern.rs @@ -4,7 +4,7 @@ //! ([`PatternDef::period`]) is rasterized at the device scale it is painted at, rounded up to a //! power of two and capped ([`raster_scale`]), and used as an image paint with `Extend::Repeat`, //! with the paint transform mapping pixels → pattern space → document. Tiles are cached per -//! pattern name and raster scale (and ink plane, see [`crate::ink`]) within +//! pattern name, raster scale, undecoded-image mark setting and ink plane (see [`crate::ink`]) within //! [`lru::PATTERN_BUDGET`]. A tile is used while the pattern's definition is the one it was //! rasterized from (art `Arc` identity, tile, tile type, overlap): the pattern's "revision", and, //! when its art shows more than itself (a symbol, another pattern, an image, type, a brush), while @@ -33,9 +33,9 @@ use crate::{Frame, RenderOptions, Rendered, Renderer}; /// Largest super-tile raster side (pixels). const MAX_TILE_PX: f64 = 2048.0; -/// What a tile is kept under: the pattern's name and the bits of its raster scale -/// ([`raster_scale`]). -type TileKey = (String, u64, Ink); +/// What a tile is kept under: the pattern's name, the bits of its raster scale +/// ([`raster_scale`]), ink plane and undecoded-image mark setting. +type TileKey = (String, u64, Ink, bool); /// What a tile was drawn from besides its pattern's own art, for art that shows more than itself: /// the art of every pattern and symbol and the pixels of every image in the document, the @@ -169,12 +169,20 @@ pub(crate) fn raster_scale(s: f64, period: (f64, f64)) -> f64 { /// Rasterize `region` (pattern space) of the infinite tiling into a `w`×`h` pixmap, colours as /// `ink` paints them. -fn rasterize(r: &mut Renderer, doc: &Document, def: &PatternDef, region: Rect, w: u16, h: u16, ink: Ink) -> (Pixmap, bool) { - let (w, h) = (w.max(1), h.max(1)); +fn rasterize( + r: &mut Renderer, + doc: &Document, + def: &PatternDef, + region: Rect, + size: (u16, u16), + ink: Ink, + mark_undecoded_images: bool, +) -> (Pixmap, bool) { + let (w, h) = (size.0.max(1), size.1.max(1)); let mut ctx = crate::single_threaded_context(w, h); let view = Affine::scale_non_uniform(w as f64 / region.width().max(1e-9), h as f64 / region.height().max(1e-9)) * Affine::translate(-region.origin().to_vec2()); - let opts = RenderOptions::default(); + let opts = RenderOptions { mark_undecoded_images, ..Default::default() }; r.image_left_out = Some(false); let pattern_images_left_out = images_left_out(); r.check_plugins(); @@ -254,7 +262,7 @@ pub(crate) fn set_pattern_paint(ctx: &mut RenderContext, name: &str, xf: Affine, let (pw, ph) = def.period(); let scale = raster_scale(s, (pw, ph)); let params = (def.tile, def.tile_type, def.overlap); - let key = (name.to_string(), scale.to_bits(), ink); + let key = (name.to_string(), scale.to_bits(), ink, f.opts.mark_undecoded_images); let cms = vectorcraft_color::cms::active(); let hit = CACHE.with(|c| { let mut c = c.borrow_mut(); @@ -283,7 +291,9 @@ pub(crate) fn set_pattern_paint(ctx: &mut RenderContext, name: &str, xf: Affine, let w = (pw * scale).ceil().clamp(1.0, 4096.0) as u16; let h = (ph * scale).ceil().clamp(1.0, 4096.0) as u16; let before = crate::paint::decode_failures(); - let Some((pm, image_left_out)) = with_tile_renderer(|r| rasterize(r, doc, def, Rect::new(0.0, 0.0, pw, ph), w, h, ink)) else { + let Some((pm, image_left_out)) = + with_tile_renderer(|r| rasterize(r, doc, def, Rect::new(0.0, 0.0, pw, ph), (w, h), ink, f.opts.mark_undecoded_images)) + else { ctx.set_paint(missing()); return true; }; @@ -322,7 +332,7 @@ pub fn render_pattern_swatch(doc: &Document, name: &str, size: u32) -> Option<Re let side = w.max(h); let region = Rect::from_center_size((w / 2.0, h / 2.0), (side, side)); let px = size.clamp(1, 1024) as u16; - let (pm, _) = with_tile_renderer(|r| rasterize(r, doc, def, region, px, px, Ink::Display))?; + let (pm, _) = with_tile_renderer(|r| rasterize(r, doc, def, region, (px, px), Ink::Display, false))?; Some(Rendered { width: px as u32, height: px as u32, pixels: pm.data_as_u8_slice().to_vec() }) } diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index 6586be0b3b..97cd1e64eb 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -207,8 +207,6 @@ impl Renderer { let failures = crate::paint::decode_failures(); let pattern_images_left_out = crate::pattern::images_left_out(); self.draw_kept_node(&mut mctx, &Frame { mt: false, ink: Ink::Display, ..*f }, &m.art); - // Pattern tiles are drawn without undecoded-image marks, so an image a tile left out counts - // with the marks on too. let incomplete = self.image_left_out.unwrap_or(false) || crate::pattern::images_left_out() > pattern_images_left_out || (!f.opts.mark_undecoded_images && crate::paint::decode_failures() > failures); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 6f15ae3135..767f1eda8a 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -944,9 +944,33 @@ fn opacity_mask_with_missing_image_in_pattern_leaves_out_object() { let img = r.render(&d, 100, 100, Affine::IDENTITY, &opts); assert_eq!(img.pixel(70, 50), [255, 255, 255, 255], "frame {frame}: incomplete pattern mask leaves out the object"); } - // Pattern tiles draw no undecoded-image mark, so the object stays out with the marks on too. - let marked = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &RenderOptions { mark_undecoded_images: true, ..opts.clone() }); - assert_eq!(marked.pixel(70, 50), [255, 255, 255, 255], "a tile without the mark leaves out the object"); +} + +#[test] +fn opacity_mask_with_marked_image_in_pattern_draws_object() { + use vectorcraft_doc::pattern::{PatternDef, pattern_paint}; + use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind, OpacityMask}; + + let mut d = Document::new(100.0, 100.0); + d.images.insert("cut-mask".into(), ImageBlob::new("image/png", b"not a PNG: pattern mask".to_vec())); + let image = + ImageObject { key: "cut-mask".into(), width: 20, height: 20, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image))); + let mut pattern = PatternDef::new("Cut mask", vec![Arc::new(image)]); + pattern.tile = Rect::new(0.0, 0.0, 20.0, 20.0); + d.patterns.push(pattern); + let art = rect_node(&mut d, Rect::new(10.0, 10.0, 50.0, 90.0), pattern_paint("Cut mask"), Paint::None, 0.0); + let mut object = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + object.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false))); + d.insert(Some(d.layers[0].id), 0, object).unwrap(); + + let mut r = Renderer::new(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let off = r.render(&d, 100, 100, Affine::IDENTITY, &opts); + assert_eq!(off.pixel(70, 50), [255, 255, 255, 255], "an unmarked missing image leaves out the object"); + let on = r.render(&d, 100, 100, Affine::IDENTITY, &RenderOptions { mark_undecoded_images: true, ..opts }); + assert_eq!(on.pixel(70, 50), [255, 0, 0, 255], "the marked image keeps the mask complete"); + assert!(on.pixel(15, 15)[1] < 255, "the marked pattern contributes mask coverage"); } #[test] @@ -1488,6 +1512,44 @@ fn an_undecodable_image_is_tried_once_and_marked_on_screen() { assert_eq!((attempts() - tried, decode_failures() - failed), (1, 3), "and counts it without decoding it again"); } +#[test] +fn pattern_tile_follows_undecoded_image_mark_in_both_cache_orders() { + use vectorcraft_doc::pattern::{PatternDef, pattern_paint}; + use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind}; + + let mut d = Document::new(80.0, 80.0); + d.images.insert("cut-pattern".into(), ImageBlob::new("image/png", b"not a PNG: pattern fill".to_vec())); + let image = ImageObject { + key: "cut-pattern".into(), + width: 20, + height: 20, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image))); + let mut pattern = PatternDef::new("Cut pattern", vec![Arc::new(image)]); + pattern.tile = Rect::new(0.0, 0.0, 20.0, 20.0); + d.patterns.push(pattern); + let shape = rect_node(&mut d, Rect::new(10.0, 10.0, 70.0, 70.0), pattern_paint("Cut pattern"), Paint::None, 0.0); + d.insert(Some(d.layers[0].id), 0, shape).unwrap(); + + let mut r = Renderer::new(); + for order in [[false, true, false], [true, false, true]] { + for mark in order { + let opts = RenderOptions { mark_undecoded_images: mark, ..Default::default() }; + let pixel = r.render(&d, 80, 80, Affine::IDENTITY, &opts).pixel(15, 15); + assert_eq!(pixel[3] > 0, mark, "mark_undecoded_images {mark}: {pixel:?}"); + if mark { + assert_eq!(pixel[0], pixel[1], "the pattern draws a gray mark"); + assert_eq!(pixel[1], pixel[2], "the pattern draws a gray mark"); + assert!((120..=140).contains(&pixel[0]), "the pattern draws a gray mark: {pixel:?}"); + } + } + } +} + /// The rasters a renderer keeps of an object's raster effects are made again when /// `mark_undecoded_images` changes: a blurred image whose pixels can't be decoded shows its blurred /// mark only while the option is on. From 875d3301f55d48e887d0274f1494e2a304ac0a6b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 00:42:46 -0700 Subject: [PATCH 029/260] Transparency: Make Opacity Mask over several layers masks their art transparency.makeOpacityMask with two or more layers below the mask object (or a layer and objects of other layers) wrapped the layers themselves in a new top-level group, so a layer ended up inside a group. A layer among several masked items now stands for its art: the masked group takes the layer's visible, unlocked objects, a hidden, locked or template layer gives none, and the layers stay where they are. One layer under a mask object, or one layer alone, is masked as before. --- crates/engine/src/cmd/opacitymask.rs | 59 +++++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/opacitymask.rs b/crates/engine/src/cmd/opacitymask.rs index d5a7f600dd..8d65308600 100644 --- a/crates/engine/src/cmd/opacitymask.rs +++ b/crates/engine/src/cmd/opacitymask.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> { "Make Opacity Mask", ["Window", "Transparency"], None, - "{ids?, clip?, invert?} the topmost of the selected objects (or of `ids`) becomes the mask of the others (grouped if several). One object gets an empty mask and enters mask editing: draw the mask, then transparency.stopEditingOpacityMask; one target (an object or a layer) is refused in isolation mode and in pattern editing mode → {id, editing}", + "{ids?, clip?, invert?} the topmost of the selected objects (or of `ids`) becomes the mask of the others (grouped if several, a layer among several by its art). One object gets an empty mask and enters mask editing: draw the mask, then transparency.stopEditingOpacityMask; one target (an object or a layer) is refused in isolation mode and in pattern editing mode → {id, editing}", can_make, make ), @@ -206,6 +206,24 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> { let invert = bool_or(p, "invert", s.menu.new_masks_inverted); // Several objects: the top one is the mask. One: an empty mask, drawn in mask editing. let (art, mask_id) = if below.is_empty() { (&ids[..], None) } else { (below, Some(top)) }; + // Several objects go into a new group, and a layer can't: a layer among them stands for its + // visible, unlocked art, which the group takes from it. A hidden, locked or template layer + // gives none. + let contents; + let art = if art.len() > 1 && art.iter().any(|id| d.node(*id).is_some_and(Node::is_layer)) { + let objects = art.iter().flat_map(|id| match d.node(*id) { + Some(n) if n.is_layer() && (!n.visible || n.locked || n.is_template()) => vec![], + Some(n) if n.is_layer() => n.layer_art(true), + _ => vec![*id], + }); + contents = super::edit::outermost(d, d.paint_order(objects)); + if contents.is_empty() { + return Err(bad(C, "the layers hold no art to mask")); + } + &contents[..] + } else { + art + }; let (id, layer) = s.edit("Make Opacity Mask", |d, sel| { let mask_art = match mask_id { Some(m) => (*d.remove(m)?).clone(), @@ -492,6 +510,45 @@ mod tests { assert!(!n.extras().mask.as_ref().unwrap().clip); } + #[test] + fn make_masks_the_art_of_layers_under_a_mask_object() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let rect = |s: &mut Session, x: u64| { + s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let l1 = s.doc().unwrap().doc.layers[0].id.0; + let (a, a2) = (rect(&mut s, 0), rect(&mut s, 30)); + let l2 = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap(); + let (b, b2) = (rect(&mut s, 60), rect(&mut s, 90)); + s.execute("layer.new", &json!({})).unwrap(); + let top = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 150, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let layer_ids = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.id.0).collect::<Vec<_>>(); + let before = s.doc().unwrap().doc.layers.clone(); + // Two layers, and a layer with an object of another layer: the masked group takes the + // layers' art, and the layers stay where they are. + for (ids, grouped, left) in [(vec![l1, l2, top], vec![a, a2, b, b2], vec![]), (vec![l1, b, top], vec![a, a2, b], vec![b2])] { + let g = s.execute("transparency.makeOpacityMask", &json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(layer_ids(&s), before.iter().map(|l| l.id.0).collect::<Vec<_>>(), "{ids:?}: no layer moved"); + let n = d.node(NodeId(g)).unwrap(); + assert!(!n.is_layer() && n.extras().mask.is_some(), "{ids:?}"); + assert!(d.parent_of(NodeId(g)).and_then(|p| d.node(p)).is_some_and(Node::is_layer), "{ids:?}: the group is in a layer"); + assert_eq!(n.children().unwrap().iter().map(|c| c.id.0).collect::<Vec<_>>(), grouped, "{ids:?}"); + for id in left { + assert_eq!(d.parent_of(NodeId(id)), Some(NodeId(l2)), "{ids:?}: {id} stays in its layer"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, before, "{ids:?}: undo"); + } + // A hidden layer gives none of its art. + s.execute("layer.setProps", &json!({"id": l2, "visible": false})).unwrap(); + let g = s.execute("transparency.makeOpacityMask", &json!({ "ids": [l1, l2, top] })).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.node(NodeId(g)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect::<Vec<_>>(), vec![a, a2]); + assert_eq!((d.parent_of(NodeId(b)), d.parent_of(NodeId(b2))), (Some(NodeId(l2)), Some(NodeId(l2)))); + } + #[test] fn release_restores_mask_art_and_undo_restores_mask() { let (mut s, a, b) = session_with_two(); From 1f31b6ed4a7b4c2ce409bdae59a5cac137e2c891 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 18:46:05 +0700 Subject: [PATCH 030/260] Find Font: Change and Change All leave hidden and locked text alone Squashed from #4852 onto main. --- crates/engine/src/cmd/fonts.rs | 85 ++++++++++++++++++++++++++++- crates/ui-egui/src/find_font.rs | 16 ++++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + 28 files changed, 124 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 6b134afb60..827875b206 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -29,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> { "Replace Font", [], None, - "{from: {family, style?}, to: {family (any of its names; stored as the font's own family name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style) → {runs}", + "{from: {family, style?}, to: {family (any of its names; stored as the font's own family name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); text that is hidden or locked, in a hidden or locked group or layer, or on a locked artboard keeps its font → {runs, skipped?: the text objects left in the font, warning?}", has_doc, replace ), @@ -414,10 +414,18 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> { Some((f, m)) if m != vectorcraft_text::FontMatch::Missing => f.family.clone(), _ => return Err(bad(C, format!("font family `{tf}` is not available"))), }; - let ids = scope(s, bool_or(p, "selectionOnly", false))?; let matches = |st: &vectorcraft_doc::CharStyle| { st.font_family.eq_ignore_ascii_case(&ff) && fs.as_ref().is_none_or(|x| st.font_style.eq_ignore_ascii_case(x)) }; + // Only text the Selection tool can reach changes: not hidden or locked, in a hidden or locked + // group or layer, or on a locked artboard. The text left in the font is counted. + let (ids, skipped) = { + let d = &s.doc()?.doc; + let editable = d.editable(); + let (ids, other): (Vec<NodeId>, Vec<NodeId>) = scope(s, bool_or(p, "selectionOnly", false))?.into_iter().partition(|id| editable(*id)); + let skipped = other.into_iter().filter(|id| text(d, *id).is_some_and(|t| t.runs.iter().any(|r| matches(&r.style)))).count(); + (ids, skipped) + }; let n = s.edit("Replace Font", |d, _| { let mut n = 0; for id in &ids { @@ -446,9 +454,17 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> { } Ok(n) })?; - Ok(json!({ "runs": n })) + let mut out = json!({ "runs": n }); + if skipped > 0 { + out["skipped"] = json!(skipped); + out["warning"] = json!(REPLACE_SKIPPED); + } + Ok(out) } +/// What Replace Font says when it left text in the font that it can't reach. +const REPLACE_SKIPPED: &str = "some text is hidden or locked, so its font wasn't replaced"; + fn select_font(s: &mut Session, p: &Value) -> Result<Value> { let family = str_param(p, "family").ok_or_else(|| bad("select.font", "missing `family`"))?.to_string(); let style = str_param(p, "style").map(str::to_string); @@ -621,6 +637,69 @@ mod tests { assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 0); assert!(s.doc().unwrap().selection.objects.is_empty()); } + + /// Replace Font leaves hidden and locked text in its font, and text inside a hidden or locked + /// group or layer, and says so. Text on a visible, unlocked template layer is changed. + #[test] + fn replace_font_skips_hidden_and_locked_text() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let text = |s: &mut Session, y: i32| { + s.execute("text.create", &json!({"x": 10, "y": y, "text": "Serif", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap() + }; + let mut ids = vec![]; + for y in [20, 40, 60, 80, 100] { + ids.push(text(&mut s, y)); + } + for (id, group, cmd) in + [(ids[1], false, "object.hide"), (ids[2], false, "object.lock"), (ids[3], true, "object.hide"), (ids[4], true, "object.lock")] + { + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + if group { + s.execute("object.group", &json!({})).unwrap(); + } + s.execute(cmd, &json!({})).unwrap(); + } + let mut layer_text = |props: &[Value]| { + let layer = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap(); + let id = text(&mut s, 140); + for p in props { + let mut p = p.clone(); + p["id"] = json!(layer); + s.execute("layer.setProps", &p).unwrap(); + } + id + }; + ids.push(layer_text(&[json!({"visible": false})])); + ids.push(layer_text(&[json!({"locked": true})])); + // Template on locks the layer; unlocking it makes its text editable again. + let template = layer_text(&[json!({"template": true}), json!({"locked": false})]); + let family = |s: &Session, id: u64| text_family(s, id); + let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(r["runs"], 2, "{r}"); + assert_eq!(r["skipped"], 6, "{r}"); + assert_eq!(r["warning"], REPLACE_SKIPPED, "{r}"); + assert_eq!(family(&s, ids[0]), "Source Sans 3"); + assert_eq!(family(&s, template), "Source Sans 3"); + for id in &ids[1..] { + assert_eq!(family(&s, *id), "Source Serif 4", "object {id}"); + } + // The font stays in the document's list while the skipped text uses it. + let fams: Vec<String> = + s.execute("text.fonts", &json!({})).unwrap().as_array().unwrap().iter().map(|f| f["family"].as_str().unwrap().to_string()).collect(); + assert_eq!(fams, ["Source Sans 3", "Source Serif 4"]); + // Only skipped text left: nothing changes, and the warning says why. + let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!((r["runs"].clone(), r["skipped"].clone(), r["warning"].clone()), (json!(0), json!(6), json!(REPLACE_SKIPPED)), "{r}"); + // A plain replacement carries no warning. + let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}})).unwrap(); + assert_eq!(r, json!({"runs": 2})); + } + + /// The font family of text object `id`'s first run. + fn text_family(s: &Session, id: u64) -> String { + text(&s.doc().unwrap().doc, NodeId(id)).unwrap().runs[0].style.font_family.clone() + } } #[cfg(test)] diff --git a/crates/ui-egui/src/find_font.rs b/crates/ui-egui/src/find_font.rs index 23340af8c5..5155542e01 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -182,6 +182,22 @@ mod tests { assert_eq!(fonts(&mut app)[0]["family"], "Source Sans 3"); } + /// Change All leaves locked text in its font, and the status bar says so. + #[test] + fn change_all_says_when_locked_text_keeps_its_font() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + open(&mut app); + let d = app.ui.dialog.clone().unwrap(); + let from = fonts(&mut app)[0].clone(); + let r = change(&mut app, &d, &from, true).unwrap(); + assert_eq!(r["runs"], 0, "{r}"); + assert_eq!(fonts(&mut app)[0]["family"], "Missing Family"); + assert_eq!(app.ui.status, "some text is hidden or locked, so its font wasn't replaced"); + } + #[test] fn find_in_folder_puts_the_missing_fonts_dialog_in_find_fonts_place() { let dir = std::fs::canonicalize(vectorcraft_testkit::temp_dir("find-font-folder")).unwrap(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2ddd7fd2b6..84ef4701b0 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4091,6 +4091,7 @@ axis Both И двете @msg no such perspective grid preset няма такава предварителна настройка за перспективна мрежа @msg no such recent file няма такъв скорошен файл @msg no such recent font няма такъв скорошен шрифт +@msg some text is hidden or locked, so its font wasn't replaced част от текста е скрит или заключен, затова шрифтът му не беше заменен @msg no such saved selection няма такава запазена селекция @msg no such segment няма такъв сегмент @msg no such spine point няма такава точка от оста diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 1c0416e677..bf9005f9a0 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4480,6 +4480,7 @@ imageTrace Outline Obris @msg no such perspective grid preset nema takvog predloška mreže perspektive @msg no such recent file nema takve nedavne datoteke @msg no such recent font nema takvog nedavnog fonta +@msg some text is hidden or locked, so its font wasn't replaced dio teksta je skriven ili zaključan, pa njegov font nije zamijenjen @msg no such saved selection nema takvog sačuvanog odabira @msg no such segment nema takvog segmenta @msg no such spine point nema takve tačke kičme diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 34722c0b16..42e560cc97 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5170,6 +5170,7 @@ @msg no such perspective grid preset no existeix aquest preajust de quadrícula de perspectiva @msg no such recent file no existeix aquest fitxer recent @msg no such recent font no existeix aquest tipus de lletra recent +@msg some text is hidden or locked, so its font wasn't replaced part del text està amagat o bloquejat, així que el seu tipus de lletra no s'ha substituït @msg no such saved selection no existeix aquesta selecció desada @msg no such segment no existeix aquest segment @msg no such spine point no existeix aquest punt de l’espina diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b5fbc21540..ee3a5acb1b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4517,6 +4517,7 @@ imageTrace Outline Obrys @msg no such perspective grid preset takové přednastavení perspektivní mřížky neexistuje @msg no such recent file takový nedávný soubor neexistuje @msg no such recent font takové nedávné písmo neexistuje +@msg some text is hidden or locked, so its font wasn't replaced některý text je skrytý nebo zamčený, a proto jeho písmo nebylo nahrazeno @msg no such saved selection takový uložený výběr neexistuje @msg no such segment takový segment neexistuje @msg no such spine point takový bod páteře neexistuje diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4642b364bc..2372e6020f 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4199,6 +4199,7 @@ imageTrace Outline Kontur @msg no such perspective grid preset ingen sådan perspektivgitterforudindstilling @msg no such recent file ingen sådan seneste fil @msg no such recent font ingen sådan seneste skrifttype +@msg some text is hidden or locked, so its font wasn't replaced noget tekst er skjult eller låst, så dens skrifttype blev ikke erstattet @msg no such saved selection ingen sådan gemt markering @msg no such segment intet sådant segment @msg no such subpath ingen sådan delsti diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 320960d0ef..44c46ab54b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4131,6 +4131,7 @@ theme Appearance Erscheinungsbild @msg no such perspective grid preset keine solche Vorgabe für Perspektivenraster @msg no such recent file keine solche zuletzt geöffnete Datei @msg no such recent font keine solche zuletzt verwendete Schrift +@msg some text is hidden or locked, so its font wasn't replaced einige Texte sind ausgeblendet oder gesperrt, daher wurde ihre Schrift nicht ersetzt @msg no such saved selection keine solche gespeicherte Auswahl @msg no such segment kein solches Segment @msg no such spine point kein solcher Achsenpunkt diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7dfc4f3e67..a7e06cec80 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4170,6 +4170,7 @@ theme Appearance Εμφάνιση @msg no such perspective grid preset δεν υπάρχει τέτοια προεπιλογή πλέγματος προοπτικής @msg no such recent file δεν υπάρχει τέτοιο πρόσφατο αρχείο @msg no such recent font δεν υπάρχει τέτοια πρόσφατη γραμματοσειρά +@msg some text is hidden or locked, so its font wasn't replaced κάποιο κείμενο είναι κρυφό ή κλειδωμένο, οπότε η γραμματοσειρά του δεν αντικαταστάθηκε @msg no such saved selection δεν υπάρχει τέτοια αποθηκευμένη επιλογή @msg no such segment δεν υπάρχει τέτοιο τμήμα @msg no such spine point δεν υπάρχει τέτοιο σημείο κεντρικής καμπύλης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 454557e044..c34f741d4e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4210,6 +4210,7 @@ axis Both Ambos @msg no such perspective grid preset no existe ese preajuste de cuadrícula de perspectiva @msg no such recent file no existe ese archivo reciente @msg no such recent font no existe esa fuente reciente +@msg some text is hidden or locked, so its font wasn't replaced parte del texto está oculto o bloqueado, así que su fuente no se ha reemplazado @msg no such saved selection no existe esa selección guardada @msg no such segment no existe ese segmento @msg no such spine point no existe ese punto del eje diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index ede17d2aca..2614a0929f 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4426,6 +4426,7 @@ imageTrace Outline Ääriviiva @msg no such perspective grid preset perspektiiviruudukon esiasetusta ei ole @msg no such recent file viimeisintä tiedostoa ei ole @msg no such recent font viimeisintä fonttia ei ole +@msg some text is hidden or locked, so its font wasn't replaced osa tekstistä on piilotettu tai lukittu, joten sen fonttia ei korvattu @msg no such saved selection tallennettua valintaa ei ole @msg no such segment segmenttiä ei ole @msg no such spine point selkärangan pistettä ei ole diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index fae329cc5b..b837907d65 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4207,6 +4207,7 @@ axis Both Les deux @msg no such perspective grid preset paramètre prédéfini de grille de perspective inexistant @msg no such recent file fichier récent inexistant @msg no such recent font police récente inexistante +@msg some text is hidden or locked, so its font wasn't replaced une partie du texte est masquée ou verrouillée : sa police n'a pas été remplacée @msg no such saved selection sélection enregistrée inexistante @msg no such segment segment inexistant @msg no such spine point point de la dorsale inexistant diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index eb4e09e41a..03dab8279d 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4874,6 +4874,7 @@ imageTrace Outline Körvonal @msg no such perspective grid preset nincs ilyen perspektivikusrács-előbeállítás @msg no such recent file nincs ilyen legutóbbi fájl @msg no such recent font nincs ilyen legutóbbi betűtípus +@msg some text is hidden or locked, so its font wasn't replaced néhány szöveg rejtett vagy zárolt, ezért a betűtípusa nem lett lecserélve @msg no such saved selection nincs ilyen mentett kijelölés @msg no such segment nincs ilyen szakasz @msg no such spine point nincs ilyen gerincpont diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e43dc998ae..52c29b570c 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4199,6 +4199,7 @@ imageTrace Outline Kontur @msg no such perspective grid preset tidak ada preset kisi perspektif seperti itu @msg no such recent file tidak ada berkas terbaru seperti itu @msg no such recent font tidak ada font terbaru seperti itu +@msg some text is hidden or locked, so its font wasn't replaced sebagian teks tersembunyi atau terkunci, sehingga fontnya tidak diganti @msg no such saved selection tidak ada seleksi tersimpan seperti itu @msg no such segment tidak ada segmen seperti itu @msg no such subpath tidak ada subjalur seperti itu diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index eefe97ac7f..a681efadf6 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4250,6 +4250,7 @@ axis Both Entrambi @msg no such perspective grid preset preset di griglia prospettica inesistente @msg no such recent file file recente inesistente @msg no such recent font font recente inesistente +@msg some text is hidden or locked, so its font wasn't replaced parte del testo è nascosta o bloccata, quindi il suo font non è stato sostituito @msg no such saved selection selezione salvata inesistente @msg no such segment segmento inesistente @msg no such spine point punto della dorsale inesistente diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 51b72cd238..8c31a2eb7f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4544,6 +4544,7 @@ swatch Bright Violet ビビッドバイオレット @msg no such perspective grid preset 指定された遠近グリッドプリセットが見つかりません @msg no such recent file 指定された最近使ったファイルが見つかりません @msg no such recent font 指定された最近使ったフォントが見つかりません +@msg some text is hidden or locked, so its font wasn't replaced 一部のテキストが非表示またはロックされているため、そのフォントは置換されませんでした @msg no such saved selection 指定された選択範囲は保存されていません @msg no such user library 指定されたユーザーライブラリが見つかりません @msg no such view 指定された表示が見つかりません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 7ae614f12b..33eae7aece 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3986,6 +3986,7 @@ font-technology Variable ცვლადი @msg no such perspective grid preset პერსპექტივის ბადის ასეთი პრესეტი არ არის @msg no such recent file ასეთი ბოლოს გახსნილი ფაილი არ არის @msg no such recent font ასეთი ბოლოდროინდელი შრიფტი არ არის +@msg some text is hidden or locked, so its font wasn't replaced ზოგიერთი ტექსტი დამალული ან ჩაკეტილია, ამიტომ მისი შრიფტი არ შეიცვალა @msg no such saved selection ასეთი შენახული მონიშვნა არ არის @msg no such segment ასეთი სეგმენტი არ არის @msg no such subpath ასეთი ქვეტრაექტორია არ არის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 23e55a28fd..cf3254be22 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4472,6 +4472,7 @@ theme Appearance 외관 @msg no such perspective grid preset 해당 원근 격자 프리셋이 없습니다 @msg no such recent file 해당 최근 파일이 없습니다 @msg no such recent font 해당 최근 글꼴이 없습니다 +@msg some text is hidden or locked, so its font wasn't replaced 일부 텍스트가 숨겨져 있거나 잠겨 있어 해당 글꼴을 바꾸지 않았습니다 @msg no such saved selection 해당 저장된 선택 영역이 없습니다 @msg no such user library 해당 사용자 라이브러리가 없습니다 @msg no such view 해당 보기가 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c269832419..2801614915 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4211,6 +4211,7 @@ imageTrace Outline Contour @msg no such perspective grid preset perspectiefrastervoorinstelling bestaat niet @msg no such recent file recent bestand bestaat niet @msg no such recent font recent lettertype bestaat niet +@msg some text is hidden or locked, so its font wasn't replaced een deel van de tekst is verborgen of vergrendeld, dus het lettertype ervan is niet vervangen @msg no such saved selection opgeslagen selectie bestaat niet @msg no such segment segment bestaat niet @msg no such subpath subpad bestaat niet diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 65cb40b345..880adf64a3 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4341,6 +4341,7 @@ imageTrace Outline Kontur @msg no such perspective grid preset brak takiego ustawienia siatki perspektywy @msg no such recent file brak takiego ostatniego pliku @msg no such recent font brak takiej ostatniej czcionki +@msg some text is hidden or locked, so its font wasn't replaced część tekstu jest ukryta lub zablokowana, więc jego czcionka nie została zastąpiona @msg no such saved selection brak takiego zapisanego zaznaczenia @msg no such segment brak takiego segmentu @msg no such spine point brak takiego punktu grzbietu diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8fd2b3ba5e..a4aea80cf8 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3787,6 +3787,7 @@ axis Both Ambos @msg no such perspective grid preset predefinição de grade de perspectiva inexistente @msg no such recent file arquivo recente inexistente @msg no such recent font fonte recente inexistente +@msg some text is hidden or locked, so its font wasn't replaced parte do texto está oculta ou bloqueada, então sua fonte não foi substituída @msg no such saved selection seleção salva inexistente @msg no such segment segmento inexistente @msg no such spine point ponto da coluna inexistente diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index b605f92778..7ebfa3c2b3 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4246,6 +4246,7 @@ axis Both Оба @msg no such perspective grid preset такого набора сетки перспективы нет @msg no such recent file такого последнего файла нет @msg no such recent font такого последнего шрифта нет +@msg some text is hidden or locked, so its font wasn't replaced часть текста скрыта или заблокирована, поэтому её шрифт не заменён @msg no such saved selection такого сохранённого выделения нет @msg no such segment такого сегмента нет @msg no such spine point такой точки остова нет diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index df96962c15..390cc84234 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4121,6 +4121,7 @@ axis Both Båda @msg no such perspective grid preset förinställningen för perspektivrutnät finns inte @msg no such recent file den senaste filen finns inte @msg no such recent font det senaste typsnittet finns inte +@msg some text is hidden or locked, so its font wasn't replaced en del text är dold eller låst, så dess typsnitt ersattes inte @msg no such saved selection den sparade markeringen finns inte @msg no such segment segmentet finns inte @msg no such spine point ryggradspunkten finns inte diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d099149f07..b16002086b 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3983,6 +3983,7 @@ axis Both Her İkisi @msg no such perspective grid preset böyle bir perspektif ızgarası ön ayarı yok @msg no such recent file böyle yeni bir dosya yok @msg no such recent font böyle yeni bir yazı tipi yok +@msg some text is hidden or locked, so its font wasn't replaced bazı metinler gizli veya kilitli olduğundan yazı tipleri değiştirilmedi @msg no such saved selection böyle kayıtlı bir seçim yok @msg no such segment öyle bir bölüm yok @msg no such subpath böyle bir alt yol yok diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 9454d2f364..d3c0cda4fc 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4234,6 +4234,7 @@ axis Both Обидві @msg no such perspective grid preset такого набору сітки перспективи немає @msg no such recent file такого останнього файлу немає @msg no such recent font такого останнього шрифту немає +@msg some text is hidden or locked, so its font wasn't replaced частина тексту прихована або заблокована, тому її шрифт не замінено @msg no such saved selection такого збереженого виділення немає @msg no such segment такого сегменту немає @msg no such spine point такої точки осі немає diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f0c495d4f9..63c0825dfb 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4523,6 +4523,7 @@ theme Appearance Giao diện @msg no such perspective grid preset không có thiết lập sẵn lưới phối cảnh như vậy @msg no such recent file không có tệp gần đây như vậy @msg no such recent font không có phông chữ gần đây như vậy +@msg some text is hidden or locked, so its font wasn't replaced một số văn bản bị ẩn hoặc bị khóa nên phông chữ của chúng không được thay thế @msg no such saved selection không có vùng chọn đã lưu như vậy @msg no such segment không có đoạn như vậy @msg no such spine point không có điểm trục như vậy diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 61defa0208..5fe6e81923 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4261,6 +4261,7 @@ imageTrace Outline 轮廓 @msg no such perspective grid preset 没有此透视网格预设 @msg no such recent file 没有此最近使用的文件 @msg no such recent font 没有此最近使用的字体 +@msg some text is hidden or locked, so its font wasn't replaced 部分文字已隐藏或锁定,因此其字体未被替换 @msg no such saved selection 没有此已保存的选区 @msg no such user library 没有此用户库 @msg no such view 没有此视图 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 423e780b0d..e352fe56be 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2201,6 +2201,7 @@ file-filter Templates 範本 @msg no such perspective grid preset 沒有這個透視格點預設集 @msg no such recent file 沒有這個最近使用的檔案 @msg no such recent font 沒有這個最近使用的字體 +@msg some text is hidden or locked, so its font wasn't replaced 部分文字已隱藏或鎖定,因此其字體未被取代 @msg no such saved selection 沒有這個已儲存的選取範圍 @msg no such user library 沒有這個使用者資料庫 @msg no such view 沒有這個檢視 From 65b6606d90e4e3e2250cc0877f20e93def849ffa Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 18:46:57 +0700 Subject: [PATCH 031/260] Part of #3229: setting type in a font or style that isn't available warns Squashed from #4866 onto main. --- crates/engine/src/cmd/create.rs | 14 +++++- crates/engine/src/cmd/fonts.rs | 78 +++++++++++++++++++++++++++++-- crates/engine/src/cmd/textedit.rs | 16 ++++++- crates/engine/src/cmd/typecmd.rs | 21 ++++++++- 4 files changed, 118 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index a943ee10dd..f414182470 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> { "Create Text", [], None, - "{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color?, keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color?, keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", has_doc, text_create ), @@ -739,7 +739,17 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> { let made = insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation))?; let id = made.get("id").and_then(Value::as_u64).map(NodeId); let made = super::typecmd::with_bounds(s, id, made); - Ok(super::typecmd::with_overflow(s, id.as_slice(), made)) + let mut made = super::typecmd::with_overflow(s, id.as_slice(), made); + if p.get("font").is_some() || p.get("style").is_some() { + let runs = match id.and_then(|i| s.doc().ok()?.doc.node(i)).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => t.runs.iter().map(|r| super::fonts::font_of(&r.style)).collect(), + _ => Default::default(), + }; + if let Some(w) = super::fonts::set_font_warning(runs) { + made["warning"] = json!(w); + } + } + Ok(made) } /// The paragraph attributes new type gets (the Type tools, `text.create`): aligned to the start of diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 827875b206..cf3404c313 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -29,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> { "Replace Font", [], None, - "{from: {family, style?}, to: {family (any of its names; stored as the font's own family name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); text that is hidden or locked, in a hidden or locked group or layer, or on a locked artboard keeps its font → {runs, skipped?: the text objects left in the font, warning?}", + "{from: {family, style?}, to: {family (any of its names; stored as the font's own family name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); text that is hidden or locked, in a hidden or locked group or layer, or on a locked artboard keeps its font → {runs, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}", has_doc, replace ), @@ -318,6 +318,24 @@ pub(super) fn substitution_warning(d: &Document) -> Option<String> { /// [`substitution_warning`] for type set in `fonts`. pub(super) fn substitution_warning_of(fonts: BTreeSet<UsedFont>) -> Option<String> { + substitutions(fonts, ("were written", "was drawn")) +} + +/// The font (family, style, version) of character style `st`. +pub(super) fn font_of(st: &vectorcraft_doc::CharStyle) -> UsedFont { + (st.font_family.clone(), st.font_style.clone(), st.font_version.clone()) +} + +/// What `text.create`, `text.setStyle`, `text.setRangeStyle` and `text.replaceFont` say when the +/// fonts they set type in (`fonts`) don't draw it: the family isn't available (the fallback font +/// is drawn) or doesn't have that style (its closest style is drawn). `None` when all draw it. +pub(super) fn set_font_warning(fonts: BTreeSet<UsedFont>) -> Option<String> { + substitutions(fonts, ("are drawn", "is drawn")) +} + +/// The warning for type set in `fonts`, with the verbs `written` and `drawn` (an export's are +/// `were written` and `was drawn`). +fn substitutions(fonts: BTreeSet<UsedFont>, (written, drawn): (&str, &str)) -> Option<String> { let db = vectorcraft_text::FontDb::global(); let mut missing: Vec<String> = Vec::new(); let mut styles: BTreeSet<String> = BTreeSet::new(); @@ -325,7 +343,7 @@ pub(super) fn substitution_warning_of(fonts: BTreeSet<UsedFont>) -> Option<Strin match db.resolve(&family, &style) { None | Some((_, vectorcraft_text::FontMatch::Missing)) => missing.push(family), Some((face, vectorcraft_text::FontMatch::Style)) => { - styles.insert(format!("{family} {style} was drawn in {} {}", face.family, face.style)); + styles.insert(format!("{family} {style} {drawn} in {} {}", face.family, face.style)); } Some(_) => {} } @@ -335,14 +353,14 @@ pub(super) fn substitution_warning_of(fonts: BTreeSet<UsedFont>) -> Option<Strin let mut parts = Vec::new(); if !missing.is_empty() { parts.push(format!( - "fonts that aren't available were written in the fallback font, {}: {} (install them, or replace them with Find Font)", + "fonts that aren't available {written} in the fallback font, {}: {} (install them, or replace them with Find Font)", vectorcraft_text::FALLBACK_FAMILY, missing.join(", ") )); } if !styles.is_empty() { parts.push(format!( - "font styles that aren't available were written in the closest style: {} (pick a style the family has)", + "font styles that aren't available {written} in the closest style: {} (pick a style the family has)", styles.into_iter().collect::<Vec<_>>().join(", ") )); } @@ -426,6 +444,8 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> { let skipped = other.into_iter().filter(|id| text(d, *id).is_some_and(|t| t.runs.iter().any(|r| matches(&r.style)))).count(); (ids, skipped) }; + // The fonts the replaced runs are set in, for the warning. + let mut set = BTreeSet::new(); let n = s.edit("Replace Font", |d, _| { let mut n = 0; for id in &ids { @@ -443,6 +463,7 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> { // Another font: none of the old one's versions or Variable Font settings. r.style.font_version = None; r.style.font_axes.clear(); + set.insert(font_of(&r.style)); changed = true; n += 1; } @@ -455,9 +476,14 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> { Ok(n) })?; let mut out = json!({ "runs": n }); + let mut warnings = Vec::new(); if skipped > 0 { out["skipped"] = json!(skipped); - out["warning"] = json!(REPLACE_SKIPPED); + warnings.push(REPLACE_SKIPPED.to_string()); + } + warnings.extend(set_font_warning(set)); + if !warnings.is_empty() { + out["warning"] = json!(warnings.join("; ")); } Ok(out) } @@ -751,6 +777,48 @@ mod open_tests { assert!(warnings.contains("Source Sans 3 Black Wide was drawn in Source Sans 3"), "{out}"); } + #[test] + fn setting_type_in_a_font_it_cant_draw_warns() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let warning = |out: &Value| out["warning"].as_str().map(str::to_string); + let made = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hi", "font": "Source Sans 3", "style": "Black Wide"})).unwrap(); + assert!(warning(&made).is_some_and(|w| w.contains("Source Sans 3 Black Wide is drawn in Source Sans 3")), "{made}"); + let gone = s.execute("text.create", &json!({"x": 10, "y": 60, "text": "Gone", "font": "No Such Font Family"})).unwrap(); + let w = warning(&gone).unwrap_or_default(); + assert!(w.contains("No Such Font Family") && w.contains(vectorcraft_text::FALLBACK_FAMILY), "{gone}"); + let plain = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Fine", "font": "Source Sans 3", "style": "Semibold"})).unwrap(); + assert_eq!(warning(&plain), None, "{plain}"); + let id = plain["id"].as_u64().unwrap(); + let set = s.execute("text.setStyle", &json!({"ids": [id], "style": "Black Wide"})).unwrap(); + assert!(warning(&set).is_some_and(|w| w.contains("Source Sans 3 Black Wide is drawn in Source Sans 3")), "{set}"); + let back = s.execute("text.setStyle", &json!({"ids": [id], "style": "Bold"})).unwrap(); + assert_eq!(warning(&back), None, "{back}"); + // Only the font the command set: the other objects' substitutes aren't its to report. + let size = s.execute("text.setStyle", &json!({"ids": [id], "size": 30})).unwrap(); + assert_eq!(warning(&size), None, "{size}"); + // Only the characters the command styles: with "Fi" in Black Wide, styling "ne" doesn't warn. + let first = s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 2, "style": "Black Wide"})).unwrap(); + assert!(warning(&first).is_some_and(|w| w.contains("Source Sans 3 Black Wide is drawn in Source Sans 3")), "{first}"); + let rest = s.execute("text.setRangeStyle", &json!({"id": id, "start": 2, "end": 4, "font": "Source Sans 3"})).unwrap(); + assert_eq!(warning(&rest), None, "{rest}"); + let range = s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 2, "font": "No Such Font Family"})).unwrap(); + assert!(warning(&range).is_some_and(|w| w.contains("No Such Font Family")), "{range}"); + let replaced = s + .execute( + "text.replaceFont", + &json!({"from": {"family": "No Such Font Family"}, "to": {"family": "Source Sans 3", "style": "Black Wide"}}), + ) + .unwrap(); + assert!(warning(&replaced).is_some_and(|w| w.contains("Source Sans 3 Black Wide is drawn in Source Sans 3")), "{replaced}"); + // Empty type: the font set is the one the next characters typed get. + let empty = s.execute("text.create", &json!({"x": 10, "y": 140, "text": ""})).unwrap()["id"].as_u64().unwrap(); + let set = s.execute("text.setStyle", &json!({"ids": [empty], "style": "Black Wide"})).unwrap(); + assert!(warning(&set).is_some_and(|w| w.contains("Black Wide")), "{set}"); + let range = s.execute("text.setRangeStyle", &json!({"id": empty, "font": "No Such Font Family"})).unwrap(); + assert!(warning(&range).is_some_and(|w| w.contains("No Such Font Family")), "{range}"); + } + #[test] fn opened_documents_have_exact_text_bounds() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index ae272f93a6..cb4a51354a 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -708,6 +708,9 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result<Value> { let t = text_ref(s, id)?; change.localize(&t, C)?; let (a, b) = range_of(p, edit::runs_len(&t.runs), C)?; + // The fonts the styled characters are set in, for the warning. + let mut set = std::collections::BTreeSet::new(); + let sets_font = change.font.is_some() || change.style.is_some(); let n = s.edit("Character", |d, _| { let t = text_mut(d, id).ok_or(EngineError::NoNode(id))?; if a == b && !t.plain_text().is_empty() { @@ -719,10 +722,19 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result<Value> { if let Some(before) = before { protect_missing_glyphs(&before, &mut t.runs); } + if sets_font { + // Empty text has one run, which the empty range styles. + let styled = if a == b { t.runs.clone() } else { edit::slice_runs(&t.runs, a, b) }; + set.extend(styled.iter().map(|r| super::fonts::font_of(&r.style))); + } refresh_bounds(t); Ok(t.runs.len()) })?; - Ok(json!({"id": id.0, "runs": n})) + let mut out = json!({"id": id.0, "runs": n}); + if let Some(w) = super::fonts::set_font_warning(set) { + out["warning"] = json!(w); + } + Ok(out) } /// The em a laid-out glyph's kerning and tracking are measured in, in text space: the size it diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 6d49301a8e..97ffea3561 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -123,7 +123,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character", [], None, - "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour, keepModel?: bool (as paint.setFill), features?: [\"dlig\", \"-liga\", …] OpenType, start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits)}", + "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour, keepModel?: bool (as paint.setFill), features?: [\"dlig\", \"-liga\", …] OpenType, start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_style ), @@ -805,6 +805,8 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> { let range = TextRange::parse(p, C)?; let ids = text_targets(s, p, C)?; let protect = s.prefs.missing_glyph_protection && (font.is_some() || style.is_some()); + // The fonts the styled characters are set in, for the warning. + let mut set = std::collections::BTreeSet::new(); s.edit("Character", |d, _| { for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; @@ -846,6 +848,17 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> { if let Some(before) = before { super::textedit::protect_missing_glyphs(&before, &mut t.runs); } + if font.is_some() || style.is_some() { + // All the text: every run, the one run of empty text included. + let styled = match range { + None => t.runs.clone(), + Some(r) => { + let (a, b) = r.bytes(t); + vectorcraft_text::edit::slice_runs(&t.runs, a, b) + } + }; + set.extend(styled.iter().map(|r| super::fonts::font_of(&r.style))); + } if let Some(j) = justify { let span = para_span(range, t); t.edit_paras(span, |pa| pa.justify = j); @@ -888,7 +901,11 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> { } Ok(()) })?; - Ok(with_overflow(s, &ids, json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))) + let mut out = with_overflow(s, &ids, json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })); + if let Some(w) = super::fonts::set_font_warning(set) { + out["warning"] = json!(w); + } + Ok(out) } /// Reshape area type's frame with `f` ([`TextObject::transform_area`], From 3a7e81e6c3d742357e90c520aa4fffdaa80e725d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 01:20:23 -0700 Subject: [PATCH 032/260] Appearance: Add New Fill copies the selected fill row right above it With a fill row selected in the Appearance panel, Add New Fill now inserts a copy of that row directly above it and selects the new fill. Rows already above the selected one stay where they are. Before, the new fill was always a copy of the topmost fill, added at the top. The selected row belongs to the first selected object. In a mixed selection, an object that shares that row gets the copy above its own equal row; an object that does not share it gets a copy of its top fill on top, as before. With a stroke row selected, or with `ids` or `target: "contents"`, Add New Fill works as before. The panel drops rows that were Cmd- or Shift-clicked together when the active row changes outside the panel, so after Add New Fill (button, menu or shortcut) only the new fill is selected. --- crates/engine/src/cmd/appearance.rs | 42 ++++++++++-- crates/engine/src/tests/appearance.rs | 68 +++++++++++++++++++ crates/ui-egui/src/panels/appearance.rs | 11 +-- crates/ui-egui/src/panels/appearance/tests.rs | 22 ++++++ 4 files changed, 134 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index f6aecc32d8..de4885564c 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -44,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> { "Add New Fill", ["Window", "Appearance"], Some("Cmd+/"), - "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row (a copy of its top fill; type without one: its characters' fill; else the default fill)", + "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row (a copy of its top fill; type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids` and no `target: \"contents\"`, the new fill is a copy of that row, right above it, and becomes the active row", has_doc, |s, p| add_item(s, p, true) ), @@ -470,12 +470,45 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> { fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> { let ids = require_targets(s, p, if fill { "appearance.addFill" } else { "appearance.addStroke" })?; let defaults = s.paint.clone(); + // The panel's active Fill row, when the new fill goes on the selection: the new fill is a copy + // of that row, right above it in each target that has it (others get a copy of their top fill). // Where the new item went in on the active item's object, when it is an image. let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied()); + // The active row is a row of the active object's stack, which need not come first in `ids` + // (they are in paint order): match the others against it. + let anchor = active.and_then(|a| ids.iter().position(|id| *id == a)); + let selected = match (s.appearance_item(), anchor) { + (Some(index), Some(_)) if fill && p.get("ids").is_none() && p.get("id").is_none() && !targets_contents(p)? => { + ItemTarget::Item { index, explicit: false, aligned: true }.of_kind(s, true) + } + _ => ItemTarget::Top, + }; + let per: Vec<Option<usize>> = match (selected, anchor) { + (ItemTarget::Item { index, .. }, Some(k)) => { + let mut order = ids.clone(); + order.swap(0, k); + let mut per: Vec<Option<usize>> = + items_per_target(&s.doc()?.doc, &order, &[index], true).into_iter().map(|v| v.first().copied()).collect(); + per.swap(0, k); + per + } + _ => vec![None; ids.len()], + }; let mut inserted = None; + // Where the new fill went in on the active item's object, when it went above the active row. + let mut above = None; s.edit(if fill { "Add New Fill" } else { "Add New Stroke" }, |d, _| { - for id in &ids { + for (id, row) in ids.iter().zip(&per) { if let Some(n) = d.node_mut(*id) { + if let Some(i) = n.appearance.item_of_kind(*row, true) + && let Some(paint) = n.appearance.paint_at(Some(i), true).cloned() + { + n.appearance.insert_item(i + 1, AppearanceItem::Fill(FillLayer::new(paint))); + if active == Some(*id) { + above = Some(i + 1); + } + continue; + } // A copy of the top fill (stroke); without one, type's characters' and otherwise the // default paint, so a new fill on a group or type shows. let paint = match (n.appearance.paint_at(None, fill), &n.kind) { @@ -509,8 +542,9 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> { } Ok(()) })?; - // The rows above the new item move up by one. - s.remap_appearance_item(&ids, |a| Some(a + usize::from(inserted.is_some_and(|k| k <= a)))); + // A fill added above the active row becomes the active row; otherwise the rows above the new + // item move up by one. + s.remap_appearance_item(&ids, |a| above.or(Some(a + usize::from(inserted.is_some_and(|k| k <= a))))); ok() } diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index d6336b86da..7d8cb2e0fb 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -288,6 +288,74 @@ fn add_fill_and_stroke_copy_the_top_ones() { assert_eq!(node(&s, id).appearance.items.len(), 3); } +/// With a fill row active, Add New Fill puts a copy of that row right above it and makes the copy +/// the active row; the rows above it stay where they are. +#[test] +fn add_fill_copies_the_active_fill_row_right_above_it() { + let mut s = session(); + let id = rect(&mut s, 100.0); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "appearance.setItem", json!({"index": 2, "color": "#0000ff"})); // [red, Stroke, blue] + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + let steps = s.doc().unwrap().history.undo.len(); + run(&mut s, "appearance.addFill", json!({})); + let n = node(&s, id); + assert_eq!(n.appearance.items.iter().map(AppearanceItem::kind_name).collect::<Vec<_>>(), ["fill", "fill", "stroke", "fill"]); + let hex = |i: usize| fill_paint(&n, i).color().unwrap().to_hex(); + assert_eq!((hex(0), hex(1), hex(3)), ("#ff0000".to_string(), "#ff0000".to_string(), "#0000ff".to_string())); + assert_eq!(s.appearance_item(), Some(1), "the new fill is the active row"); + // The next edit goes to the new fill. + run(&mut s, "paint.setFill", json!({"color": "#00ff00"})); + let n = node(&s, id); + assert_eq!((fill_paint(&n, 0).color().unwrap().to_hex(), fill_paint(&n, 1).color().unwrap().to_hex()), ("#ff0000".into(), "#00ff00".into())); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(node(&s, id).appearance.items.len(), 3); + // An active stroke row, or ids, leave the new fill on top. + run(&mut s, "appearance.setActiveItem", json!({"index": 1})); + run(&mut s, "appearance.addFill", json!({})); + assert_eq!(node(&s, id).appearance.items.iter().map(AppearanceItem::kind_name).collect::<Vec<_>>(), ["fill", "stroke", "fill", "fill"]); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + assert_eq!(fill_paint(&node(&s, id), 4).color().unwrap().to_hex(), "#0000ff"); + assert_eq!(s.appearance_item(), Some(0)); +} + +/// In a mixed selection the active fill row goes above itself in the first object; an object that +/// doesn't share that row gets a copy of its top fill on top, as without an active row. +#[test] +fn add_fill_above_an_unshared_active_row_tops_the_other_objects() { + let mut s = session(); + let (a, b) = mixed_circles(&mut s, true); // a [yellow, Stroke], b [red, green, Stroke] + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "appearance.addFill", json!({})); + let (na, nb) = (node(&s, a), node(&s, b)); + assert_eq!(na.appearance.items.iter().map(AppearanceItem::kind_name).collect::<Vec<_>>(), ["fill", "fill", "stroke"]); + assert_eq!(fill_paint(&na, 1).color().unwrap().to_hex(), "#ffff00"); + assert_eq!(nb.appearance.items.iter().map(AppearanceItem::kind_name).collect::<Vec<_>>(), ["fill", "fill", "stroke", "fill"]); + assert_eq!(fill_paint(&nb, 3).color().unwrap().to_hex(), "#00ff00"); + assert_eq!(s.appearance_item(), Some(1)); +} + +/// The active row is a row of the first selected object, also when that object paints above the +/// others. +#[test] +fn add_fill_goes_above_the_active_row_of_the_first_selected_object() { + let mut s = session(); + let (a, b) = mixed_circles(&mut s, true); // a [yellow, Stroke], b [red, green, Stroke] + run(&mut s, "select.set", json!({"ids": [b.0, a.0]})); + run(&mut s, "appearance.setActiveItem", json!({"index": 1})); // b's green fill + run(&mut s, "appearance.addFill", json!({})); + let (na, nb) = (node(&s, a), node(&s, b)); + assert_eq!(nb.appearance.items.iter().map(AppearanceItem::kind_name).collect::<Vec<_>>(), ["fill", "fill", "fill", "stroke"]); + assert_eq!(fill_paint(&nb, 2).color().unwrap().to_hex(), "#00ff00"); + assert_eq!(na.appearance.items.iter().map(AppearanceItem::kind_name).collect::<Vec<_>>(), ["fill", "stroke", "fill"]); + assert_eq!(fill_paint(&na, 2).color().unwrap().to_hex(), "#ffff00"); + assert_eq!(s.appearance_item(), Some(2)); +} + #[test] fn set_item_and_remove_item() { let mut s = session(); diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 19a578137a..09df1544ac 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -88,15 +88,16 @@ pub(crate) fn select_row(app: &mut VectorcraftApp, ctx: &egui::Context, sel: Sel } let owner = app.session.active().and_then(|d| d.selection.subjects().first().copied()); set_pstate(ctx, "ap-sel", (owner, sel)); - set_pstate(ctx, "ap-multi", (owner, sel.item().into_iter().collect::<Vec<usize>>())); + set_pstate(ctx, "ap-multi", (owner, sel.item().into_iter().collect::<Vec<usize>>(), sel.item())); } /// The selected fill/stroke rows of `n` (paint order, ascending): the active row plus those -/// Cmd/Shift-clicked with it. +/// Cmd/Shift-clicked with it. When the active row has changed since (Add New Fill makes the new +/// fill active), only the active row. fn selected_items(ctx: &egui::Context, n: Option<&Node>, sel: Sel) -> Vec<usize> { let (Some(n), Sel::Item(active)) = (n, sel) else { return vec![] }; - let (owner, mut set): (Option<NodeId>, Vec<usize>) = pstate(ctx, "ap-multi"); - if owner != Some(n.id) || !set.contains(&active) { + let (owner, mut set, at): (Option<NodeId>, Vec<usize>, Option<usize>) = pstate(ctx, "ap-multi"); + if owner != Some(n.id) || at != Some(active) || !set.contains(&active) { return vec![active]; } set.retain(|i| *i < n.appearance.items.len()); @@ -130,7 +131,7 @@ fn click_item(app: &mut VectorcraftApp, ctx: &egui::Context, n: &Node, sel: Sel, } }; select_row(app, ctx, Sel::Item(active)); - set_pstate(ctx, "ap-multi", (Some(n.id), set)); + set_pstate(ctx, "ap-multi", (Some(n.id), set, Some(active))); } /// An effect as the fx menu lists it: (id, label without the ellipsis, Effect-menu path). diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 16bc55039b..dfd7ccb638 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -438,6 +438,28 @@ fn groups_show_a_contents_row_and_type_a_characters_row_in_their_slot() { assert_eq!(rows(frame(&mut app)), ["Fill:", "Characters"]); } +/// Add New Fill (button, menu or shortcut) with rows selected: the copy of the active row lands +/// right above it and is then the only selected row. +#[test] +fn add_new_fill_selects_the_new_fill_alone() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let id = NodeId(app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + app.run("appearance.addFill", json!({})).unwrap(); // [Fill, Stroke, Fill] + let ctx = egui::Context::default(); + let n = app.session.doc().unwrap().doc.node(id).unwrap().clone(); + // Rows 0 and 1 (the stroke) Cmd-clicked together, row 0 active. + click_item(&mut app, &ctx, &n, Sel::None, 0, egui::Modifiers::NONE); + click_item(&mut app, &ctx, &n, Sel::Item(0), 1, egui::Modifiers::COMMAND); + assert_eq!(selected_items(&ctx, Some(&n), Sel::Item(0)), [0, 1]); + app.run("appearance.addFill", json!({})).unwrap(); + let n = app.session.doc().unwrap().doc.node(id).unwrap().clone(); + assert_eq!(n.appearance.items.iter().map(AppearanceItem::kind_name).collect::<Vec<_>>(), ["fill", "fill", "stroke", "fill"]); + let sel = current_sel(&app, &ctx, Some(&n)); + assert_eq!(sel, Sel::Item(1)); + assert_eq!(selected_items(&ctx, Some(&n), sel), [1]); +} + #[test] fn images_show_a_contents_row_with_new_fills_and_strokes_below_it() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); From 45b266c8056e0f9b4648efbce5c638907e08c7c1 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 01:14:24 -0700 Subject: [PATCH 033/260] Appearance: Reduce to Basic Appearance finds the active row in the first selected object The targets are in paint order, so the first selected object is not always the first target. The active row is now matched against the first selected object wherever it is among them. --- crates/engine/src/cmd/appearance.rs | 16 ++++++++++------ crates/engine/src/tests/appearance.rs | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index df691490ff..3da1cb56c1 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -615,12 +615,16 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> { // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); // The Appearance panel's active row (a row of the first selected object's stack, and in each - // other target the row equal to it there), when the command acts on that selection. - let active = match s.appearance_item() { - Some(index) - if p.get("ids").is_none() && p.get("id").is_none() && !targets_contents(p)? && s.doc()?.selection.subjects().first() == ids.first() => - { - items_per_target(&before, &ids, &[index], true) + // other target the row equal to it there), when the command acts on that selection. The targets + // are in paint order, so the first selected object can be any of them. + let first = s.doc()?.selection.subjects().first().and_then(|f| ids.iter().position(|id| id == f)); + let active = match (s.appearance_item(), first) { + (Some(index), Some(k)) if p.get("ids").is_none() && p.get("id").is_none() && !targets_contents(p)? => { + let mut from = ids.clone(); + from.swap(0, k); + let mut rows = items_per_target(&before, &from, &[index], true); + rows.swap(0, k); + rows } _ => vec![Vec::new(); ids.len()], }; diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index 4906228129..3a56ff7f18 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -444,6 +444,25 @@ fn reduce_to_basic_keeps_the_active_row() { assert_eq!(stroke(&n, 1).width, 1.0); } +/// The active row is a row of the first selected object even when that object paints above the +/// others; another object without an equal row keeps its topmost fill. +#[test] +fn reduce_to_basic_keeps_the_active_row_of_the_first_selected_object() { + let mut s = session(); + let a = rect(&mut s, 50.0); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "appearance.setItem", json!({"index": 2, "color": "#0000ff"})); // [Fill, Stroke, Fill blue] + let b = rect(&mut s, 200.0); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "appearance.setItem", json!({"index": 0, "color": "#00ff00"})); + run(&mut s, "appearance.setItem", json!({"index": 2, "color": "#ff0000"})); // [Fill green, Stroke, Fill red] + run(&mut s, "select.set", json!({"ids": [b.0, a.0]})); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "appearance.reduceToBasic", json!({})); + assert_eq!(fill_paint(&node(&s, b), 0).color().unwrap().to_hex(), "#00ff00"); + assert_eq!(fill_paint(&node(&s, a), 0).color().unwrap().to_hex(), "#0000ff"); +} + /// How many steps there are to undo and to redo, and whether the document has unsaved changes. fn history(s: &Session) -> (usize, usize, bool) { let st = s.doc().unwrap(); From 3d345ff95bb280adac3d24555c7dba07c481af44 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 23:07:50 -0700 Subject: [PATCH 034/260] Geometry: a perspective point that overflows maps to nothing instead of infinity Homography::apply checked that w is in front of the horizon but not the quotients, so a point with w just above 1e-9 and a large x or y, or a NaN w, mapped to an infinite or NaN point. apply now returns None unless the mapped point is finite. inverse, conjugated and affine_at return None when their result has an entry that is not finite. --- crates/geom/src/projective.rs | 59 ++++++++++++++++++++++++++++++----- 1 file changed, 52 insertions(+), 7 deletions(-) diff --git a/crates/geom/src/projective.rs b/crates/geom/src/projective.rs index 349ddb80f2..6264df67d3 100644 --- a/crates/geom/src/projective.rs +++ b/crates/geom/src/projective.rs @@ -40,7 +40,8 @@ impl Homography { [m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], m[2][2]] } - /// Map a point; `None` when it lands on or beyond the horizon (w ≤ 0). + /// Map a point; `None` when it lands on or beyond the horizon (w ≤ 0), or when it does not map + /// to a finite page point. pub fn apply(&self, p: Point) -> Option<Point> { let m = &self.0; let x = m[0][0] * p.x + m[0][1] * p.y + m[0][2]; @@ -49,7 +50,8 @@ impl Homography { if w <= 1e-9 || !x.is_finite() || !y.is_finite() { return None; } - Some(Point::new(x / w, y / w)) + let q = Point::new(x / w, y / w); + q.is_finite().then_some(q) } pub fn det(&self) -> f64 { @@ -58,7 +60,8 @@ impl Homography { + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]) } - /// Inverse. + /// Inverse; `None` when the map is not invertible or its inverse has an entry that is not + /// finite. pub fn inverse(&self) -> Option<Self> { let m = &self.0; let d = self.det(); @@ -77,6 +80,9 @@ impl Homography { out[r][k] = v / d; } } + if out.iter().flatten().any(|v| !v.is_finite()) { + return None; + } // H⁻¹·(x, y, 1) = (u, v, 1)/w_H, so points in front of the camera keep w > 0. Some(Self(out)) } @@ -94,16 +100,18 @@ impl Homography { } /// `self` seen through `a`: the map `a ∘ self ∘ a⁻¹` (what `self` becomes when everything it - /// maps from and to is moved by `a`). `None` when `a` isn't invertible. + /// maps from and to is moved by `a`). `None` when `a` isn't invertible or the result has an + /// entry that is not finite. pub fn conjugated(&self, a: Affine) -> Option<Self> { if a.determinant().abs() < 1e-15 { return None; } - Some(Self::from_affine(a).then_after(self).then_after(&Self::from_affine(a.inverse()))) + let c = Self::from_affine(a).then_after(self).then_after(&Self::from_affine(a.inverse())); + c.0.iter().flatten().all(|v| v.is_finite()).then_some(c) } /// The affine map that matches `self` to first order at `p` (its derivative there), `None` - /// beyond the horizon. + /// beyond the horizon or when the derivative is not finite. pub fn affine_at(&self, p: Point) -> Option<Affine> { let m = &self.0; let w = m[2][0] * p.x + m[2][1] * p.y + m[2][2]; @@ -111,7 +119,8 @@ impl Homography { // d(x/w) = (dx − (x/w)·dw) / w, and the same for y. let j = |r: usize, c: usize| (m[r][c] - [q.x, q.y][r] * m[2][c]) / w; let lin = Affine::new([j(0, 0), j(1, 0), j(0, 1), j(1, 1), 0.0, 0.0]); - Some(Affine::translate(q.to_vec2()) * lin * Affine::translate(-p.to_vec2())) + let out = Affine::translate(q.to_vec2()) * lin * Affine::translate(-p.to_vec2()); + out.is_finite().then_some(out) } /// The bounding box of the image of `r` (lines stay lines: its corners bound it), `None` when @@ -175,6 +184,42 @@ mod tests { } } + #[test] + fn a_point_that_overflows_maps_to_nothing() { + // w = 1e-8 is in front of the horizon, but 1e305 / 1e-8 overflows. + let near = Homography([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1e-8]]); + assert_eq!(near.apply(Point::new(1e305, 0.0)), None); + assert_eq!(near.apply(Point::new(0.0, -1e305)), None); + assert_eq!(near.map_rect_bbox(Rect::new(0.0, 0.0, 1e305, 1.0)), None); + assert!(near.apply(Point::new(2.0, 3.0)).unwrap().distance(Point::new(2e8, 3e8)) < 1e-6); + // A NaN w is not caught by the horizon test. + let nan = Homography([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, f64::NAN]]); + assert_eq!(nan.apply(Point::new(1.0, 1.0)), None); + } + + #[test] + fn an_inverse_that_overflows_is_none() { + let big = Homography([[1e300, 0.0, 0.0], [0.0, 1e300, 0.0], [0.0, 0.0, 1e-310]]); + assert_eq!(big.inverse(), None); + assert!(h().inverse().is_some()); + } + + #[test] + fn a_derivative_that_overflows_is_none() { + // The point maps to 1e300, but the derivative there is 1e302 / 1e-8. + let steep = Homography([[1e302, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1e-8]]); + let p = Point::new(1e-10, 0.0); + assert!(steep.apply(p).is_some()); + assert_eq!(steep.affine_at(p), None); + } + + #[test] + fn a_conjugate_that_overflows_is_none() { + let far = Homography([[1.0, 0.0, 1e200], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]); + assert_eq!(far.conjugated(Affine::scale(1e150)), None); + assert!(far.conjugated(Affine::scale(2.0)).is_some()); + } + #[test] fn rect_bbox_is_the_corners_box() { let b = h().map_rect_bbox(Rect::new(0.0, 0.0, 10.0, 20.0)).unwrap(); From 021fa4a8460cd5f28e4b70d1ad682897ba4eace0 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 15:01:22 -0700 Subject: [PATCH 035/260] Shortcuts: Shift+Comma and Shift+Period follow their key positions only with Shift alone The key-position match for Shift+Comma and Shift+Period now applies only when Shift is the only modifier. Cmd/Ctrl+Shift and Alt+Shift presses at those keys keep their logical key, so the type-size shortcuts on German-like layouts behave as before. The typing test also checks that no paint command runs while text is edited. --- crates/ui-egui/src/shortcuts.rs | 4 ++++ crates/ui-egui/src/shortcuts/tests.rs | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 504e84b2d7..8b8355b074 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -736,6 +736,10 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, accept: impl FnMut(&H for e in &mut i.events { if let egui::Event::Key { key, physical_key: Some(physical), modifiers, pressed: true, .. } = e && modifiers.shift + && !modifiers.command + && !modifiers.ctrl + && !modifiers.alt + && !modifiers.mac_cmd && matches!(*physical, Key::Comma | Key::Period) && *key != *physical && let (Some(logical), Some(position)) = (craft_keymap::Key::from_egui(*key), craft_keymap::Key::from_egui(*physical)) diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 6bce0cc6fb..56e552b316 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1184,12 +1184,37 @@ fn plain_and_shifted_paint_keys_run_once_on_us_and_german_like_input() { (Key::Colon, Key::Period, Modifiers::SHIFT, ":"), (Key::Semicolon, Key::Comma, Modifiers::SHIFT, ";"), ] { + let journal_before = app.session.journal.len(); frame(&mut app, press(key, physical_key, mods, typed)); assert_eq!(crate::panels::current_paints(&app), paints_before, "typing {typed} keeps fill and stroke"); + assert!( + app.session.journal.since(journal_before).iter().all(|(command, _)| !command.starts_with("paint.")), + "typing {typed} runs no paint command" + ); } assert_eq!(text_and_layers(&mut app, id).0, "Hi,.<>:;"); } +#[test] +fn modified_german_like_punctuation_keeps_text_size() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "Hi", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + for (key, physical_key) in [(Key::Colon, Key::Period), (Key::Semicolon, Key::Comma)] { + let modifiers = Modifiers::COMMAND | Modifiers::SHIFT; + frame( + &mut app, + vec![ + egui::Event::ModifiersChanged(modifiers), + egui::Event::Key { key, physical_key: Some(physical_key), pressed: true, repeat: false, modifiers }, + ], + ); + let range = app.session.execute("text.getRange", &json!({"id": id})).unwrap(); + assert_eq!(range["runs"][0]["style"]["size"], json!(12.0), "{key:?} keeps the text size"); + } +} + #[test] fn explicit_logical_shifted_binding_wins_over_position_alias() { let mut app = remembered_paint_app(); From db38e2e1144dd07e419f4668c35e70d41726e721 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 23:27:44 -0700 Subject: [PATCH 036/260] Perspective: a projection that a transform overflows is scaled down or removed When moving type or a symbol instance in perspective makes the conjugated projection overflow, Homography::conjugated now forms the product from factors scaled to a largest entry of 1 and returns it at that scale, which maps every point to the same place. When even the scaled result is not invertible, the transform removes the projection and the art is drawn flat, instead of keeping the old projection while the flat art moves. --- crates/doc/src/node/tests.rs | 29 ++++++++++++++++++++++++ crates/doc/src/perspective.rs | 8 ++++--- crates/geom/src/projective.rs | 42 ++++++++++++++++++++++++++++++----- 3 files changed, 71 insertions(+), 8 deletions(-) diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index dc241841fa..b4cc7b0722 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -339,6 +339,35 @@ fn transform_group_recurses() { assert_eq!(child.appearance.stroke_width(), 2.0); } +/// A symbol instance in perspective keeps its picture moved by a transform, and loses its +/// projection when no invertible map of finite numbers draws the moved picture. +#[test] +fn a_projection_follows_the_transform_or_is_removed() { + use vectorcraft_geom::{Homography, Point}; + let instance = |h: Homography| { + let mut n = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "S".into(), xf: Affine::IDENTITY }); + n.extras_mut().perspective = + Some(Box::new(crate::PerspectiveAttachment { projection: Some(h.to_array()), ..crate::PerspectiveAttachment::new("left", 0.0) })); + n + }; + let projection = |n: &Node| n.extras().perspective.as_deref().and_then(|p| p.projection); + // A move by 10 scaled by 1e307: moved by a scale by 10, the product overflows unless scaled down. + let big = Homography([[1e307, 0.0, 1e308], [0.0, 1e307, 0.0], [0.0, 0.0, 1e307]]); + let mut n = instance(big); + n.transform(Affine::scale(10.0), false); + let p = Point::new(3.0, 7.0); + assert!(n.projection().unwrap().apply(p).unwrap().distance(Point::new(103.0, 7.0)) < 1e-9); + // A move by 1e200 moved by a scale by 1e150 sends every point to about (1e350, 0). + let far = Homography([[1.0, 0.0, 1e200], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]); + let mut n = instance(far); + n.transform(Affine::scale(1e150), false); + assert_eq!(projection(&n), None); + // A transform that is not invertible leaves the projection as it is. + let mut n = instance(far); + n.transform(Affine::scale(0.0), false); + assert_eq!(projection(&n), Some(far.to_array())); +} + #[test] fn unplaced_gradients_pin_only_when_a_refit_would_differ() { use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, Paint}; diff --git a/crates/doc/src/perspective.rs b/crates/doc/src/perspective.rs index 4de3823dba..6ec18bcfa2 100644 --- a/crates/doc/src/perspective.rs +++ b/crates/doc/src/perspective.rs @@ -58,12 +58,14 @@ impl Node { } } - /// Keep a projection drawing the same picture moved by `a` (the flat art moves by `a` too). + /// Keep a projection drawing the same picture moved by `a` (the flat art moves by `a` too). An + /// invertible `a` that the projection cannot follow removes it, and the art is drawn flat. pub(crate) fn transform_projection(&mut self, a: vectorcraft_geom::Affine) { if let Some(p) = self.extras_if_any().and_then(|e| e.perspective.as_deref_mut()) - && let Some(h) = p.homography().and_then(|h| h.conjugated(a)) + && let Some(h) = p.homography() + && a.determinant().abs() >= 1e-15 { - p.projection = Some(h.to_array()); + p.projection = h.conjugated(a).map(|h| h.to_array()); } } } diff --git a/crates/geom/src/projective.rs b/crates/geom/src/projective.rs index 6264df67d3..e7754c1312 100644 --- a/crates/geom/src/projective.rs +++ b/crates/geom/src/projective.rs @@ -100,14 +100,31 @@ impl Homography { } /// `self` seen through `a`: the map `a ∘ self ∘ a⁻¹` (what `self` becomes when everything it - /// maps from and to is moved by `a`). `None` when `a` isn't invertible or the result has an - /// entry that is not finite. + /// maps from and to is moved by `a`). When the product overflows, it is formed from factors + /// scaled to a largest entry of 1 and returned at that scale (the same map). `None` when `a` + /// isn't invertible, or when the product overflows and the scaled result is not invertible. pub fn conjugated(&self, a: Affine) -> Option<Self> { if a.determinant().abs() < 1e-15 { return None; } - let c = Self::from_affine(a).then_after(self).then_after(&Self::from_affine(a.inverse())); - c.0.iter().flatten().all(|v| v.is_finite()).then_some(c) + let (to, from) = (Self::from_affine(a), Self::from_affine(a.inverse())); + let c = to.then_after(self).then_after(&from); + if c.is_finite() { + return Some(c); + } + let c = to.normalized()?.then_after(&self.normalized()?).then_after(&from.normalized()?).normalized()?; + (c.det().abs() > 1e-15).then_some(c) + } + + fn is_finite(&self) -> bool { + self.0.iter().flatten().all(|v| v.is_finite()) + } + + /// `self` divided by its largest entry magnitude, a positive scale that maps every point to + /// the same place; `None` when an entry is not finite or every entry is 0. + fn normalized(&self) -> Option<Self> { + let k = self.0.iter().flatten().fold(0.0_f64, |k, v| k.max(v.abs())); + (self.is_finite() && k > 0.0).then(|| Self(self.0.map(|row| row.map(|v| v / k)))) } /// The affine map that matches `self` to first order at `p` (its derivative there), `None` @@ -214,10 +231,25 @@ mod tests { } #[test] - fn a_conjugate_that_overflows_is_none() { + fn a_conjugate_that_overflows_is_scaled_down() { + // A move by 10, scaled by 1e307: seen through a scale by 10 it moves by 100, but the + // product's corner entry is 1e309. + let big = Homography([[1e307, 0.0, 1e308], [0.0, 1e307, 0.0], [0.0, 0.0, 1e307]]); + let t = Affine::scale(10.0); + let c = big.conjugated(t).unwrap(); + assert!(c.0.iter().flatten().all(|v| v.is_finite() && v.abs() <= 1.0)); + assert_eq!(Homography::from_array(c.to_array()), Some(c)); + for p in [Point::new(3.0, 7.0), Point::new(-4.0, 1.5)] { + assert!(c.apply(t * p).unwrap().distance(t * big.apply(p).unwrap()) < 1e-9); + assert!(c.apply(p).unwrap().distance(p + kurbo::Vec2::new(100.0, 0.0)) < 1e-9); + } + // A move by 1e200 seen through a scale by 1e150 sends every point to about (1e350, 0), + // which no invertible map of finite numbers draws. let far = Homography([[1.0, 0.0, 1e200], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]); assert_eq!(far.conjugated(Affine::scale(1e150)), None); assert!(far.conjugated(Affine::scale(2.0)).is_some()); + // A product that does not overflow is kept as it is. + assert_eq!(far.conjugated(Affine::scale(2.0)).unwrap().0[0][2], 2e200); } #[test] From 55108efef4675cf09bf1e0b4d1731192d7bce2fc Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 15:24:53 -0700 Subject: [PATCH 037/260] Toolbar: the paint-chip tips name Shift+, and Shift+. instead of < and > The Color and Gradient tips now read "Color (, or Shift+,)" and "Gradient (. or Shift+.)". The shortcuts follow the key positions, so on layouts where Shift at those keys types another character the tips name the keys to press. The 25 catalogs with these rows and the toolbar accessibility test follow. --- crates/ui-egui/src/i18n/bg.tsv | 4 ++-- crates/ui-egui/src/i18n/ca.tsv | 4 ++-- crates/ui-egui/src/i18n/cs.tsv | 4 ++-- crates/ui-egui/src/i18n/da.tsv | 4 ++-- crates/ui-egui/src/i18n/de.tsv | 4 ++-- crates/ui-egui/src/i18n/el.tsv | 4 ++-- crates/ui-egui/src/i18n/es.tsv | 4 ++-- crates/ui-egui/src/i18n/fi.tsv | 4 ++-- crates/ui-egui/src/i18n/fr.tsv | 4 ++-- crates/ui-egui/src/i18n/hu.tsv | 4 ++-- crates/ui-egui/src/i18n/id.tsv | 4 ++-- crates/ui-egui/src/i18n/it.tsv | 4 ++-- crates/ui-egui/src/i18n/ja.tsv | 4 ++-- crates/ui-egui/src/i18n/ka.tsv | 4 ++-- crates/ui-egui/src/i18n/ko.tsv | 4 ++-- crates/ui-egui/src/i18n/nl.tsv | 4 ++-- crates/ui-egui/src/i18n/pl.tsv | 4 ++-- crates/ui-egui/src/i18n/pt-br.tsv | 4 ++-- crates/ui-egui/src/i18n/ru.tsv | 4 ++-- crates/ui-egui/src/i18n/sv.tsv | 4 ++-- crates/ui-egui/src/i18n/tr.tsv | 4 ++-- crates/ui-egui/src/i18n/uk.tsv | 4 ++-- crates/ui-egui/src/i18n/vi.tsv | 4 ++-- crates/ui-egui/src/i18n/zh-hans.tsv | 4 ++-- crates/ui-egui/src/i18n/zh-hant.tsv | 4 ++-- crates/ui-egui/src/toolbar.rs | 4 +++- crates/ui-egui/src/toolbar/tests.rs | 2 +- 27 files changed, 54 insertions(+), 52 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 84ef4701b0..706c4a5f65 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -495,7 +495,7 @@ font-technology Variable Променливи Collect in New Layer Събиране в нов слой Collect Links in a Separate Folder Събиране на връзките в отделна папка Color Цвят - Color (, or <) Цвят (, или <) + Color (, or Shift+,) Цвят (, или Shift+,) Color Adjustments Цветови корекции Color bars Цветови скали Color blindness – Deuteranopia-type Цветна слепота – тип девтеранопия @@ -1235,7 +1235,7 @@ font-technology Variable Променливи GPL palettes keep solid colours only, as RGB. Палитрите GPL запазват само плътни цветове като RGB. GPU Performance Производителност на графичния процесор Gradient Градиент - Gradient (. or >) Градиент (. или >) + Gradient (. or Shift+.) Градиент (. или Shift+.) Gradient across stroke Градиент напречно на щриха Gradient along stroke Градиент по дължината на щриха Gradient and Mesh Resolution: Разделителна способност на градиент и мрежа: diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 42e560cc97..597eb81828 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -708,7 +708,7 @@ Collect in New Layer Recull en una capa nova Collect Links in a Separate Folder Recull els enllaços en una carpeta a part Color Color - Color (, or <) Color (, o <) + Color (, or Shift+,) Color (, o Maj+,) Color Adjustments Ajustos de color Color bars Barres de color Color blindness – Deuteranopia-type Daltonisme – tipus deuteranòpsia @@ -1690,7 +1690,7 @@ GPU Performance Rendiment de la GPU Grab bag Calaix de sastre Gradient Degradat - Gradient (. or >) Degradat (. o >) + Gradient (. or Shift+.) Degradat (. o Maj+.) Gradient across stroke Degradat transversal al traç Gradient along stroke Degradat al llarg del traç Gradient and Mesh Resolution: Resolució de degradat i malla: diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index ee3a5acb1b..b1539f4d85 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1209,12 +1209,12 @@ lighting Light Světlo to set spacing and orientation nastaví rozestupy a orientaci Apply Použít Change Screen Mode (F) Změnit režim obrazovky (F) - Color (, or <) Barva (, nebo <) + Color (, or Shift+,) Barva (, nebo Shift+,) Draw Behind Kreslit za Draw Inside Kreslit dovnitř Draw Normal Kreslit normálně Expand: Rozložit: - Gradient (. or >) Přechod (. nebo >) + Gradient (. or Shift+.) Přechod (. nebo Shift+.) H: V: Modify Úpravy Navigate Pohled diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 2372e6020f..e1f760e1f0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1127,12 +1127,12 @@ lighting Light Lys to set spacing and orientation for at angive afstand og orientering Apply Anvend Change Screen Mode (F) Skift skærmtilstand (F) - Color (, or <) Farve (, eller <) + Color (, or Shift+,) Farve (, eller Skift+,) Draw Behind Tegn bagved Draw Inside Tegn indeni Draw Normal Tegn normalt Expand: Udvid: - Gradient (. or >) Gradient (. eller >) + Gradient (. or Shift+.) Gradient (. eller Skift+.) H: H: Modify Ændr Navigate Navigér diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 44c46ab54b..bcfc78c073 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -487,7 +487,7 @@ font-technology Variable Variabel Collect in New Layer In neuer Ebene sammeln Collect Links in a Separate Folder Verknüpfungen in separatem Ordner sammeln Color Farbe - Color (, or <) Farbe (, oder <) + Color (, or Shift+,) Farbe (, oder Shift+,) Color Adjustments Farbkorrekturen Color bars Farbkontrollstreifen Color blindness – Deuteranopia-type Farbenblindheit – Deuteranopie @@ -1259,7 +1259,7 @@ file-filter Templates Vorlagen GPL palettes keep solid colours only, as RGB. GPL-Paletten enthalten nur einfarbige Farben, als RGB. GPU Performance GPU-Leistung Gradient Verlauf - Gradient (. or >) Verlauf (. oder >) + Gradient (. or Shift+.) Verlauf (. oder Shift+.) Gradient across stroke Verlauf quer zur Kontur Gradient along stroke Verlauf entlang der Kontur Gradient and Mesh Resolution: Auflösung für Verläufe und Gitter: diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a7e06cec80..8305782fa4 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -470,7 +470,7 @@ font-technology Variable Μεταβλητές Collect in New Layer Συγκέντρωση σε νέο επίπεδο Collect Links in a Separate Folder Συγκέντρωση συνδεδεμένων αρχείων σε ξεχωριστό φάκελο Color Χρώμα - Color (, or <) Χρώμα (, ή <) + Color (, or Shift+,) Χρώμα (, ή Shift+,) Color Adjustments Ρυθμίσεις χρώματος Color bars Χρωματικές μπάρες Color blindness – Deuteranopia-type Αχρωματοψία – τύπου δευτερανοπίας @@ -1199,7 +1199,7 @@ font-technology Variable Μεταβλητές GPL palettes keep solid colours only, as RGB. Οι παλέτες GPL διατηρούν μόνο συμπαγή χρώματα σε RGB. GPU Performance Απόδοση GPU Gradient Ντεγκραντέ - Gradient (. or >) Ντεγκραντέ (. ή >) + Gradient (. or Shift+.) Ντεγκραντέ (. ή Shift+.) Gradient across stroke Ντεγκραντέ εγκάρσια στο περίγραμμα Gradient along stroke Ντεγκραντέ κατά μήκος του περιγράμματος Gradient and Mesh Resolution: Ανάλυση ντεγκραντέ και πλέγματος: diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c34f741d4e..cd071b0ae1 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -509,7 +509,7 @@ font-technology Variable Variables Collect in New Layer Reunir en capa nueva Collect Links in a Separate Folder Reunir vínculos en una carpeta aparte Color Color - Color (, or <) Color (, o <) + Color (, or Shift+,) Color (, o Shift+,) Color Adjustments Ajustes de color Color bars Barras de color Color blindness – Deuteranopia-type Daltonismo – tipo deuteranopía @@ -1272,7 +1272,7 @@ font-technology Variable Variables GPL palettes keep solid colours only, as RGB. Las paletas GPL solo conservan colores sólidos, en RGB. GPU Performance Rendimiento de GPU Gradient Degradado - Gradient (. or >) Degradado (. o >) + Gradient (. or Shift+.) Degradado (. o Shift+.) Gradient across stroke Degradado a lo ancho del trazo Gradient along stroke Degradado a lo largo del trazo Gradient and Mesh Resolution: Resolución de degradados y mallas: diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 2614a0929f..1d34418d98 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1187,12 +1187,12 @@ lighting Light Valo to set spacing and orientation asettaaksesi välit ja suunnan Apply Käytä Change Screen Mode (F) Vaihda näyttötilaa (F) - Color (, or <) Väri (, tai <) + Color (, or Shift+,) Väri (, tai Shift+,) Draw Behind Piirrä taakse Draw Inside Piirrä sisään Draw Normal Piirrä normaalisti Expand: Laajenna: - Gradient (. or >) Liukuväri (. tai >) + Gradient (. or Shift+.) Liukuväri (. tai Shift+.) H: K: Modify Muokkaa Navigate Siirry diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index b837907d65..5e1c40015e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -510,7 +510,7 @@ font-technology Variable Variables Collect in New Layer Rassembler dans un nouveau calque Collect Links in a Separate Folder Rassembler les liens dans un dossier distinct Color Couleur - Color (, or <) Couleur (, ou <) + Color (, or Shift+,) Couleur (, ou Maj+,) Color Adjustments Réglages de couleur Color bars Barres de couleurs Color blindness – Deuteranopia-type Daltonisme – type deutéranopie @@ -1272,7 +1272,7 @@ font-technology Variable Variables GPL palettes keep solid colours only, as RGB. Les palettes GPL ne conservent que les couleurs unies, en RVB. GPU Performance Performances GPU Gradient Dégradé - Gradient (. or >) Dégradé (. ou >) + Gradient (. or Shift+.) Dégradé (. ou Maj+.) Gradient across stroke Dégradé sur la largeur du contour Gradient along stroke Dégradé le long du contour Gradient and Mesh Resolution: Résolution des dégradés et des filets : diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 03dab8279d..cc72129c0a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -679,7 +679,7 @@ font-technology Variable Változó Collect in New Layer Összegyűjtés új rétegbe Collect Links in a Separate Folder Csatolások gyűjtése külön mappába Color Szín - Color (, or <) Szín (, vagy <) + Color (, or Shift+,) Szín (, vagy Shift+,) Color Adjustments Színkorrekciók Color bars Színsávok Color blindness – Deuteranopia-type Színvakság – deuteranópia @@ -1590,7 +1590,7 @@ file-filter Templates Sablonok GPU Performance GPU-teljesítmény Grab bag Vegyes Gradient Színátmenet - Gradient (. or >) Színátmenet (. vagy >) + Gradient (. or Shift+.) Színátmenet (. vagy Shift+.) Gradient across stroke Színátmenet a körvonalon keresztben Gradient along stroke Színátmenet a körvonal mentén Gradient and Mesh Resolution: Színátmenet és háló felbontása: diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 52c29b570c..34ca64d532 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1127,12 +1127,12 @@ lighting Light Cahaya to set spacing and orientation untuk mengatur jarak dan orientasi Apply Terapkan Change Screen Mode (F) Ganti mode layar (F) - Color (, or <) Warna (, atau <) + Color (, or Shift+,) Warna (, atau Shift+,) Draw Behind Gambar di belakang Draw Inside Gambar di dalam Draw Normal Gambar normal Expand: Perluas: - Gradient (. or >) Gradien (. atau >) + Gradient (. or Shift+.) Gradien (. atau Shift+.) H: H: Modify Ubah Navigate Navigasi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index a681efadf6..7eabb61750 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -509,7 +509,7 @@ font-technology Variable Variabili Collect in New Layer Raccogli in un nuovo livello Collect Links in a Separate Folder Raccogli i collegamenti in una cartella separata Color Colore - Color (, or <) Colore (, o <) + Color (, or Shift+,) Colore (, o Shift+,) Color Adjustments Regolazioni colore Color bars Barre colore Color blindness – Deuteranopia-type Daltonismo – tipo deuteranopia @@ -1282,7 +1282,7 @@ file-filter Templates Modelli GPL palettes keep solid colours only, as RGB. Le palette GPL conservano solo i colori pieni, in RGB. GPU Performance Prestazioni GPU Gradient Sfumatura - Gradient (. or >) Sfumatura (. o >) + Gradient (. or Shift+.) Sfumatura (. o Shift+.) Gradient across stroke Sfumatura trasversale alla traccia Gradient along stroke Sfumatura lungo la traccia Gradient and Mesh Resolution: Risoluzione sfumature e trame: diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 8c31a2eb7f..b08889efda 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3364,7 +3364,7 @@ gradient-kind Radial 円形 Client-side (.html) クライアントサイド (.html) Cmd Cmd Collect Links in a Separate Folder リンクを別フォルダーに収集 - Color (, or <) カラー (, または <) + Color (, or Shift+,) カラー (, または Shift+,) Color Group カラーグループ Color Library カラーライブラリ Color Management カラーマネジメント @@ -3459,7 +3459,7 @@ file-filter Templates テンプレート General › Placement › X 一般 › 位置 › X General › Thumbnails 一般 › サムネール Global Process Color, CMYK グローバルプロセスカラー、CMYK - Gradient (. or >) グラデーション (. または >) + Gradient (. or Shift+.) グラデーション (. または Shift+.) Graph Data グラフデータ Graph Type グラフの種類 Graph Design グラフのデザイン diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 33eae7aece..208ff506be 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1061,12 +1061,12 @@ lighting Light სინათლე to set spacing and orientation — ინტერვალისა და ორიენტაციის დასაყენებლად Apply გამოყენება Change Screen Mode (F) ეკრანის რეჟიმის შეცვლა (F) - Color (, or <) ფერი (, ან <) + Color (, or Shift+,) ფერი (, ან Shift+,) Draw Behind უკან ხატვა Draw Inside შიგნით ხატვა Draw Normal ჩვეულებრივი ხატვა Expand: გაშლა: - Gradient (. or >) გრადიენტი (. ან >) + Gradient (. or Shift+.) გრადიენტი (. ან Shift+.) H: სიმ.: Modify შეცვლა Navigate ნავიგაცია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index cf3254be22..6be4d08703 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3353,7 +3353,7 @@ gradient-kind Radial 방사형 Client-side (.html) 클라이언트 측 (.html) Cmd Cmd Collect Links in a Separate Folder 링크를 별도 폴더에 모으기 - Color (, or <) 색상 (, 또는 <) + Color (, or Shift+,) 색상 (, 또는 Shift+,) Color Group 색상 그룹 Color Library 색상 라이브러리 Color Management 색상 관리 @@ -3448,7 +3448,7 @@ file-filter Templates 템플릿 General › Placement › X 일반 › 배치 › X General › Thumbnails 일반 › 축소판 Global Process Color, CMYK 글로벌 프로세스 색상, CMYK - Gradient (. or >) 그레이디언트 (. 또는 >) + Gradient (. or Shift+.) 그레이디언트 (. 또는 Shift+.) Graph Data 그래프 데이터 Graph Type 그래프 유형 Graph Design 그래프 디자인 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 2801614915..6078c314c9 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1141,12 +1141,12 @@ lighting Light Licht to set spacing and orientation om de tussenruimte en de oriëntatie in te stellen Apply Toepassen Change Screen Mode (F) Schermmodus wisselen (F) - Color (, or <) Kleur (, of <) + Color (, or Shift+,) Kleur (, of Shift+,) Draw Behind Achter tekenen Draw Inside Binnen tekenen Draw Normal Normaal tekenen Expand: Uitvouwen: - Gradient (. or >) Verloop (. of >) + Gradient (. or Shift+.) Verloop (. of Shift+.) H: H: Modify Wijzigen Navigate Navigeren diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 880adf64a3..63dd77d7d6 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1140,12 +1140,12 @@ lighting Light Światło to set spacing and orientation aby ustawić odstęp i orientację Apply Zastosuj Change Screen Mode (F) Zmień tryb ekranu (F) - Color (, or <) Kolor (, lub <) + Color (, or Shift+,) Kolor (, lub Shift+,) Draw Behind Rysuj pod spodem Draw Inside Rysuj wewnątrz Draw Normal Rysuj normalnie Expand: Rozszerz: - Gradient (. or >) Gradient (. lub >) + Gradient (. or Shift+.) Gradient (. lub Shift+.) H: W: Modify Modyfikuj Navigate Nawigacja diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a4aea80cf8..94508e9659 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4330,7 +4330,7 @@ axis Both Ambos Client-side (.html) Lado do Cliente (.html) Cmd Cmd Collect Links in a Separate Folder Reunir Links em uma Pasta Separada - Color (, or <) Cor (, ou <) + Color (, or Shift+,) Cor (, ou Shift+,) Color bars Barras de cores Color Group Grupo de Cores Color Library Biblioteca de Cores @@ -4403,7 +4403,7 @@ axis Both Ambos General › Placement › X Geral › Posicionamento › X General › Thumbnails Geral › Miniaturas Global Process Color, CMYK Cor de Processo Global, CMYK - Gradient (. or >) Gradiente (. ou >) + Gradient (. or Shift+.) Gradiente (. ou Shift+.) Graph Data Dados do Gráfico Graph Type Tipo de Gráfico New Design Novo Design diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 7ebfa3c2b3..37e6eb061e 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -507,7 +507,7 @@ font-technology Variable Вариативные Collect in New Layer Собрать в новый слой Collect Links in a Separate Folder Собрать связи в отдельную папку Color Цвет - Color (, or <) Цвет (, или <) + Color (, or Shift+,) Цвет (, или Shift+,) Color Adjustments Настройки цвета Color bars Цветные полосы Color blindness – Deuteranopia-type Дальтонизм — дейтеранопия @@ -1280,7 +1280,7 @@ file-filter Templates Шаблоны GPL palettes keep solid colours only, as RGB. Палитры GPL сохраняют только сплошные цвета в RGB. GPU Performance Производительность GPU Gradient Градиент - Gradient (. or >) Градиент (. или >) + Gradient (. or Shift+.) Градиент (. или Shift+.) Gradient across stroke Градиент поперёк обводки Gradient along stroke Градиент вдоль обводки Gradient and Mesh Resolution: Разрешение градиентов и сеток: diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 390cc84234..fbed797583 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -497,7 +497,7 @@ font-technology Variable Variabla Collect in New Layer Samla i nytt lager Collect Links in a Separate Folder Samla länkar i en separat mapp Color Färg - Color (, or <) Färg (, eller <) + Color (, or Shift+,) Färg (, eller Shift+,) Color Adjustments Färgjusteringar Color bars Färgstaplar Color blindness – Deuteranopia-type Färgblindhet – deuteranopi @@ -1237,7 +1237,7 @@ font-technology Variable Variabla GPL palettes keep solid colours only, as RGB. GPL-paletter sparar bara enfärgade färger, som RGB. GPU Performance GPU-prestanda Gradient Gradient - Gradient (. or >) Gradient (. eller >) + Gradient (. or Shift+.) Gradient (. eller Shift+.) Gradient across stroke Gradient tvärs över konturen Gradient along stroke Gradient längs konturen Gradient and Mesh Resolution: Upplösning för gradienter och nät: diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index b16002086b..aabe5c6452 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -491,7 +491,7 @@ font-technology Variable Değişken Collect in New Layer Yeni Katmanda Topla Collect Links in a Separate Folder Bağlantıları Ayrı Bir Klasörde Toplayın Color Renk - Color (, or <) Renk (, veya <) + Color (, or Shift+,) Renk (, veya Shift+,) Color Adjustments Renk Ayarlamaları Color bars Renk çubukları Color blindness – Deuteranopia-type Renk körlüğü – Döteranopi tipi @@ -1214,7 +1214,7 @@ font-technology Variable Değişken GPL palettes keep solid colours only, as RGB. GPL paletleri yalnızca düz renkleri RGB olarak tutar. GPU Performance GPU Performansı Gradient Degrade - Gradient (. or >) Gradyan (. veya >) + Gradient (. or Shift+.) Gradyan (. veya Shift+.) Gradient across stroke Kontur boyunca gradyan Gradient along stroke Kontur boyunca gradyan Gradient and Mesh Resolution: Gradyan ve Mesh Çözünürlüğü: diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d3c0cda4fc..b3553b0445 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -503,7 +503,7 @@ font-technology Variable Варіативні Collect in New Layer Зібрати у новий шар Collect Links in a Separate Folder Зібрати зв’язки в окрему папку Color Колір - Color (, or <) Колір (, або <) + Color (, or Shift+,) Колір (, або Shift+,) Color Adjustments Налаштування кольору Color bars Кольорові смуги Color blindness – Deuteranopia-type Дальтонізм - дейтеранопія @@ -1276,7 +1276,7 @@ file-filter Templates Шаблони GPL palettes keep solid colours only, as RGB. Палітри GPL зберігають лише суцільні кольори RGB. GPU Performance Продуктивність GPU Gradient Градієнт - Gradient (. or >) Градієнт (. або >) + Gradient (. or Shift+.) Градієнт (. або Shift+.) Gradient across stroke Градієнт упоперек обведення Gradient along stroke Градієнт вздовж обведення Gradient and Mesh Resolution: Роздільна здатність градієнтів і сіток: diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 63c0825dfb..4bb1fd1226 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -591,7 +591,7 @@ font-technology Variable Biến thiên Collect in New Layer Thu thập vào lớp mới Collect Links in a Separate Folder Thu thập liên kết vào thư mục riêng Color Màu - Color (, or <) Màu (, hoặc <) + Color (, or Shift+,) Màu (, hoặc Shift+,) Color Adjustments Điều chỉnh màu sắc Color bars Thanh màu Color blindness – Deuteranopia-type Mù màu – loại Deuteranopia @@ -1490,7 +1490,7 @@ file-filter Templates Mẫu GPU Performance Hiệu suất GPU Grab bag Tổng hợp Gradient Chuyển sắc - Gradient (. or >) Chuyển sắc (. hoặc >) + Gradient (. or Shift+.) Chuyển sắc (. hoặc Shift+.) Gradient across stroke Chuyển sắc ngang qua nét Gradient along stroke Chuyển sắc dọc theo nét Gradient and Mesh Resolution: Độ phân giải chuyển sắc và lưới: diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5fe6e81923..bd495d05d6 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -455,7 +455,7 @@ Collect in New Layer 收集到新图层 Collect Links in a Separate Folder 将链接收集到单独的文件夹 Color 颜色 - Color (, or <) 颜色 (, 或 <) + Color (, or Shift+,) 颜色 (, 或 Shift+,) Color Adjustments 色彩调整 Color bars 色彩条 Color blindness – Deuteranopia-type 色盲 – 绿色盲型 @@ -1220,7 +1220,7 @@ file-filter Templates 模板 GPL palettes keep solid colours only, as RGB. GPL 调板仅保留为 RGB 的纯色。 GPU Performance GPU 性能 Gradient 渐变 - Gradient (. or >) 渐变 (. 或 >) + Gradient (. or Shift+.) 渐变 (. 或 Shift+.) Gradient across stroke 横跨描边的渐变 Gradient along stroke 沿描边的渐变 Gradient and Mesh Resolution: 渐变和网格分辨率: diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e352fe56be..f69992edd9 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -471,7 +471,7 @@ font-technology Variable 可變 Collect in New Layer 收集至新圖層 Collect Links in a Separate Folder 將連結收集到獨立的資料夾 Color 顏色 - Color (, or <) 顏色 (, 或 <) + Color (, or Shift+,) 顏色 (, 或 Shift+,) Color Adjustments 色彩調整 Color bars 色彩條 Color blindness – Deuteranopia-type 色盲 – 綠色盲型 @@ -1246,7 +1246,7 @@ file-filter Templates 範本 GPL palettes keep solid colours only, as RGB. GPL 調色盤僅保留純色,並以 RGB 儲存。 GPU Performance GPU 效能 Gradient 漸層 - Gradient (. or >) 漸層 (. 或 >) + Gradient (. or Shift+.) 漸層 (. 或 Shift+.) Gradient across stroke 橫跨筆畫的漸層 Gradient along stroke 沿筆畫的漸層 Gradient and Mesh Resolution: 漸層與網格解析度: diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 02efbfd4c3..33a2eb10b8 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -486,7 +486,9 @@ fn bottom_controls(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, cols: usiz ui.add_space((ui.available_width() - 3.0 * chip - 2.0 * gap) / 2.0); ui.spacing_mut().item_spacing.x = gap; let mut clicked = None; - for (tip, cmd) in [("Color (, or <)", "paint.lastColor"), ("Gradient (. or >)", "paint.lastGradient"), ("None (/)", "paint.none")] { + for (tip, cmd) in + [("Color (, or Shift+,)", "paint.lastColor"), ("Gradient (. or Shift+.)", "paint.lastGradient"), ("None (/)", "paint.none")] + { let (r, resp) = ui.allocate_exact_size(vec2(chip, chip), Sense::click()); match cmd { "paint.lastColor" => widgets::paint_chip(ui, r, &Paint::solid(app.session.last_solid)), diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index e8e3f49776..a1a29f7757 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -109,7 +109,7 @@ fn screen_readers_name_the_tool_buttons_and_the_active_tool() { let name = |id| tool_info(id).map(tip).unwrap_or_default(); assert_eq!(role_and_state(&tree, &name("pen")), (Role::Button, Some(Toggled::True))); assert_eq!(role_and_state(&tree, &name("selection")), (Role::Button, Some(Toggled::False))); - for label in ["Toggle single/double column", "Drag to float the toolbar", "Color (, or <)", "Gradient (. or >)", "None (/)"] { + for label in ["Toggle single/double column", "Drag to float the toolbar", "Color (, or Shift+,)", "Gradient (. or Shift+.)", "None (/)"] { assert_eq!(role_and_state(&tree, label), (Role::Button, None), "{label}"); } } From 9f644523030a1331c6ad34372e4ec62c04a3c959 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 19:35:32 -0700 Subject: [PATCH 038/260] Perspective Selection: Snap to Grid keeps a Shift-constrained move on its axis or diagonal perspective.move takes an optional constrain: [dx, dy], a plane-space direction. For an in-plane move, Snap to Grid's correction is projected onto that direction, so a move the Shift key constrains to a plane axis or a 45-degree diagonal stays on that line when an object edge lies near a gridline. The Perspective Selection tool sends the direction for Shift moves and copies. Moves without the param behave as before. --- crates/engine/src/cmd/distortcmds.rs | 2 +- .../engine/src/cmd/distortcmds/perspective.rs | 18 +++- crates/engine/src/tests/persp_select.rs | 83 +++++++++++++++++++ crates/tools/src/distort/perspective.rs | 6 ++ crates/tools/src/distort/perspective/tools.rs | 11 ++- docs/mcp.md | 4 +- 6 files changed, 117 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index 3da43957c8..e224692792 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> { "Move in Perspective", [], None, - "{ids?|id?, from: [x,y], to: [x,y], plane?, copy?: bool (move copies, as Alt-dragging does), perpendicular?: bool (move along the plane's normal instead, as pressing 5 while dragging does), snap?: bool (default: View › Perspective Grid › Snap to Grid)} slide objects within their plane (unattached objects attach to `plane`/the active plane first); snapping lands the nearer edge of the objects' joint bounds on a gridline within a quarter cell; Transform Again repeats it", + "{ids?|id?, from: [x,y], to: [x,y], plane?, copy?: bool (move copies, as Alt-dragging does), perpendicular?: bool (move along the plane's normal instead, as pressing 5 while dragging does), snap?: bool (default: View › Perspective Grid › Snap to Grid), constrain?: [dx,dy] (nonzero plane-space direction; keeps snap correction on that line for in-plane moves)} slide objects within their plane (unattached objects attach to `plane`/the active plane first); snapping pulls the nearer edge of the objects' joint bounds toward a gridline within a quarter cell, along `constrain` when supplied; Transform Again repeats it", has_doc, persp_move ), diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index 8481770274..023fa95c23 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -284,12 +284,28 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> { } let fallback = plane_param(&grid_of(&s.doc()?.doc), p, C).ok(); let (perp, copy) = (switch_or(p, "perpendicular", false, C)?, switch_or(p, "copy", false, C)?); + let constrain = match p.get("constrain").filter(|v| !v.is_null()) { + Some(v) => { + let direction = v.as_array().filter(|v| v.len() == 2).and_then(|v| Some((v.first()?.as_f64()?, v.get(1)?.as_f64()?))); + let (x, y) = direction.ok_or_else(|| bad(C, "constrain must be two finite numbers, not both zero"))?; + if !x.is_finite() || !y.is_finite() || (x == 0.0 && y == 0.0) { + return Err(bad(C, "constrain must be two finite numbers, not both zero")); + } + let scale = x.abs().max(y.abs()); + let (x, y) = (x / scale, y / scale); + let length = x.hypot(y); + Some(vectorcraft_geom::Vec2::new(x / length, y / length)) + } + None => None, + }; // `snap_fix` uses Snap to Grid's setting for a `snap` that is not true or false. check_switches(p, &["snap"], C)?; // Snap to Grid: a correction for the objects on the first one's plane and depth. let fix = if perp { None } else { crate::cmd::perspgrid::snap_fix(&s.doc()?.doc, &ids, p, (from, to)) }; let snapped = move |pl: Plane, depth: f64, dv: vectorcraft_geom::Vec2| { - dv + fix.filter(|f| f.0 == pl && f.1 == depth).map_or(vectorcraft_geom::Vec2::ZERO, |f| f.2) + dv + fix + .filter(|f| f.0 == pl && f.1 == depth) + .map_or(vectorcraft_geom::Vec2::ZERO, |f| constrain.map_or(f.2, |unit| unit * (f.2.x * unit.x + f.2.y * unit.y))) }; // In-plane: the plane-space offset under the pointer; perpendicular: the depth it reaches. let step = |g: &PerspectiveGrid, pl: Plane, depth: f64| -> Result<(Homography, f64)> { diff --git a/crates/engine/src/tests/persp_select.rs b/crates/engine/src/tests/persp_select.rs index a6f912b732..b3e8341f55 100644 --- a/crates/engine/src/tests/persp_select.rs +++ b/crates/engine/src/tests/persp_select.rs @@ -129,6 +129,89 @@ fn shift_drag_moves_on_a_plane_axis() { assert_eq!(plane_pts(&s, id, Plane::Right, 0.0), before); } +/// An attached rectangle with a horizontal edge close enough to a gridline to be pulled by snapping. +fn near_gridline_session() -> (Session, NodeId) { + let (mut s, id) = persp_session(); + let g = grid(&s); + let b = bounds_of(&plane_pts(&s, id, Plane::Right, 0.0)); + let dy = (b.y0 / g.cell).round() * g.cell + g.cell * 0.1 - b.y0; + let h = g.homography(Plane::Right).unwrap(); + let from = h.apply(b.center()).unwrap(); + let to = h.apply(b.center() + Vec2::new(0.0, dy)).unwrap(); + s.execute("perspective.move", &json!({"ids": [id.0], "from": [from.x, from.y], "to": [to.x, to.y], "snap": false})).unwrap(); + s.execute("perspective.grid.snap", &json!({"on": true})).unwrap(); + (s, id) +} + +fn shift_move_near_gridline(diagonal: bool, copy: bool) { + let (mut s, id) = near_gridline_session(); + s.select_tool("perspectiveSelection", ViewInfo::default()).unwrap(); + let before = plane_pts(&s, id, Plane::Right, 0.0); + let h = grid(&s).homography(Plane::Right).unwrap(); + let start = bounds_of(&before).center(); + let raw = if diagonal { Vec2::new(40.0, 50.0) } else { Vec2::new(80.0, 20.0) }; + let from = h.apply(start).unwrap(); + let to = h.apply(start + raw).unwrap(); + drag(&mut s, &[from, to, to], Mods { shift: true, alt: copy, ..Default::default() }); + let target = if copy { *s.doc().unwrap().selection.objects.first().unwrap() } else { id }; + assert!(!copy || target != id); + let after = plane_pts(&s, target, Plane::Right, 0.0); + for (a, b) in before.iter().zip(after) { + let d = b - *a; + if diagonal { + assert!((d.x - d.y).abs() < 1e-6, "diagonal move left its line: {d:?}"); + } else { + assert!(d.y.abs() < 1e-6, "axis move left its line: {d:?}"); + } + } + if copy { + assert_eq!(plane_pts(&s, id, Plane::Right, 0.0), before); + } +} + +#[test] +fn shift_axis_move_stays_on_axis_with_grid_snap() { + shift_move_near_gridline(false, false); +} + +#[test] +fn shift_axis_copy_stays_on_axis_with_grid_snap() { + shift_move_near_gridline(false, true); +} + +#[test] +fn shift_diagonal_move_stays_on_diagonal_with_grid_snap() { + shift_move_near_gridline(true, false); +} + +#[test] +fn shift_diagonal_copy_stays_on_diagonal_with_grid_snap() { + shift_move_near_gridline(true, true); +} + +#[test] +fn constrained_move_command_stays_on_axis_with_grid_snap() { + let (mut s, id) = near_gridline_session(); + let before = plane_pts(&s, id, Plane::Right, 0.0); + let h = grid(&s).homography(Plane::Right).unwrap(); + let start = bounds_of(&before).center(); + let from = h.apply(start).unwrap(); + let to = h.apply(start + Vec2::new(80.0, 0.0)).unwrap(); + s.execute("perspective.move", &json!({"ids": [id.0], "from": [from.x, from.y], "to": [to.x, to.y], "constrain": [1.0, 0.0]})).unwrap(); + for (a, b) in before.iter().zip(plane_pts(&s, id, Plane::Right, 0.0)) { + assert!((b.y - a.y).abs() < 1e-6, "constrained command left axis: {a:?} to {b:?}"); + } +} + +#[test] +fn constrained_move_rejects_invalid_direction() { + let (mut s, id) = near_gridline_session(); + for direction in [json!([0.0, 0.0]), json!([1.0]), json!([1.0, "bad"]), json!([null, 1.0])] { + let error = s.execute("perspective.move", &json!({"ids": [id.0], "from": [1.0, 1.0], "to": [2.0, 2.0], "constrain": direction})).unwrap_err(); + assert!(error.to_string().contains("constrain must be two finite numbers, not both zero"), "{error}"); + } +} + #[test] fn shift_drag_keeps_its_displacement_after_a_plane_key() { let (mut s, id) = persp_session(); diff --git a/crates/tools/src/distort/perspective.rs b/crates/tools/src/distort/perspective.rs index 2542e6a1a5..9052ecca40 100644 --- a/crates/tools/src/distort/perspective.rs +++ b/crates/tools/src/distort/perspective.rs @@ -1250,6 +1250,9 @@ mod tests { let endpoint = Point::new(v["to"][0].as_f64().unwrap(), v["to"][1].as_f64().unwrap()); let delta = hi.apply(endpoint).unwrap() - start; assert!((delta - expected).hypot() < 1e-6, "{plane:?}: {delta:?} != {expected:?}"); + let direction = expected / expected.hypot(); + let sent = Vec2::new(v["constrain"][0].as_f64().unwrap(), v["constrain"][1].as_f64().unwrap()); + assert!((sent - direction).hypot() < 1e-12, "{plane:?}: {sent:?} != {direction:?}"); } } } @@ -1276,16 +1279,19 @@ mod tests { t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(Mods { shift: true, alt: true, ..Default::default() })); let Some(Action::Preview(_, snapped)) = shifted.last() else { panic!("{shifted:?}") }; assert_eq!(snapped["copy"], json!(true)); + assert_eq!(snapped["constrain"], json!([1.0, 0.0])); assert_ne!(snapped["to"], raw["to"]); let perpendicular = t.key(&c, ToolKey::Digit(5), Mods { shift: true, alt: true, ..Default::default() }); let Some(Action::Preview(_, depth)) = perpendicular.last() else { panic!("{perpendicular:?}") }; assert_eq!(depth["to"], raw["to"]); + assert!(depth.get("constrain").is_none()); let in_plane = t.key(&c, ToolKey::Digit(5), Mods { shift: true, alt: true, ..Default::default() }); let Some(Action::Preview(_, snapped_again)) = in_plane.last() else { panic!("{in_plane:?}") }; assert_eq!(snapped_again["to"], snapped["to"]); let released = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); let Some(Action::Preview(_, raw_again)) = released.last() else { panic!("{released:?}") }; assert_eq!(raw_again["to"], raw["to"]); + assert!(raw_again.get("constrain").is_none()); } #[test] diff --git a/crates/tools/src/distort/perspective/tools.rs b/crates/tools/src/distort/perspective/tools.rs index 9e9454b304..d748cb51be 100644 --- a/crates/tools/src/distort/perspective/tools.rs +++ b/crates/tools/src/distort/perspective/tools.rs @@ -167,7 +167,7 @@ impl PerspectiveSelectionTool { let SelDrag::Move { ids, from, last, perp, copy, shift, .. } = &self.drag else { return None }; let g = PerspectiveGrid::current(cx.doc); let at = ids.first().and_then(|id| g.attachment_of(cx.doc, *id)).or((g.plane != Plane::None).then_some((g.plane, g.offset(g.plane)))); - let to = if *shift && !*perp { + let constrained = if *shift && !*perp { at.and_then(|(plane, depth)| { let h = g.homography_at(plane, depth)?; let hi = h.inverse()?; @@ -176,13 +176,16 @@ impl PerspectiveSelectionTool { let angle = (delta.y.atan2(delta.x) / std::f64::consts::FRAC_PI_4).round() * std::f64::consts::FRAC_PI_4; let direction = Vec2::new(angle.cos(), angle.sin()); let distance = delta.x * direction.x + delta.y * direction.y; - h.apply(start + direction * distance).filter(|p| p.x.is_finite() && p.y.is_finite()) + h.apply(start + direction * distance).filter(|p| p.x.is_finite() && p.y.is_finite()).map(|to| (to, direction)) }) - .unwrap_or(*last) } else { - *last + None }; + let to = if let Some((to, _)) = constrained { to } else { *last }; let mut v = json!({"ids": crate::json_ids(ids), "from": [from.x, from.y], "to": [to.x, to.y], "copy": copy, "perpendicular": perp}); + if let Some((_, direction)) = constrained { + v["constrain"] = json!([direction.x, direction.y]); + } if g.plane != Plane::None { v["plane"] = json!(g.plane.id()); } diff --git a/docs/mcp.md b/docs/mcp.md index add4788c4a..164320533f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5477,7 +5477,9 @@ distance along the plane's normal), so copies, duplicates and pastes stay attach `perspectiveSelection` tool, a drag moves the selection within its plane (`perspective.move`; Alt copies), the bounding-box handles scale it in plane space (`perspective.transform`; Shift keeps proportions, Alt scales about the centre), and `press_key` `5` during a drag switches the move to perpendicular to the plane (press again to switch -back). `press_key` Escape during a move, a resize or a plane widget drag cancels it and puts the objects and the +back). Holding Shift during an in-plane move constrains the displacement to a plane axis or 45° diagonal; `perspective.move` +passes that plane-space direction as `constrain: [dx, dy]`, so Snap to Grid adjusts the move only along that line. +`press_key` Escape during a move, a resize or a plane widget drag cancels it and puts the objects and the grid back. The arrow keys nudge a selection in perspective by the keyboard increment (`perspective.nudge`; Shift ×10, Alt copies). Object › Transform › Transform Again repeats the last perspective move or scale in plane space. From 375b413ba6aa3d27fdef6f95346072f28940be20 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 23:46:02 -0700 Subject: [PATCH 039/260] Perspective: a projection that a transform overflows keeps a w row of 1 When conjugating a projection overflows, the scaled-down result is now divided by the largest entry in its w row. A valid conjugate is no longer dropped by the determinant cutoff at the arbitrary scale, and every point of a kept projection passes the horizon test in apply instead of none. --- crates/geom/src/projective.rs | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/crates/geom/src/projective.rs b/crates/geom/src/projective.rs index e7754c1312..94831fb5cb 100644 --- a/crates/geom/src/projective.rs +++ b/crates/geom/src/projective.rs @@ -101,8 +101,10 @@ impl Homography { /// `self` seen through `a`: the map `a ∘ self ∘ a⁻¹` (what `self` becomes when everything it /// maps from and to is moved by `a`). When the product overflows, it is formed from factors - /// scaled to a largest entry of 1 and returned at that scale (the same map). `None` when `a` - /// isn't invertible, or when the product overflows and the scaled result is not invertible. + /// scaled to a largest entry of 1 and returned divided by the largest magnitude in its `w` row + /// (the same map, with a `w` row whose largest entry is 1). `None` when `a` isn't invertible, + /// or when the product overflows and the result at that scale has an entry that is not finite + /// or is not invertible. pub fn conjugated(&self, a: Affine) -> Option<Self> { if a.determinant().abs() < 1e-15 { return None; @@ -113,7 +115,12 @@ impl Homography { return Some(c); } let c = to.normalized()?.then_after(&self.normalized()?).then_after(&from.normalized()?).normalized()?; - (c.det().abs() > 1e-15).then_some(c) + let k = c.0[2].iter().fold(0.0_f64, |k, v| k.max(v.abs())); + if k <= 0.0 { + return None; + } + let c = Self(c.0.map(|row| row.map(|v| v / k))); + (c.is_finite() && c.det().abs() > 1e-15).then_some(c) } fn is_finite(&self) -> bool { @@ -237,12 +244,29 @@ mod tests { let big = Homography([[1e307, 0.0, 1e308], [0.0, 1e307, 0.0], [0.0, 0.0, 1e307]]); let t = Affine::scale(10.0); let c = big.conjugated(t).unwrap(); - assert!(c.0.iter().flatten().all(|v| v.is_finite() && v.abs() <= 1.0)); + assert!(c.is_finite()); + assert_eq!(c.0[2], [0.0, 0.0, 1.0]); assert_eq!(Homography::from_array(c.to_array()), Some(c)); for p in [Point::new(3.0, 7.0), Point::new(-4.0, 1.5)] { assert!(c.apply(t * p).unwrap().distance(t * big.apply(p).unwrap()) < 1e-9); assert!(c.apply(p).unwrap().distance(p + kurbo::Vec2::new(100.0, 0.0)) < 1e-9); } + // A move by 1 scaled by 1e307, seen through a scale by 1e7: a move by 1e7, whose + // determinant is 1 at a w row of 1 but 1e-21 at a largest entry of 1. + let one = Homography([[1e307, 0.0, 1e307], [0.0, 1e307, 0.0], [0.0, 0.0, 1e307]]); + assert!(Homography::from_array(one.to_array()).is_some()); + let c = one.conjugated(Affine::scale(1e7)).unwrap(); + assert_eq!(Homography::from_array(c.to_array()), Some(c)); + let p = Point::new(3.0, -2.0); + assert!(c.apply(p).unwrap().distance(p + kurbo::Vec2::new(1e7, 0.0)) < 1e-6); + // A scale by 1e10 seen through a scale by 1e10: still a scale by 1e10, which every point + // reaches only when w is not left at 1e-10. + let wide = Homography([[1e300, 0.0, 0.0], [0.0, 1e300, 0.0], [0.0, 0.0, 1e290]]); + let c = wide.conjugated(Affine::scale(1e10)).unwrap(); + assert_eq!(Homography::from_array(c.to_array()), Some(c)); + for p in [Point::new(1.0, 2.0), Point::new(-5.0, 0.5)] { + assert!(c.apply(p).unwrap().distance(Point::new(p.x * 1e10, p.y * 1e10)) < 1e-3); + } // A move by 1e200 seen through a scale by 1e150 sends every point to about (1e350, 0), // which no invertible map of finite numbers draws. let far = Homography([[1.0, 0.0, 1e200], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]); From 64c776af4c898c2f19411966f2d0d931e2133d10 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 16:07:18 -0700 Subject: [PATCH 040/260] Shortcuts: a bound layout candidate for Shift+Period or Shift+Comma wins over the key position --- crates/ui-egui/src/shortcuts.rs | 16 ++++++++++------ crates/ui-egui/src/shortcuts/tests.rs | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 8b8355b074..8425456b99 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -731,9 +731,10 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, accept: impl FnMut(&H let mirror = crate::shortcut_editor::current(); let dispatcher = &mut app.dispatcher; ctx.input_mut(|i| { - // Shift+Comma and Shift+Period follow their key positions when the logical character - // differs. An explicitly bound logical shifted chord takes precedence. + // Shift+Comma and Shift+Period follow their key positions when no chord for the + // logical press is bound. An explicit shifted logical binding takes precedence. for e in &mut i.events { + let input = craft_keymap::KeyInput::from_egui(e, crate::keymap::platform()); if let egui::Event::Key { key, physical_key: Some(physical), modifiers, pressed: true, .. } = e && modifiers.shift && !modifiers.command @@ -743,14 +744,17 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, accept: impl FnMut(&H && matches!(*physical, Key::Comma | Key::Period) && *key != *physical && let (Some(logical), Some(position)) = (craft_keymap::Key::from_egui(*key), craft_keymap::Key::from_egui(*physical)) + && let Some(input) = input { let mods = craft_keymap::Mods::from_egui(modifiers, crate::keymap::platform()); let logical_chord = craft_keymap::Chord::new(mods, logical); let position_chord = craft_keymap::Chord::new(mods, position); - if crate::keymap::lookup(&mirror.keymap, &logical_chord).is_some() { - *physical = *key; - } else if crate::keymap::lookup(&mirror.keymap, &position_chord).is_some() { - *key = *physical; + if !dispatcher.layout().candidates(&input).iter().any(|chord| crate::keymap::lookup(&mirror.keymap, chord).is_some()) { + if crate::keymap::lookup(&mirror.keymap, &logical_chord).is_some() { + *physical = *key; + } else if crate::keymap::lookup(&mirror.keymap, &position_chord).is_some() { + *key = *physical; + } } } } diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 56e552b316..ceb68108c7 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1232,6 +1232,25 @@ fn explicit_logical_shifted_binding_wins_over_position_alias() { assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); } +#[test] +fn resolved_logical_binding_wins_over_position_alias() { + for chord in [":", "Shift+;"] { + let mut app = remembered_paint_app(); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "view.grid", chord); + let journal_before = app.session.journal.len(); + frame( + &mut app, + vec![ + egui::Event::ModifiersChanged(Modifiers::SHIFT), + egui::Event::Key { key: Key::Colon, physical_key: Some(Key::Period), pressed: true, repeat: false, modifiers: Modifiers::SHIFT }, + egui::Event::Text(":".into()), + ], + ); + assert!(app.ui.view.grid, "{chord} runs Show Grid"); + assert!(app.session.journal.since(journal_before).iter().all(|(command, _)| !command.starts_with("paint.")), "{chord} runs no paint command"); + } +} + #[test] fn user_shifted_punctuation_binding_runs_once() { let mut app = remembered_paint_app(); From c15874ba6eb7135e9c92aea6123d194eef92a1e6 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 19:58:33 -0700 Subject: [PATCH 041/260] Perspective Selection: Shift constrains each object in its own plane perspective.move takes constrain: true instead of a plane-space direction. For each object, the command snaps the move to the nearest axis or 45-degree diagonal of that object's own plane, so a selection on several planes keeps every object on a line of its plane. The tool sends the raw pointer with the flag. On a diagonal, Snap to Grid now moves along the diagonal by the nearer per-axis correction, so that edge lands on its gridline. --- crates/engine/src/cmd/distortcmds.rs | 2 +- .../engine/src/cmd/distortcmds/perspective.rs | 52 ++++++++++------- crates/engine/src/tests/persp_select.rs | 57 +++++++++++++++++-- crates/tools/src/distort/perspective.rs | 43 +++++++++++--- crates/tools/src/distort/perspective/tools.rs | 23 +++----- docs/mcp.md | 5 +- docs/target-app-parity.md | 2 +- 7 files changed, 135 insertions(+), 49 deletions(-) diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index e224692792..7a0643ca51 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> { "Move in Perspective", [], None, - "{ids?|id?, from: [x,y], to: [x,y], plane?, copy?: bool (move copies, as Alt-dragging does), perpendicular?: bool (move along the plane's normal instead, as pressing 5 while dragging does), snap?: bool (default: View › Perspective Grid › Snap to Grid), constrain?: [dx,dy] (nonzero plane-space direction; keeps snap correction on that line for in-plane moves)} slide objects within their plane (unattached objects attach to `plane`/the active plane first); snapping pulls the nearer edge of the objects' joint bounds toward a gridline within a quarter cell, along `constrain` when supplied; Transform Again repeats it", + "{ids?|id?, from: [x,y], to: [x,y], plane?, copy?: bool (move copies, as Alt-dragging does), perpendicular?: bool (move along the plane's normal instead, as pressing 5 while dragging does), snap?: bool (default: View › Perspective Grid › Snap to Grid), constrain?: bool (default false; constrain each in-plane move to its plane's nearest axis or 45° diagonal)} slide objects within their own planes (unattached objects attach to `plane`/the active plane first); snapping pulls the nearer edge of the first plane's joint bounds toward a gridline within a quarter cell while preserving the constrained direction; Transform Again repeats it", has_doc, persp_move ), diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index 023fa95c23..54cac360d5 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -284,28 +284,42 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> { } let fallback = plane_param(&grid_of(&s.doc()?.doc), p, C).ok(); let (perp, copy) = (switch_or(p, "perpendicular", false, C)?, switch_or(p, "copy", false, C)?); - let constrain = match p.get("constrain").filter(|v| !v.is_null()) { - Some(v) => { - let direction = v.as_array().filter(|v| v.len() == 2).and_then(|v| Some((v.first()?.as_f64()?, v.get(1)?.as_f64()?))); - let (x, y) = direction.ok_or_else(|| bad(C, "constrain must be two finite numbers, not both zero"))?; - if !x.is_finite() || !y.is_finite() || (x == 0.0 && y == 0.0) { - return Err(bad(C, "constrain must be two finite numbers, not both zero")); - } - let scale = x.abs().max(y.abs()); - let (x, y) = (x / scale, y / scale); - let length = x.hypot(y); - Some(vectorcraft_geom::Vec2::new(x / length, y / length)) - } - None => None, - }; + let constrain = switch_or(p, "constrain", false, C)?; // `snap_fix` uses Snap to Grid's setting for a `snap` that is not true or false. check_switches(p, &["snap"], C)?; // Snap to Grid: a correction for the objects on the first one's plane and depth. - let fix = if perp { None } else { crate::cmd::perspgrid::snap_fix(&s.doc()?.doc, &ids, p, (from, to)) }; - let snapped = move |pl: Plane, depth: f64, dv: vectorcraft_geom::Vec2| { - dv + fix - .filter(|f| f.0 == pl && f.1 == depth) - .map_or(vectorcraft_geom::Vec2::ZERO, |f| constrain.map_or(f.2, |unit| unit * (f.2.x * unit.x + f.2.y * unit.y))) + let snap_to = if constrain && !perp { + let doc = &s.doc()?.doc; + let g = grid_of(doc); + g.plane_bounds(doc, &ids) + .and_then(|(plane, depth, _)| { + let h = g.homography_at(plane, depth)?; + let start = h.inverse()?.apply(from)?; + let delta = g.plane_delta(plane, depth, from, to)?; + h.apply(start + vectorcraft_tools::distort::perspective::constrain_move_delta(delta).1) + }) + .unwrap_or(to) + } else { + to + }; + let fix = if perp { None } else { crate::cmd::perspgrid::snap_fix(&s.doc()?.doc, &ids, p, (from, snap_to)) }; + let snapped = move |pl: Plane, depth: f64, raw: vectorcraft_geom::Vec2| { + let (direction, dv) = + if constrain { vectorcraft_tools::distort::perspective::constrain_move_delta(raw) } else { (vectorcraft_geom::Vec2::ZERO, raw) }; + dv + fix.filter(|f| f.0 == pl && f.1 == depth).map_or(vectorcraft_geom::Vec2::ZERO, |f| { + if !constrain { + return f.2; + } + if direction.x.abs() < 1e-12 { + return vectorcraft_geom::Vec2::new(0.0, f.2.y); + } + if direction.y.abs() < 1e-12 { + return vectorcraft_geom::Vec2::new(f.2.x, 0.0); + } + let (correction, axis) = + if f.2.x == 0.0 || (f.2.y != 0.0 && f.2.y.abs() < f.2.x.abs()) { (f.2.y, direction.y) } else { (f.2.x, direction.x) }; + direction * (correction / axis) + }) }; // In-plane: the plane-space offset under the pointer; perpendicular: the depth it reaches. let step = |g: &PerspectiveGrid, pl: Plane, depth: f64| -> Result<(Homography, f64)> { diff --git a/crates/engine/src/tests/persp_select.rs b/crates/engine/src/tests/persp_select.rs index b3e8341f55..c590aee5b7 100644 --- a/crates/engine/src/tests/persp_select.rs +++ b/crates/engine/src/tests/persp_select.rs @@ -197,18 +197,67 @@ fn constrained_move_command_stays_on_axis_with_grid_snap() { let start = bounds_of(&before).center(); let from = h.apply(start).unwrap(); let to = h.apply(start + Vec2::new(80.0, 0.0)).unwrap(); - s.execute("perspective.move", &json!({"ids": [id.0], "from": [from.x, from.y], "to": [to.x, to.y], "constrain": [1.0, 0.0]})).unwrap(); + s.execute("perspective.move", &json!({"ids": [id.0], "from": [from.x, from.y], "to": [to.x, to.y], "constrain": true})).unwrap(); for (a, b) in before.iter().zip(plane_pts(&s, id, Plane::Right, 0.0)) { assert!((b.y - a.y).abs() < 1e-6, "constrained command left axis: {a:?} to {b:?}"); } } #[test] -fn constrained_move_rejects_invalid_direction() { +fn diagonal_shift_snap_lands_an_edge_on_a_gridline() { let (mut s, id) = near_gridline_session(); - for direction in [json!([0.0, 0.0]), json!([1.0]), json!([1.0, "bad"]), json!([null, 1.0])] { + let g = grid(&s); + let before = plane_pts(&s, id, Plane::Right, 0.0); + let b = bounds_of(&before); + let (raw, correction) = (1..200) + .map(|n| { + let raw = Vec2::new(n as f64 * g.cell * 0.05, n as f64 * g.cell * 0.05); + (raw, g.snap_offset(b, raw) - raw) + }) + .find(|(_, fix)| fix.x.abs() < 1e-9 && fix.y.abs() > 1e-6) + .unwrap(); + let h = g.homography(Plane::Right).unwrap(); + let start = b.center(); + let from = h.apply(start).unwrap(); + let to = h.apply(start + raw).unwrap(); + s.execute("perspective.move", &json!({"ids": [id.0], "from": [from.x, from.y], "to": [to.x, to.y], "constrain": true})).unwrap(); + let after = plane_pts(&s, id, Plane::Right, 0.0); + let delta = after[0] - before[0]; + assert!((delta.x - delta.y).abs() < 1e-6, "{delta:?}"); + let edge = [b.y0 + delta.y, b.y1 + delta.y]; + assert!(edge.iter().any(|y| ((y / g.cell).round() * g.cell - y).abs() < 1e-6), "{edge:?}, correction {correction:?}"); +} + +#[test] +fn constrained_move_uses_each_objects_plane() { + let (mut s, right) = persp_session(); + let left_result = s.execute("shape.rectangle", &json!({"x": 240, "y": 380, "width": 60, "height": 60})).unwrap(); + let left = NodeId(left_result["id"].as_u64().unwrap()); + s.execute("perspective.attach", &json!({"ids": [left.0], "plane": "left"})).unwrap(); + let right_before = plane_pts(&s, right, Plane::Right, 0.0); + let left_before = plane_pts(&s, left, Plane::Left, 0.0); + let from = grid(&s).homography(Plane::Right).unwrap().apply(bounds_of(&right_before).center()).unwrap(); + let to = from + Vec2::new(70.0, 30.0); + let g = grid(&s); + for plane in [Plane::Right, Plane::Left] { + let raw = g.plane_delta(plane, 0.0, from, to).unwrap(); + assert!(raw.x.abs() > 1e-3 && raw.y.abs() > 1e-3 && (raw.x.abs() - raw.y.abs()).abs() > 1e-3, "raw {plane:?}: {raw:?}"); + } + s.execute("perspective.move", &json!({"ids": [right.0, left.0], "from": [from.x, from.y], "to": [to.x, to.y], "constrain": true, "snap": false})) + .unwrap(); + for (id, plane, before) in [(right, Plane::Right, right_before), (left, Plane::Left, left_before)] { + let after = plane_pts(&s, id, plane, 0.0); + let delta = after[0] - before[0]; + assert!(delta.x.abs() < 1e-6 || delta.y.abs() < 1e-6 || (delta.x.abs() - delta.y.abs()).abs() < 1e-6, "{plane:?}: {delta:?}"); + } +} + +#[test] +fn constrained_move_rejects_non_boolean_switch() { + let (mut s, id) = near_gridline_session(); + for direction in [json!([0.0, 0.0]), json!([1.0]), json!(1), json!("true")] { let error = s.execute("perspective.move", &json!({"ids": [id.0], "from": [1.0, 1.0], "to": [2.0, 2.0], "constrain": direction})).unwrap_err(); - assert!(error.to_string().contains("constrain must be two finite numbers, not both zero"), "{error}"); + assert!(error.to_string().contains("`constrain` must be true or false"), "{error}"); } } diff --git a/crates/tools/src/distort/perspective.rs b/crates/tools/src/distort/perspective.rs index 9052ecca40..d535b5cd2a 100644 --- a/crates/tools/src/distort/perspective.rs +++ b/crates/tools/src/distort/perspective.rs @@ -74,6 +74,14 @@ impl Plane { pub const ALL: [Plane; 3] = [Plane::Left, Plane::Right, Plane::Ground]; } +/// Return the nearest 45-degree direction of `delta` in plane space, counted from the plane's x axis, +/// and `delta` projected onto that direction. +pub fn constrain_move_delta(delta: Vec2) -> (Vec2, Vec2) { + let angle = (delta.y.atan2(delta.x) / std::f64::consts::FRAC_PI_4).round() * std::f64::consts::FRAC_PI_4; + let direction = Vec2::new(angle.cos(), angle.sin()); + (direction, direction * (delta.x * direction.x + delta.y * direction.y)) +} + /// Plane Switching widget: (plane, face quad) list and the "no plane" circle (centre, radius). pub type WidgetGeom = (Vec<(Plane, [Point; 4])>, (Point, f64)); @@ -1247,16 +1255,37 @@ mod tests { let acts = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(Mods { shift: true, ..Default::default() })); let Some(Action::Preview(cmd, v)) = acts.last() else { panic!("{acts:?}") }; assert_eq!(cmd, "perspective.move"); - let endpoint = Point::new(v["to"][0].as_f64().unwrap(), v["to"][1].as_f64().unwrap()); - let delta = hi.apply(endpoint).unwrap() - start; + assert_eq!(v["to"], json!([to.x, to.y])); + let raw_delta = hi.apply(to).unwrap() - start; + let delta = constrain_move_delta(raw_delta).1; assert!((delta - expected).hypot() < 1e-6, "{plane:?}: {delta:?} != {expected:?}"); - let direction = expected / expected.hypot(); - let sent = Vec2::new(v["constrain"][0].as_f64().unwrap(), v["constrain"][1].as_f64().unwrap()); - assert!((sent - direction).hypot() < 1e-12, "{plane:?}: {sent:?} != {direction:?}"); + assert_eq!(v["constrain"], json!(true)); } } } + #[test] + fn selection_shift_preview_sends_raw_pointer_and_boolean_constraint() { + let (mut d, id) = doc_with_rect(); + grid(2).store(&mut d); + set_attachment(d.node_mut(id).unwrap(), Plane::Right, 0.0); + let mut selection = Selection::default(); + selection.add(id); + let p = paint(); + let c = cx(&d, &selection, &p); + let h = PerspectiveGrid::current(&d).homography(Plane::Right).unwrap(); + let from = d.node(id).unwrap().geometric_bounds().unwrap().center(); + let start = h.inverse().unwrap().apply(from).unwrap(); + let to = h.apply(start + Vec2::new(60.0, 12.0)).unwrap(); + let mut tool = PerspectiveSelectionTool::default(); + tool.pointer(&c, &PointerEvent::new(PointerKind::Down, from.x, from.y)); + let actions = tool.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(Mods { shift: true, ..Default::default() })); + let Some(Action::Preview(command, params)) = actions.last() else { panic!("{actions:?}") }; + assert_eq!(command, "perspective.move"); + assert_eq!(params["to"], json!([to.x, to.y])); + assert_eq!(params["constrain"], json!(true)); + } + #[test] fn selection_move_recomputes_shift_copy_and_perpendicular() { let (mut d, id) = doc_with_rect(); @@ -1279,8 +1308,8 @@ mod tests { t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(Mods { shift: true, alt: true, ..Default::default() })); let Some(Action::Preview(_, snapped)) = shifted.last() else { panic!("{shifted:?}") }; assert_eq!(snapped["copy"], json!(true)); - assert_eq!(snapped["constrain"], json!([1.0, 0.0])); - assert_ne!(snapped["to"], raw["to"]); + assert_eq!(snapped["constrain"], json!(true)); + assert_eq!(snapped["to"], raw["to"]); let perpendicular = t.key(&c, ToolKey::Digit(5), Mods { shift: true, alt: true, ..Default::default() }); let Some(Action::Preview(_, depth)) = perpendicular.last() else { panic!("{perpendicular:?}") }; assert_eq!(depth["to"], raw["to"]); diff --git a/crates/tools/src/distort/perspective/tools.rs b/crates/tools/src/distort/perspective/tools.rs index d748cb51be..e791f4ef33 100644 --- a/crates/tools/src/distort/perspective/tools.rs +++ b/crates/tools/src/distort/perspective/tools.rs @@ -169,34 +169,27 @@ impl PerspectiveSelectionTool { let at = ids.first().and_then(|id| g.attachment_of(cx.doc, *id)).or((g.plane != Plane::None).then_some((g.plane, g.offset(g.plane)))); let constrained = if *shift && !*perp { at.and_then(|(plane, depth)| { - let h = g.homography_at(plane, depth)?; - let hi = h.inverse()?; - let start = hi.apply(*from)?; - let delta = hi.apply(*last)? - start; - let angle = (delta.y.atan2(delta.x) / std::f64::consts::FRAC_PI_4).round() * std::f64::consts::FRAC_PI_4; - let direction = Vec2::new(angle.cos(), angle.sin()); - let distance = delta.x * direction.x + delta.y * direction.y; - h.apply(start + direction * distance).filter(|p| p.x.is_finite() && p.y.is_finite()).map(|to| (to, direction)) + let delta = g.plane_delta(plane, depth, *from, *last)?; + Some(super::constrain_move_delta(delta).1) }) } else { None }; - let to = if let Some((to, _)) = constrained { to } else { *last }; - let mut v = json!({"ids": crate::json_ids(ids), "from": [from.x, from.y], "to": [to.x, to.y], "copy": copy, "perpendicular": perp}); - if let Some((_, direction)) = constrained { - v["constrain"] = json!([direction.x, direction.y]); + let mut v = json!({"ids": crate::json_ids(ids), "from": [from.x, from.y], "to": [last.x, last.y], "copy": copy, "perpendicular": perp}); + if *shift && !*perp { + v["constrain"] = json!(true); } if g.plane != Plane::None { v["plane"] = json!(g.plane.id()); } self.measure = at.and_then(|(pl, depth)| { let text = if *perp { - format!("dZ: {}", cx.len(g.depth_at(pl, depth, *from, to)? - depth)) + format!("dZ: {}", cx.len(g.depth_at(pl, depth, *from, *last)? - depth)) } else { - let d = g.plane_delta(pl, depth, *from, to)?; + let d = constrained.unwrap_or(g.plane_delta(pl, depth, *from, *last)?); cx.offset_label(d.x, d.y) }; - Some((to, text)) + Some((*last, text)) }); Some(Action::Preview("perspective.move".into(), v)) } diff --git a/docs/mcp.md b/docs/mcp.md index 164320533f..81681d6c2f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5477,8 +5477,9 @@ distance along the plane's normal), so copies, duplicates and pastes stay attach `perspectiveSelection` tool, a drag moves the selection within its plane (`perspective.move`; Alt copies), the bounding-box handles scale it in plane space (`perspective.transform`; Shift keeps proportions, Alt scales about the centre), and `press_key` `5` during a drag switches the move to perpendicular to the plane (press again to switch -back). Holding Shift during an in-plane move constrains the displacement to a plane axis or 45° diagonal; `perspective.move` -passes that plane-space direction as `constrain: [dx, dy]`, so Snap to Grid adjusts the move only along that line. +back). Holding Shift during an in-plane move constrains each object's displacement to an axis or 45° diagonal of its +own plane. `perspective.move` accepts `constrain: true` (default false) and adjusts Snap to Grid along the constrained +direction on the first object's plane and depth. `press_key` Escape during a move, a resize or a plane widget drag cancels it and puts the objects and the grid back. The arrow keys nudge a selection in perspective by the keyboard increment (`perspective.nudge`; Shift ×10, Alt copies). Object › Transform › Transform Again repeats the last perspective move or scale in plane space. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 51c0373344..2f6ee32b76 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1104,7 +1104,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur An Alt-drag with the Selection, Direct Selection, Group Selection, Rotate, Scale, Reflect or Shear tool copies the selection on its first move, and the moves after it transform those copies; the previews of the Move, Rotate, Scale, Reflect and Shear dialogs with Copy and Preview on copy the selection once in the same way (#1429). An Alt-drag of objects in perspective with the Perspective Selection tool, and an Alt-drag of a plane widget with that tool or the Perspective Grid tool, copy the objects on the first move, and the moves after it move those copies (#1429). With the Perspective Selection tool, Ctrl+Alt-drag (Command+Option-drag on macOS) also copies objects on their perspective plane; Alt/Option-drag continues to do so. - With the Perspective Selection tool, holding Shift while moving or copying on a plane constrains the displacement to the nearest plane axis or 45° diagonal; releasing Shift resumes the raw pointer position, and 5 still moves perpendicular to the plane. + With the Perspective Selection tool, holding Shift while moving or copying constrains each object's displacement to the nearest axis or 45° diagonal of its own plane; releasing Shift resumes the raw pointer position, and 5 still moves perpendicular to the plane. Snap to Grid follows the constrained line on the first object's plane and depth. When the desktop app opens a document on a thread of its own (#1245), that thread also reads the document's linked files and lays out its type, and the UI thread only adds the finished document: in release builds, the step left on the UI thread takes 0.02 ms instead of 1.04 s for a document with 12 linked 3000 × 2000 TIFFs, and it takes 0.1 ms instead of 0.85 s for one with 300 Auto Size area type objects, every second one in three columns. The Layers panel's Delete Selection, Duplicate Selection, Collect in New Layer, Merge Selected, Flatten Artwork, Release to Layers (Sequence) and row drags also take time in proportion to the size of the document, and so do Cut Artboard and Duplicate Artboard with their art and each move of an Alt-drag of one artboard with the Artboard tool while Move/Copy Artwork with Artboard is on (#1429). In Outline view the renderer draws paths and compound paths from the geometry it keeps for them between frames, and it culls the members of clip groups by the bounds it keeps for them. Layers with Preview off and the outlines of Image Trace objects are drawn the same way. From c711ad42f0f2372a5bb5ad5d8783c235493a412f Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 23:52:44 -0700 Subject: [PATCH 042/260] Perspective: a transform's overflow fallback scales each partial product When the conjugate of a projection overflows, it is now formed one factor at a time, and each partial product is divided by its largest entry magnitude. Scaling the affine factors up front let the w row underflow to 0, so a scale by 2 seen through a move by 1e308 returned None and the projection was removed, though its conjugate is finite. --- crates/geom/src/projective.rs | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/crates/geom/src/projective.rs b/crates/geom/src/projective.rs index 94831fb5cb..4b17aac60d 100644 --- a/crates/geom/src/projective.rs +++ b/crates/geom/src/projective.rs @@ -100,11 +100,11 @@ impl Homography { } /// `self` seen through `a`: the map `a ∘ self ∘ a⁻¹` (what `self` becomes when everything it - /// maps from and to is moved by `a`). When the product overflows, it is formed from factors - /// scaled to a largest entry of 1 and returned divided by the largest magnitude in its `w` row - /// (the same map, with a `w` row whose largest entry is 1). `None` when `a` isn't invertible, - /// or when the product overflows and the result at that scale has an entry that is not finite - /// or is not invertible. + /// maps from and to is moved by `a`). When the product overflows, it is formed one factor at a + /// time, each partial product scaled to a largest entry of 1, and returned divided by the + /// largest magnitude in its `w` row (the same map, with a `w` row whose largest entry is 1). + /// `None` when `a` isn't invertible, or when the product overflows and the result at that + /// scale has an entry that is not finite or is not invertible. pub fn conjugated(&self, a: Affine) -> Option<Self> { if a.determinant().abs() < 1e-15 { return None; @@ -114,7 +114,7 @@ impl Homography { if c.is_finite() { return Some(c); } - let c = to.normalized()?.then_after(&self.normalized()?).then_after(&from.normalized()?).normalized()?; + let c = to.then_after_normalized(&self.normalized()?)?.then_after_normalized(&from)?; let k = c.0[2].iter().fold(0.0_f64, |k, v| k.max(v.abs())); if k <= 0.0 { return None; @@ -134,6 +134,17 @@ impl Homography { (self.is_finite() && k > 0.0).then(|| Self(self.0.map(|row| row.map(|v| v / k)))) } + /// `self ∘ other` divided by its largest entry magnitude; when that product overflows, it is + /// formed from both factors divided by their largest entry magnitudes. `None` when the result + /// has an entry that is not finite or every entry is 0. + fn then_after_normalized(&self, other: &Self) -> Option<Self> { + let c = self.then_after(other); + if c.is_finite() { + return c.normalized(); + } + self.normalized()?.then_after(&other.normalized()?).normalized() + } + /// The affine map that matches `self` to first order at `p` (its derivative there), `None` /// beyond the horizon or when the derivative is not finite. pub fn affine_at(&self, p: Point) -> Option<Affine> { @@ -267,6 +278,16 @@ mod tests { for p in [Point::new(1.0, 2.0), Point::new(-5.0, 0.5)] { assert!(c.apply(p).unwrap().distance(Point::new(p.x * 1e10, p.y * 1e10)) < 1e-3); } + // A scale by 2 seen through a move by 1e308: p goes to 2p - 1e308, though the product's + // corner entry is 2 * -1e308 + 1e308 and the moves scaled to a largest entry of 1 leave + // their w rows at 1e-308. + let two = Homography([[2.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 1.0]]); + let c = two.conjugated(Affine::translate((1e308, 0.0))).unwrap(); + let want = [2.0, 0.0, -1e308, 0.0, 2.0, 0.0, 0.0, 0.0, 1.0]; + for (v, w) in c.to_array().iter().zip(want) { + assert!((v - w).abs() <= 1e-9 * w.abs().max(1.0), "{c:?}"); + } + assert_eq!(Homography::from_array(c.to_array()), Some(c)); // A move by 1e200 seen through a scale by 1e150 sends every point to about (1e350, 0), // which no invertible map of finite numbers draws. let far = Homography([[1.0, 0.0, 1e200], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]); From 26173437b945f230c8bf45df04e14a2545387acb Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 17:17:05 -0700 Subject: [PATCH 043/260] i18n: Bosnian paint-chip tips name Shift+, and Shift+. The Bosnian catalog still carried the Color (,) and Gradient (.) rows, which no longer match the toolbar's tips. It now translates Color (, or Shift+,) and Gradient (. or Shift+.) like the other catalogs. --- crates/ui-egui/src/i18n/bs.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index bf9005f9a0..17de837b8e 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1188,12 +1188,12 @@ lighting Light Svjetlo to set spacing and orientation za postavljanje razmaka i orijentacije Apply Primijeni Change Screen Mode (F) Promijeni način prikaza ekrana (F) - Color (,) Boja (,) + Color (, or Shift+,) Boja (, ili Shift+,) Draw Behind Crtaj iza Draw Inside Crtaj unutra Draw Normal Crtaj normalno Expand: Proširi: - Gradient (.) Gradijent (.) + Gradient (. or Shift+.) Gradijent (. ili Shift+.) H: V: Modify Izmijeni Navigate Navigacija From 9259434a89b7384b40b1345609ea51d43cd095d9 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sat, 31 Oct 2026 06:20:00 +0300 Subject: [PATCH 044/260] SVG export: a gradient mesh patch is cut no finer than its colour changes Each patch of a gradient mesh was cut into 8 x 8 flat quads for SVG export, Object > Expand and the other outputs that cannot shade a mesh, whatever its colours, so a patch of one colour became 64 identical pieces. Neighbouring quads are now joined into square blocks wherever the colour changes by no more than about one 8-bit step across the block; the block's outline runs through its quads' corners, and a patch that folds over itself is not joined. --- crates/doc/src/live.rs | 2 +- crates/doc/src/live/expand.rs | 5 +- crates/doc/src/live/mesh.rs | 108 +++++++++++++++++++++++++++ crates/engine/src/tests/live.rs | 12 ++- crates/svg/tests/it/main.rs | 1 + crates/svg/tests/it/mesh_export.rs | 116 +++++++++++++++++++++++++++++ docs/file-format-parity.md | 3 +- 7 files changed, 240 insertions(+), 7 deletions(-) create mode 100644 crates/svg/tests/it/mesh_export.rs diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 258035c10f..102a614b93 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -63,7 +63,7 @@ pub use expand::{ }; #[cfg(test)] use mesh::grid_eval; -pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds}; +pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds}; pub use warp::{WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, pieces, warp_point}; #[cfg(test)] diff --git a/crates/doc/src/live/expand.rs b/crates/doc/src/live/expand.rs index c67dbee3ee..66d20f27b6 100644 --- a/crates/doc/src/live/expand.rs +++ b/crates/doc/src/live/expand.rs @@ -293,9 +293,10 @@ pub fn is_live(n: &Node) -> bool { ) } -/// Mesh tessellation as filled quad paths (no stroke), `n`×`n` per patch. +/// Mesh tessellation as flat-filled paths (no stroke): each patch cut `n`×`n`, its quads joined +/// where the colour hardly changes ([`GradientMesh::pieces`]). pub fn mesh_quad_nodes(m: &GradientMesh, n: usize) -> Vec<Node> { - m.quads(n) + m.pieces(n) .into_iter() .map(|q| { let mut ap = Appearance::default(); diff --git a/crates/doc/src/live/mesh.rs b/crates/doc/src/live/mesh.rs index e86eecff9d..10540266a3 100644 --- a/crates/doc/src/live/mesh.rs +++ b/crates/doc/src/live/mesh.rs @@ -35,6 +35,15 @@ pub struct MeshQuad { pub corners: [(Color, f32); 4], } +/// One flat-coloured piece of a mesh ([`GradientMesh::pieces`]): a closed outline through +/// tessellation points, its colour and opacity. +#[derive(Clone, Debug, PartialEq)] +pub struct MeshPiece { + pub pts: Vec<Point>, + pub color: Color, + pub opacity: f32, +} + /// Create Gradient Mesh → Appearance. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum MeshAppearance { @@ -395,6 +404,105 @@ impl GradientMesh { out } + /// Flat-coloured pieces covering the mesh, for outputs that can't shade a mesh smoothly (SVG, + /// Expand): each patch cut into `n`×`n` quads as by [`Self::quads`], then neighbouring quads + /// joined into square blocks as large as keeps the colour across each block within about one + /// 8-bit step. A patch of one colour is one piece; a patch whose colour changes a lot keeps + /// all its quads. A piece's outline runs through its quads' outer corners, so it covers what + /// they covered, and it takes the colour at its centre. + pub fn pieces(&self, n: usize) -> Vec<MeshPiece> { + let n = n.clamp(1, 64); + let quads = self.quads(n); + let cols = (self.cols as usize).max(1); + let mut out = Vec::with_capacity(quads.len()); + for (k, patch) in quads.chunks_exact(n * n).enumerate() { + let (r, c) = (k / cols, k % cols); + let side = self.block_side(r, c, n, patch); + if side == 1 { + out.extend(patch.iter().map(|q| MeshPiece { pts: q.pts.to_vec(), color: q.color, opacity: q.opacity })); + continue; + } + // Tessellation point (i, j) of the patch (0..=n each), from a quad it is a corner of. + let at = |i: usize, j: usize| -> Option<Point> { + let (qi, qj) = (i.min(n - 1), j.min(n - 1)); + let q = patch.get(qj * n + qi)?; + q.pts + .get(match (i > qi, j > qj) { + (false, false) => 0, + (true, false) => 1, + (true, true) => 2, + (false, true) => 3, + }) + .copied() + }; + for j0 in (0..n).step_by(side) { + for i0 in (0..n).step_by(side) { + let (i1, j1) = (i0 + side, j0 + side); + // Around the block, in the quads' order: along its top, down its right side, + // back along its bottom and up its left side. + let ring = (i0..i1) + .map(|i| (i, j0)) + .chain((j0..j1).map(|j| (i1, j))) + .chain((i0 + 1..=i1).rev().map(|i| (i, j1))) + .chain((j0 + 1..=j1).rev().map(|j| (i0, j))); + let Some(pts) = ring.map(|(i, j)| at(i, j)).collect::<Option<Vec<Point>>>() else { continue }; + let half = side as f64 / 2.0; + let (color, opacity) = self.color_at(r, c, (i0 as f64 + half) / n as f64, (j0 as f64 + half) / n as f64); + out.push(MeshPiece { pts, color, opacity }); + } + } + } + out + } + + /// The side, in quads, of the blocks [`Self::pieces`] joins patch (r, c) into, cut into + /// `n`×`n` `quads`: the largest divisor of `n` that keeps the colour changing by at most one + /// 8-bit step across a block. 1 (no joining) where the patch folds over itself, as the outline + /// of a block across the fold wouldn't fill it as its quads do. + fn block_side(&self, r: usize, c: usize, n: usize, quads: &[MeshQuad]) -> usize { + let corner = |dr: usize, dc: usize| self.points.get(self.idx(r + dr, c + dc)); + let (Some(p00), Some(p01), Some(p10), Some(p11)) = (corner(0, 0), corner(0, 1), corner(1, 0), corner(1, 1)) else { + return 1; + }; + // Corners all in CMYK mix in their inks ([`Self::color_at`]); the RGB they show is checked too. + let inks = [p00, p01, p10, p11].iter().all(|p| matches!(p.color, Color::Cmyk { .. })); + let channels = |p: &MeshPoint| -> Vec<f32> { + let mut v = p.color.to_rgb().to_vec(); + if inks && let Color::Cmyk { c, m, y, k } = p.color { + v.extend([c, m, y, k]); + } + v.push(p.opacity); + v + }; + let [a, b, cc, d] = [p00, p01, p10, p11].map(channels); + // A bilinear patch changes across a block of side h (0..1 of the patch) by at most + // h × (du + dv) in each channel, du and dv its largest change along each parameter. + let mut steps = 0.0f32; + for k in 0..a.len() { + let ch = |v: &[f32]| v.get(k).copied().unwrap_or_default(); + let du = (ch(&a) - ch(&b)).abs().max((ch(&cc) - ch(&d)).abs()); + let dv = (ch(&a) - ch(&cc)).abs().max((ch(&b) - ch(&d)).abs()); + steps = steps.max((du + dv) * 255.0); + } + if !steps.is_finite() { + return 1; + } + let side = (1..=n).rev().find(|&s| n.is_multiple_of(s) && (n / s) as f32 >= steps).unwrap_or(1); + if side > 1 { + // Every quad turning the same way: the patch doesn't fold, so a block's outline + // encloses just what its quads cover. + let turn = |q: &MeshQuad| { + let [a, b, c, d] = q.pts; + (b - a).cross(c - a) + (c - a).cross(d - a) + }; + let first = quads.first().map(turn).unwrap_or_default(); + if !quads.iter().all(|q| turn(q) * first > 0.0) { + return 1; + } + } + side + } + /// The mesh's outer boundary as a closed path. pub fn outline(&self) -> PathData { if !self.is_valid() { diff --git a/crates/engine/src/tests/live.rs b/crates/engine/src/tests/live.rs index ebe275bcec..a3b9f132b5 100644 --- a/crates/engine/src/tests/live.rs +++ b/crates/engine/src/tests/live.rs @@ -1020,10 +1020,15 @@ fn mesh_expand_to_flat_pieces() { let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); sel(&mut s, &[a]); s.execute("object.mesh.create", &json!({"rows": 1, "cols": 2})).unwrap(); + // The first patch shades from black to white; the second is one colour. + for (index, color) in [(0, "#000000"), (3, "#000000"), (1, "#ffffff"), (2, "#ffffff"), (4, "#ffffff"), (5, "#ffffff")] { + s.execute("object.mesh.setPointColor", &json!({"id": a.0, "index": index, "color": color})).unwrap(); + } s.execute("object.mesh.expand", &json!({})).unwrap(); let g = node(&s, a); assert!(matches!(g.kind, NodeKind::Group { .. })); - assert_eq!(g.children().unwrap().len(), 2 * 64); + // 8 × 8 pieces for the shaded patch, one for the flat one. + assert_eq!(g.children().unwrap().len(), 64 + 1); assert!(g.children().unwrap().iter().all(|c| c.id != NodeId(0))); } @@ -1093,9 +1098,10 @@ fn live_objects_round_trip_through_native_format() { fn svg_export_expands_live_objects() { let s = live_doc(); let svg = vectorcraft_svg::export(&s.doc().unwrap().doc, &Default::default()); - // 4 blend objects + envelope content + 4 patches × 64 mesh pieces. + // 4 blend objects + envelope content + a piece for each of the 4 mesh patches (the mesh is + // white, which its highlight leaves white, so a patch is one piece rather than 64 alike). let paths = vectorcraft_testkit::svg_shapes(&svg); - assert!(paths >= 4 + 1 + 256, "{paths}"); + assert!(paths >= 4 + 1 + 4, "{paths}"); assert!(vectorcraft_svg::import(&svg).is_ok()); } diff --git a/crates/svg/tests/it/main.rs b/crates/svg/tests/it/main.rs index e769c6d987..3e554a3977 100644 --- a/crates/svg/tests/it/main.rs +++ b/crates/svg/tests/it/main.rs @@ -22,6 +22,7 @@ mod import_text; mod import_units; mod interactivity; mod mask_options; +mod mesh_export; mod non_scaling_stroke; mod options; mod prop_svg; diff --git a/crates/svg/tests/it/mesh_export.rs b/crates/svg/tests/it/mesh_export.rs new file mode 100644 index 0000000000..60c5dcbb08 --- /dev/null +++ b/crates/svg/tests/it/mesh_export.rs @@ -0,0 +1,116 @@ +//! Gradient meshes in SVG export: SVG has no mesh paint, so a mesh is written as flat-coloured +//! pieces, each patch cut finely enough that neighbouring pieces differ by about one 8-bit +//! colour step at most, and no finer: a patch of one colour is one piece, not 64 alike. + +use vectorcraft_color::Color; +use vectorcraft_doc::live::{GradientMesh, MeshAppearance}; +use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_geom::{Rect, shapes}; +use vectorcraft_svg::{ExportOptions, export}; +use vectorcraft_testkit::raster::{Image, channel_diff, render_artboard}; + +/// A 200 × 200 pt document with a `rows` × `cols` mesh over (20, 20)–(180, 180), each point +/// coloured by `color(row, col)`. +fn doc(rows: u32, cols: u32, color: impl Fn(usize, usize) -> Color) -> Document { + let mut m = GradientMesh::for_path(&shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), rows, cols, Color::BLACK, MeshAppearance::Flat, 0.0) + .expect("a mesh"); + for r in 0..=rows as usize { + for c in 0..=cols as usize { + let i = m.idx(r, c); + m.points[i].color = color(r, c); + } + } + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + d.insert(Some(l), 0, Node::new(id, NodeKind::Mesh(m))).unwrap(); + d +} + +/// Filled shapes in the SVG. +fn pieces(svg: &str) -> usize { + ["<polygon", "<rect", "<path"].iter().map(|e| svg.matches(e).count()).sum() +} + +/// The exported SVG rendered by resvg on white at 1 px/pt. +fn resvg_render(svg: &str) -> Image { + let tree = resvg::usvg::Tree::from_str(svg, &resvg::usvg::Options::default()).expect("parse"); + let mut pm = resvg::tiny_skia::Pixmap::new(200, 200).unwrap(); + pm.fill(resvg::tiny_skia::Color::WHITE); + resvg::render(&tree, resvg::tiny_skia::Transform::identity(), &mut pm.as_mut()); + Image { width: 200, height: 200, rgba: pm.data().to_vec() } +} + +/// Compare the SVG as resvg draws it with the canvas, over the pixels `inside` the mesh (the +/// canvas grows a mesh's outline by half a pixel, so its edge is left out): at most `bad` of them +/// differ by more than `tol` in a channel. +fn assert_looks_alike(d: &Document, svg: &str, inside: impl Fn(f64, f64) -> bool, tol: u8, bad: f64) { + let (mine, canvas) = (resvg_render(svg), render_artboard(d)); + let (mut n, mut off, mut worst) = (0usize, 0usize, 0u8); + for y in 0..200 { + for x in 0..200 { + if !inside(x as f64 + 0.5, y as f64 + 0.5) { + continue; + } + n += 1; + let c = channel_diff(mine.pixel(x, y), canvas.pixel(x, y)); + worst = worst.max(c); + if c > tol { + off += 1; + } + } + } + assert!(n > 0 && (off as f64) <= bad * n as f64, "{off} of {n} pixels differ by more than {tol} (worst {worst})"); +} + +/// Inside the mesh square, two pixels in from its edge. +fn in_square(x: f64, y: f64) -> bool { + (22.0..178.0).contains(&x) && (22.0..178.0).contains(&y) +} + +#[test] +fn a_patch_of_one_colour_is_one_piece() { + // 4 × 4 patches, every point the same colour: 16 pieces, not 16 × 64. + let d = doc(4, 4, |_, _| Color::rgb8(40, 120, 200)); + let svg = export(&d, &ExportOptions::default()); + assert!(pieces(&svg) <= 16, "{} pieces", pieces(&svg)); + assert_looks_alike(&d, &svg, in_square, 2, 0.0); +} + +#[test] +fn a_patch_is_cut_no_finer_than_its_colour_changes() { + // Each patch changes by one 8-bit step from left to right: one piece is close enough. + let d = doc(2, 2, |_, c| Color::rgb8(100 + c as u8, 100 + c as u8, 100 + c as u8)); + let svg = export(&d, &ExportOptions::default()); + assert!(pieces(&svg) <= 4, "{} pieces", pieces(&svg)); + assert_looks_alike(&d, &svg, in_square, 2, 0.0); +} + +#[test] +fn a_strong_gradient_is_still_cut_finely() { + // Black to white across one patch: as many pieces as before, so the steps stay small. + let d = doc(1, 1, |_, c| if c == 0 { Color::BLACK } else { Color::WHITE }); + let svg = export(&d, &ExportOptions::default()); + assert!(pieces(&svg) >= 64, "{} pieces", pieces(&svg)); + // Flat pieces step where the canvas shades smoothly: within half a piece's step (255 / 16). + assert_looks_alike(&d, &svg, in_square, 17, 0.0); +} + +#[test] +fn a_curved_patch_of_one_colour_keeps_its_shape() { + // A mesh over a circle: its patches' edges are curves, which one piece must still follow. + let mut m = + GradientMesh::for_path(&shapes::ellipse(Rect::new(20.0, 20.0, 180.0, 180.0)), 2, 2, Color::BLACK, MeshAppearance::Flat, 0.0).expect("a mesh"); + for p in &mut m.points { + p.color = Color::rgb8(200, 40, 60); + } + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + d.insert(Some(l), 0, Node::new(id, NodeKind::Mesh(m))).unwrap(); + let svg = export(&d, &ExportOptions::default()); + assert!(pieces(&svg) <= 4, "{} pieces", pieces(&svg)); + // Two pixels in from the circle: the pieces' edges are straight between points 1/8 of a + // patch edge apart, as the quads' were. + assert_looks_alike(&d, &svg, |x, y| (x - 100.0).hypot(y - 100.0) < 78.0, 2, 0.0); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index dc23c77b7e..9c866d4223 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (PDF import: knockout and isolated groups keep their flags after a group drawn straight onto its parent) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (SVG export and Expand: a gradient mesh patch is cut no finer than its colour changes) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -132,6 +132,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | SVG export (and Object › Expand, EPS, DXF, EMF and the other outputs that cut a gradient mesh into flat pieces): each patch was cut into 8 × 8 quads whatever its colours, so a patch of one colour became 64 identical pieces. Neighbouring quads are now joined into square blocks wherever the colour changes by no more than about one 8-bit step across the block, so a flat patch is one piece and a patch that shades strongly keeps all 64; a block's outline runs through its quads' corners, and a patch that folds over itself is not joined. A synthetic page of 400 meshes (6 × 6 patches, half flat) exports 468,000 pieces instead of 921,600 (35 MB instead of 66 MB), and resvg draws the two files identically. Tests `mesh_export` (crate `vectorcraft-svg`), `tests::live::mesh_expand_to_flat_pieces`; scores unchanged | | 2026-10-31 | minor | PDF import (and a `.ai`'s PDF part): a transparency group's knockout and isolate flags (`/K`, `/I`; ISO 32000-1, 11.4.6.3) come from the interpreter as it pushes the group. They were read from the file in order and matched to the groups pushed, but a group that adds nothing (full opacity, Normal, no mask, neither flag) is drawn straight onto its parent without being pushed, so every group after one lost its own flags and took another's; and a page drawing form groups more than 10,000 times failed to import (the list of their flags was capped), which it no longer does. A blend's steps written as a knockout group of falling opacity drew as solid dark shapes: a user's `.ai` with 143 such bubbles now draws them as light rings, as poppler does (its bubble area 4.9% → 1.2% of pixels off from poppler's render); 16 other users' PDFs with transparency groups (44 pages) draw the same. Test `tests::import_fidelity::knockout_groups_after_a_group_drawn_straight_keep_their_flag`; scores unchanged | | 2026-10-30 | minor | `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout; blends are written with knockout on) in the state block after its record, as a group takes the one after its end; it was left for the next object, so a blend's steps of falling opacity drew over each other instead of knocking each other out, and every such blend came in too dark (a user's file has 143, its bubbles came in as dark rings). Both a live blend and drawn steps kept as a group take it. Test `import::ai::tests::a_blends_transparency_follows_its_record`; checked locally against that file: it comes 1.3% → 0.6% nearer its page, though a mesh seen through a mesh-shaped opacity mask still keeps it just over the limit. When a blend is the layer's last object and the layer's own state block (`7 () XW`, then `LB`) follows, the state is the layer's and the blend keeps its own, as for meshes (#4748); scores unchanged | | 2026-10-31 | minor | PDF (and `.ai`) with Illustrator editing data saved with only some of its artboards: its pages are those artboards, while the editing data keeps them all, and the layers were compared with the first page on the first artboard, so a page of the second artboard came in as the PDF part, without its layers. With fewer pages than artboards, the first page is now taken to be the artboard of its size whose art draws most like it (up to 16 weighed), and the pages' type goes to that artboard and the ones after it. All artboards come in, as before. Test `import::tests_native::a_pdf_of_its_second_artboard_is_compared_on_that_artboard`; scores unchanged | From 64ffab00a99255ef1b116685f184c53820733f3c Mon Sep 17 00:00:00 2001 From: marshiyar <57055687+marshiyar@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:28:00 -0700 Subject: [PATCH 045/260] Swatch libraries: a library titled with a Windows device name is saved under another name (#3602) library_file_name kept CON, NUL, COM1 and the like, which Windows treats as devices, not files. It now adds a - after such a name (CON-.json). Part of #3602 --- crates/engine/src/cmd/swatchlib.rs | 11 +++++++++-- crates/engine/src/file_access.rs | 2 +- crates/engine/src/tests/swatchlib.rs | 16 ++++++++++++++++ 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index b7a0e2f299..d3652aa4e1 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -331,11 +331,18 @@ fn library_tab_name(file: &str, lib_name: &str) -> String { } /// The file name of library `name` with extension `ext`: characters file systems reject become -/// `-`, and dots and spaces at either end are dropped. A name with nothing left is `Library`. +/// `-`, and dots and spaces at either end are dropped. A name with nothing left is `Library`, and +/// one that is a Windows device name (`CON`, `NUL`, `COM1`…) gets a `-` after it. pub fn library_file_name(name: &str, ext: &str) -> String { let base: String = name.chars().map(|c| if "/\\:*?\"<>|".contains(c) || c.is_control() { '-' } else { c }).collect(); let base = base.trim_matches(['.', ' ']); - format!("{}.{ext}", if base.is_empty() { "Library" } else { base }) + if base.is_empty() { + format!("Library.{ext}") + } else if crate::file_access::is_device_name(base) { + format!("{base}-.{ext}") + } else { + format!("{base}.{ext}") + } } /// The library files with extensions `exts` in folder `dir`, sorted by name. diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 9930065132..56db72a222 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -274,7 +274,7 @@ fn same_component(a: Component, b: Component) -> bool { } /// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file. -fn is_device_name(component: &str) -> bool { +pub(crate) fn is_device_name(component: &str) -> bool { let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase(); let numbered = |prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9")); matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT") diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index c20968db54..d6c9f84520 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -637,3 +637,19 @@ fn gradient_libraries_are_listed_and_gradient_swatches_rename_and_take_new_gradi run(&mut s, "swatch.edit", json!({"name": "Red", "paint": {"color": "#00ff00"}})); assert_eq!(doc(&s).swatch("Red").unwrap().paint.color().map(|c| c.to_hex()), Some("#00ff00".into())); } + +/// #3602: a library titled with a Windows device name is saved under a name that is not one. +#[test] +fn a_library_file_name_is_never_a_windows_device_name() { + use crate::cmd::swatchlib::library_file_name; + for (title, ext) in [("CON", "json"), ("nul", "json"), ("Com1", "acb"), ("LPT9", "ase"), ("aux.", "json")] { + let file = library_file_name(title, ext); + assert!(!crate::file_access::is_device_name(&file), "{title}: {file}"); + assert!( + file.ends_with(&format!(".{ext}")) && file.to_ascii_lowercase().contains(&title.trim_end_matches('.').to_ascii_lowercase()), + "{title}: {file}" + ); + } + assert_eq!(library_file_name("Console", "json"), "Console.json"); + assert_eq!(library_file_name("COM10", "json"), "COM10.json"); +} From ae7645572345f8b7444f21434ecf26dc43a029cb Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 20:18:54 -0700 Subject: [PATCH 046/260] Perspective Selection: a move of loose art keeps its plane when 4 clears the active plane The move drag remembers the plane it places loose art on. Pressing 4 during the drag, or dragging on after it, previews and commits the move on that plane instead of dropping it. A 1-3 key pressed before the drag threshold also sets the plane the move uses. --- crates/engine/src/tests/persp_select.rs | 33 +++++++++++++++++++ crates/tools/src/distort/perspective.rs | 25 ++++++++++++++ crates/tools/src/distort/perspective/tools.rs | 30 ++++++++++------- 3 files changed, 77 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/tests/persp_select.rs b/crates/engine/src/tests/persp_select.rs index c590aee5b7..4ca4b46faf 100644 --- a/crates/engine/src/tests/persp_select.rs +++ b/crates/engine/src/tests/persp_select.rs @@ -281,6 +281,39 @@ fn shift_drag_keeps_its_displacement_after_a_plane_key() { } } +#[test] +fn loose_art_move_survives_clearing_the_active_plane() { + for (drag_after_key, switch_before_drag) in [(false, false), (true, false), (false, true)] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600, "created": null})).unwrap(); + s.execute("perspective.grid.preset", &json!({"kind": 2})).unwrap(); + s.execute("perspective.grid.snap", &json!({"on": false})).unwrap(); + s.execute("perspective.plane.set", &json!({"plane": "right"})).unwrap(); + let result = s.execute("shape.rectangle", &json!({"x": 450, "y": 380, "width": 60, "height": 60})).unwrap(); + let id = NodeId(result["id"].as_u64().unwrap()); + assert_eq!(attached(&s, id), None); + let before = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap(); + let (from, to) = (before.center(), before.center() + Vec2::new(30.0, 15.0)); + let v = ViewInfo::default(); + s.select_tool("perspectiveSelection", v).unwrap(); + let undo_before = undo_len(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, from.x, from.y), v).unwrap(); + if switch_before_drag { + s.tool_key(ToolKey::Digit(2), Mods::default(), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Drag, to.x, to.y), v).unwrap(); + s.tool_key(ToolKey::Digit(4), Mods::default(), v).unwrap(); + assert_eq!(grid(&s).plane, Plane::None); + if drag_after_key { + s.pointer(&PointerEvent::new(PointerKind::Drag, to.x + 10.0, to.y), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, to.x, to.y), v).unwrap(); + assert_eq!(attached(&s, id), Some((if switch_before_drag { Plane::Ground } else { Plane::Right }, 0.0))); + assert_ne!(s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap(), before); + assert_eq!(undo_len(&s), undo_before + 1); + } +} + #[test] fn cmd_alt_shift_drag_copies_on_a_plane_axis() { let (mut s, id) = persp_session(); diff --git a/crates/tools/src/distort/perspective.rs b/crates/tools/src/distort/perspective.rs index d535b5cd2a..7f3f374055 100644 --- a/crates/tools/src/distort/perspective.rs +++ b/crates/tools/src/distort/perspective.rs @@ -1286,6 +1286,31 @@ mod tests { assert_eq!(params["constrain"], json!(true)); } + #[test] + fn loose_move_preview_keeps_its_plane_when_the_active_plane_is_cleared() { + let (mut d, id) = doc_with_rect(); + let mut g = grid(2); + g.plane = Plane::Right; + g.store(&mut d); + let mut selection = Selection::default(); + selection.add(id); + let p = paint(); + let from = d.node(id).unwrap().geometric_bounds().unwrap().center(); + let to = from + Vec2::new(30.0, 15.0); + let mut tool = PerspectiveSelectionTool::default(); + let c = cx(&d, &selection, &p); + tool.pointer(&c, &PointerEvent::new(PointerKind::Down, from.x, from.y)); + let actions = tool.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + assert!(matches!(actions.last(), Some(Action::Preview(_, params)) if params["plane"] == "right")); + g.plane = Plane::None; + g.store(&mut d); + let c = cx(&d, &selection, &p); + let actions = tool.key(&c, ToolKey::Digit(4), Mods::default()); + assert!(matches!(actions.last(), Some(Action::Preview(_, params)) if params["plane"] == "right"), "{actions:?}"); + let actions = tool.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x + 10.0, to.y)); + assert!(matches!(actions.last(), Some(Action::Preview(_, params)) if params["plane"] == "right"), "{actions:?}"); + } + #[test] fn selection_move_recomputes_shift_copy_and_perpendicular() { let (mut d, id) = doc_with_rect(); diff --git a/crates/tools/src/distort/perspective/tools.rs b/crates/tools/src/distort/perspective/tools.rs index e791f4ef33..915e4a8835 100644 --- a/crates/tools/src/distort/perspective/tools.rs +++ b/crates/tools/src/distort/perspective/tools.rs @@ -120,7 +120,7 @@ enum SelDrag { Idle, /// Pressed on an object: moves `ids` once the pointer leaves the drag threshold. `perp`: along /// the plane's normal (5 pressed while dragging); `copy` and `shift`: modifiers at the last event. - Move { ids: Vec<NodeId>, from: Point, last: Point, began: bool, perp: bool, copy: bool, shift: bool }, + Move { ids: Vec<NodeId>, from: Point, last: Point, plane: Plane, began: bool, perp: bool, copy: bool, shift: bool }, /// Dragging `handle` of the perspective bounding box `rect` (plane space, on `plane` at `depth`). Scale { ids: Vec<NodeId>, plane: Plane, depth: f64, rect: Rect, handle: BoxHandle }, /// Dragging a plane widget. @@ -164,9 +164,11 @@ pub(super) fn resize_cursor(d: Vec2) -> Cursor { impl PerspectiveSelectionTool { /// The `perspective.move` preview for the move drag (and its measurement label). fn move_preview(&mut self, cx: &ToolContext) -> Option<Action> { - let SelDrag::Move { ids, from, last, perp, copy, shift, .. } = &self.drag else { return None }; + let SelDrag::Move { ids, from, last, plane, perp, copy, shift, .. } = &self.drag else { return None }; let g = PerspectiveGrid::current(cx.doc); - let at = ids.first().and_then(|id| g.attachment_of(cx.doc, *id)).or((g.plane != Plane::None).then_some((g.plane, g.offset(g.plane)))); + let move_plane = if g.plane == Plane::None { *plane } else { g.plane }; + let at = + ids.first().and_then(|id| g.attachment_of(cx.doc, *id)).or((move_plane != Plane::None).then_some((move_plane, g.offset(move_plane)))); let constrained = if *shift && !*perp { at.and_then(|(plane, depth)| { let delta = g.plane_delta(plane, depth, *from, *last)?; @@ -179,8 +181,8 @@ impl PerspectiveSelectionTool { if *shift && !*perp { v["constrain"] = json!(true); } - if g.plane != Plane::None { - v["plane"] = json!(g.plane.id()); + if move_plane != Plane::None { + v["plane"] = json!(move_plane.id()); } self.measure = at.and_then(|(pl, depth)| { let text = if *perp { @@ -230,24 +232,26 @@ impl Tool for PerspectiveSelectionTool { vec![top] }; // Selecting an object in perspective makes its plane the active one. + let mut plane = g.plane; if let Some((pl, _)) = g.attachment_of(cx.doc, top) && pl != g.plane { acts.push(Action::Exec("perspective.plane.set".into(), json!({"plane": pl.id()}))); + plane = pl; } - self.drag = SelDrag::Move { ids, from: p, last: p, began: false, perp: false, copy: m.alt, shift: m.shift }; + self.drag = SelDrag::Move { ids, from: p, last: p, plane, began: false, perp: false, copy: m.alt, shift: m.shift }; acts } - (PointerKind::Drag, SelDrag::Move { ids, from, began, perp, .. }) => { + (PointerKind::Drag, SelDrag::Move { ids, from, plane, began, perp, .. }) => { if !began && p.distance(from) < cx.tol(3.0) { - self.drag = SelDrag::Move { ids, from, last: p, began, perp, copy: m.alt, shift: m.shift }; + self.drag = SelDrag::Move { ids, from, last: p, plane, began, perp, copy: m.alt, shift: m.shift }; return vec![]; } let mut out = vec![]; if !began { out.push(Action::Begin(if m.alt { "Copy in Perspective" } else { "Move in Perspective" }.into())); } - self.drag = SelDrag::Move { ids, from, last: p, began: true, perp, copy: m.alt, shift: m.shift }; + self.drag = SelDrag::Move { ids, from, last: p, plane, began: true, perp, copy: m.alt, shift: m.shift }; out.extend(self.move_preview(cx)); out } @@ -307,10 +311,14 @@ impl Tool for PerspectiveSelectionTool { return if *began { self.move_preview(cx).into_iter().collect() } else { vec![] }; } if matches!(key, ToolKey::Digit(1..=4)) - && let SelDrag::Move { began: true, shift, .. } = &mut self.drag + && let SelDrag::Move { began, plane, shift, .. } = &mut self.drag { *shift = mods.shift; - return self.move_preview(cx).into_iter().collect(); + let active = PerspectiveGrid::current(cx.doc).plane; + if active != Plane::None { + *plane = active; + } + return if *began { self.move_preview(cx).into_iter().collect() } else { vec![] }; } let (dx, dy) = match key { ToolKey::Left => (-1, 0), From 8363c815ecb7222f1a04b664d414ad0a3f3a6265 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 00:05:46 -0700 Subject: [PATCH 047/260] Perspective: a transform's overflow fallback keeps each entry's powers of two apart MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the conjugate a ∘ self ∘ a⁻¹ overflows, conjugated now forms every entry of the product as a sum of terms whose factors are split into a mantissa and a power of two, and scales the whole product by one power of two from its w row at the end. Scaling each partial product to a largest entry of 1 could round an entry to 0 that the next factor would restore, so a projection with entries far apart in size, such as a scale by (1e160, 1e-160) seen through the same scale, was removed and the art drew flat. --- crates/geom/src/projective.rs | 89 +++++++++++++++++++++++++---------- 1 file changed, 63 insertions(+), 26 deletions(-) diff --git a/crates/geom/src/projective.rs b/crates/geom/src/projective.rs index 4b17aac60d..ddf836a23f 100644 --- a/crates/geom/src/projective.rs +++ b/crates/geom/src/projective.rs @@ -100,11 +100,11 @@ impl Homography { } /// `self` seen through `a`: the map `a ∘ self ∘ a⁻¹` (what `self` becomes when everything it - /// maps from and to is moved by `a`). When the product overflows, it is formed one factor at a - /// time, each partial product scaled to a largest entry of 1, and returned divided by the - /// largest magnitude in its `w` row (the same map, with a `w` row whose largest entry is 1). - /// `None` when `a` isn't invertible, or when the product overflows and the result at that - /// scale has an entry that is not finite or is not invertible. + /// maps from and to is moved by `a`). When the product overflows, every entry is formed with + /// its powers of two kept apart, and the product is returned divided by the largest magnitude + /// in its `w` row (the same map, with a `w` row whose largest entry is 1). `None` when `a` + /// isn't invertible, or when the product overflows and the result at that scale has an entry + /// that is not finite or is not invertible. pub fn conjugated(&self, a: Affine) -> Option<Self> { if a.determinant().abs() < 1e-15 { return None; @@ -114,12 +114,28 @@ impl Homography { if c.is_finite() { return Some(c); } - let c = to.then_after_normalized(&self.normalized()?)?.then_after_normalized(&from)?; - let k = c.0[2].iter().fold(0.0_f64, |k, v| k.max(v.abs())); + // Each entry of the product is a sum of nine terms to[r][i]·self[i][j]·from[j][k]. Every + // factor is split into a mantissa and a power of two, so each term is a mantissa product + // and an exponent sum, and the whole product is scaled by one power of two at the end. + let split = |h: &Self| h.0.map(|row| row.map(frexp)); + let (t, s, f) = (split(&to), split(self), split(&from)); + let term = |r: usize, i: usize, j: usize, k: usize| { + let (a, b, c) = (t[r][i], s[i][j], f[j][k]); + (a.0 * b.0 * c.0, a.1 + b.1 + c.1) + }; + let ijk = (0..27).map(|n| (n / 9, n / 3 % 3, n % 3)); + let e = ijk.map(|(i, j, k)| term(2, i, j, k)).filter(|(m, _)| *m != 0.0).map(|(_, e)| e).max()?; + let mut c = [[0.0; 3]; 3]; + for (r, row) in c.iter_mut().enumerate() { + for (k, v) in row.iter_mut().enumerate() { + *v = (0..9).map(|n| term(r, n / 3, n % 3, k)).map(|(m, x)| ldexp(m, x - e)).sum(); + } + } + let k = c[2].iter().fold(0.0_f64, |k, v| k.max(v.abs())); if k <= 0.0 { return None; } - let c = Self(c.0.map(|row| row.map(|v| v / k))); + let c = Self(c.map(|row| row.map(|v| v / k))); (c.is_finite() && c.det().abs() > 1e-15).then_some(c) } @@ -127,24 +143,6 @@ impl Homography { self.0.iter().flatten().all(|v| v.is_finite()) } - /// `self` divided by its largest entry magnitude, a positive scale that maps every point to - /// the same place; `None` when an entry is not finite or every entry is 0. - fn normalized(&self) -> Option<Self> { - let k = self.0.iter().flatten().fold(0.0_f64, |k, v| k.max(v.abs())); - (self.is_finite() && k > 0.0).then(|| Self(self.0.map(|row| row.map(|v| v / k)))) - } - - /// `self ∘ other` divided by its largest entry magnitude; when that product overflows, it is - /// formed from both factors divided by their largest entry magnitudes. `None` when the result - /// has an entry that is not finite or every entry is 0. - fn then_after_normalized(&self, other: &Self) -> Option<Self> { - let c = self.then_after(other); - if c.is_finite() { - return c.normalized(); - } - self.normalized()?.then_after(&other.normalized()?).normalized() - } - /// The affine map that matches `self` to first order at `p` (its derivative there), `None` /// beyond the horizon or when the derivative is not finite. pub fn affine_at(&self, p: Point) -> Option<Affine> { @@ -171,6 +169,36 @@ impl Homography { } } +/// `v` as `m·2^e` with `0.5 ≤ |m| < 1`; 0, infinities and NaN come back as `(v, 0)`. +fn frexp(v: f64) -> (f64, i32) { + if v == 0.0 || !v.is_finite() { + return (v, 0); + } + // A subnormal is scaled into the normal range first. + let (v, bias) = if v.abs() < f64::MIN_POSITIVE { (v * pow2(64), -64) } else { (v, 0) }; + let bits = v.to_bits(); + let e = ((bits >> 52) & 0x7ff) as i32 - 1022; + (f64::from_bits((bits & !(0x7ff << 52)) | (1022 << 52)), e + bias) +} + +/// `m·2^e`, multiplied in steps of powers of two that are each within the normal range. +fn ldexp(mut m: f64, mut e: i32) -> f64 { + while e > 1023 && m.is_finite() { + m *= pow2(1023); + e -= 1023; + } + while e < -1022 && m != 0.0 { + m *= pow2(-1022); + e += 1022; + } + m * pow2(e.clamp(-1022, 1023)) +} + +/// `2^e` for `-1022 ≤ e ≤ 1023`. +fn pow2(e: i32) -> f64 { + f64::from_bits(((e + 1023) as u64) << 52) +} + #[cfg(test)] mod tests { use super::*; @@ -288,6 +316,15 @@ mod tests { assert!((v - w).abs() <= 1e-9 * w.abs().max(1.0), "{c:?}"); } assert_eq!(Homography::from_array(c.to_array()), Some(c)); + // A scale by (1e160, 1e-160) seen through the same scale is itself, though the product's + // first entry is 1e320 and a scale to a largest entry of 1 takes its second to 1e-480. + let thin = Homography([[1e160, 0.0, 0.0], [0.0, 1e-160, 0.0], [0.0, 0.0, 1.0]]); + assert!(Homography::from_array(thin.to_array()).is_some()); + let c = thin.conjugated(Affine::scale_non_uniform(1e160, 1e-160)).unwrap(); + for (v, w) in c.to_array().iter().zip(thin.to_array()) { + assert!((v - w).abs() <= 1e-9 * w.abs(), "{c:?}"); + } + assert_eq!(Homography::from_array(c.to_array()), Some(c)); // A move by 1e200 seen through a scale by 1e150 sends every point to about (1e350, 0), // which no invertible map of finite numbers draws. let far = Homography([[1.0, 0.0, 1e200], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]); From f28de75a225f4f8a2e4e9d3069534f3440951239 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 17:47:29 -0700 Subject: [PATCH 048/260] Shortcuts: an exact Shift binding for the typed character wins over a plain binding at Shift+Comma or Shift+Period --- crates/ui-egui/src/shortcuts.rs | 16 ++++++++-------- crates/ui-egui/src/shortcuts/tests.rs | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 8425456b99..cb66d71c1d 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -731,8 +731,8 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, accept: impl FnMut(&H let mirror = crate::shortcut_editor::current(); let dispatcher = &mut app.dispatcher; ctx.input_mut(|i| { - // Shift+Comma and Shift+Period follow their key positions when no chord for the - // logical press is bound. An explicit shifted logical binding takes precedence. + // An explicit shifted logical binding takes precedence. Otherwise, Shift+Comma and + // Shift+Period follow their key positions when no chord for the press is bound. for e in &mut i.events { let input = craft_keymap::KeyInput::from_egui(e, crate::keymap::platform()); if let egui::Event::Key { key, physical_key: Some(physical), modifiers, pressed: true, .. } = e @@ -749,12 +749,12 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, accept: impl FnMut(&H let mods = craft_keymap::Mods::from_egui(modifiers, crate::keymap::platform()); let logical_chord = craft_keymap::Chord::new(mods, logical); let position_chord = craft_keymap::Chord::new(mods, position); - if !dispatcher.layout().candidates(&input).iter().any(|chord| crate::keymap::lookup(&mirror.keymap, chord).is_some()) { - if crate::keymap::lookup(&mirror.keymap, &logical_chord).is_some() { - *physical = *key; - } else if crate::keymap::lookup(&mirror.keymap, &position_chord).is_some() { - *key = *physical; - } + if crate::keymap::lookup(&mirror.keymap, &logical_chord).is_some() { + *physical = *key; + } else if crate::keymap::lookup(&mirror.keymap, &position_chord).is_some() + && !dispatcher.layout().candidates(&input).iter().any(|chord| crate::keymap::lookup(&mirror.keymap, chord).is_some()) + { + *key = *physical; } } } diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index ceb68108c7..c5005fba9d 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1251,6 +1251,27 @@ fn resolved_logical_binding_wins_over_position_alias() { } } +#[test] +fn exact_shifted_logical_binding_wins_over_plain_text_binding() { + let mut app = remembered_paint_app(); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "view.rulers", ";"); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "view.grid", "Shift+;"); + let rulers_before = app.ui.view.rulers; + let grid_before = app.ui.view.grid; + let journal_before = app.session.journal.len(); + frame( + &mut app, + vec![ + egui::Event::ModifiersChanged(Modifiers::SHIFT), + egui::Event::Key { key: Key::Semicolon, physical_key: Some(Key::Comma), pressed: true, repeat: false, modifiers: Modifiers::SHIFT }, + egui::Event::Text(";".into()), + ], + ); + assert_eq!(app.ui.view.grid, !grid_before, "Shift+; runs Show Grid"); + assert_eq!(app.ui.view.rulers, rulers_before, "plain ; does not run Show Rulers"); + assert!(app.session.journal.since(journal_before).iter().all(|(command, _)| !command.starts_with("paint.")), "the press runs no paint command"); +} + #[test] fn user_shifted_punctuation_binding_runs_once() { let mut app = remembered_paint_app(); From b13b3260cd86e4ecf243b1be15c1fd8cc803967c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 18:48:07 +0700 Subject: [PATCH 049/260] Keyboard Shortcuts: a shortcut on the Turkish Q quotation-mark key shows " and runs Squashed from #4851 onto main. --- crates/ui-egui/src/chrome.rs | 2 +- crates/ui-egui/src/chrome/hints.rs | 4 +- crates/ui-egui/src/edit_toolbar.rs | 2 +- crates/ui-egui/src/menus.rs | 2 +- crates/ui-egui/src/menus/bar.rs | 4 +- crates/ui-egui/src/menus/entries.rs | 6 ++ crates/ui-egui/src/palette.rs | 2 +- crates/ui-egui/src/shortcut_editor.rs | 139 +++++++++++++++++++++++--- crates/ui-egui/src/shortcuts.rs | 28 ++++-- crates/ui-egui/src/shortcuts/tests.rs | 49 +++++++++ crates/ui-egui/src/toolbar.rs | 7 +- docs/target-app-parity.md | 1 + 12 files changed, 213 insertions(+), 33 deletions(-) diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index dea0bd3a49..b9c5f11fc9 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -101,7 +101,7 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { // Search → command palette (its shortcut opens it too). if search { let tip = match menus::shortcut_of("help.commandPalette") { - Some(sc) => format!("{} ({})", tl!("Search commands and tools"), menus::pretty_shortcut(sc)), + Some(sc) => format!("{} ({})", tl!("Search commands and tools"), menus::shown_shortcut(sc)), None => tl!("Search commands and tools").to_string(), }; if widgets::icon_button(ui, "search", &tip, app.ui.palette_open, icon).clicked() { diff --git a/crates/ui-egui/src/chrome/hints.rs b/crates/ui-egui/src/chrome/hints.rs index 7fc2e749b7..7d85a07be1 100644 --- a/crates/ui-egui/src/chrome/hints.rs +++ b/crates/ui-egui/src/chrome/hints.rs @@ -214,11 +214,11 @@ pub(super) fn hint_segments(tool: &str) -> Vec<(Cow<'static, str>, bool)> { } match text.rsplit_once('+') { Some((_, key)) if !key.is_empty() => { - let pretty = menus::pretty_shortcut(text); + let pretty = menus::shown_shortcut(text); let shown = pretty.strip_suffix(key).map_or(pretty.clone(), |m| format!("{m}{}", tl!(key))); (Cow::Owned(shown), bold) } - _ => (Cow::Owned(menus::pretty_shortcut(tl!(text))), bold), + _ => (Cow::Owned(menus::shown_shortcut(tl!(text))), bold), } }) .collect() diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index 8ec296aba1..34f5c77828 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -602,7 +602,7 @@ fn row(ui: &mut Ui, t: &Tokens, tool: &'static ToolInfo, on: bool, dimmed: bool) let icon = Rect::from_center_size(rect.left_center() + vec2(8.0 + ICON / 2.0, 0.0), vec2(ICON, ICON)); icons::paint(ui, icons::tool_icon(tool.icon), icon, if dimmed || on { color } else { t.icon }); let painter = ui.painter().with_clip_rect(rect); - let shortcut = crate::shortcut_editor::tool_shortcut(tool.id); + let shortcut = crate::shortcut_editor::tool_shortcut(tool.id).map(crate::shortcut_editor::as_typed); let keys_w = shortcut.as_ref().map_or(0.0, |k| { let keys = if on { t.text_strong diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 2c8c051f66..a419204162 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -62,7 +62,7 @@ pub(crate) use bar::{home_key, home_showing}; #[cfg(test)] use bar::{menu_body, pointer_reaches_title}; pub use context::{context_items, context_menu_body, ruler_menu_body, ruler_unit_items}; -pub use entries::{MenuEntry, Row, context_entries, entry, menu_entries, pretty_shortcut}; +pub use entries::{MenuEntry, Row, context_entries, entry, menu_entries, pretty_shortcut, shown_shortcut}; pub(crate) use invoke::graph_dialog; pub use invoke::{click_target, invoke, invoke_from_system_menu}; #[cfg(test)] diff --git a/crates/ui-egui/src/menus/bar.rs b/crates/ui-egui/src/menus/bar.rs index 1fc2f7855c..a0e4e0d6ac 100644 --- a/crates/ui-egui/src/menus/bar.rs +++ b/crates/ui-egui/src/menus/bar.rs @@ -1,4 +1,4 @@ -use super::entries::{Row, entry, pretty_shortcut}; +use super::entries::{Row, entry, shown_shortcut}; use super::invoke::{field_event, focused_text_field, invoke, to_field, with_held_keys}; use super::tree::menu_tree_named; use super::{Entry, Item, Tokens, Value, VectorcraftApp, widgets}; @@ -124,7 +124,7 @@ pub(super) fn render_items(app: &VectorcraftApp, ui: &mut egui::Ui, items: &[Ite /// One menu item: its label (with a check mark, or the room for one, under `checks`), its shortcut, /// and Type › Font's samples. fn render_row(app: &VectorcraftApp, ui: &mut egui::Ui, row: &Row, checks: bool, clicked: &mut Option<(String, Value)>) { - let sc = row.shortcut.map(pretty_shortcut).unwrap_or_default(); + let sc = row.shortcut.map(shown_shortcut).unwrap_or_default(); let Some((id, p)) = row.command else { ui.add_enabled_ui(false, |ui| { ui.add(egui::Button::new(row.label.as_ref()).shortcut_text(sc)); diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index fa78fef80e..e9cfc538a1 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -88,6 +88,12 @@ pub fn pretty_shortcut(s: &str) -> String { } } +/// [`pretty_shortcut`] with the backtick key shown as the character it types on the layout in use +/// (`"` on Turkish Q), as Edit › Keyboard Shortcuts shows it. +pub fn shown_shortcut(s: &str) -> String { + pretty_shortcut(&crate::shortcut_editor::as_typed(s)) +} + #[derive(Serialize)] pub struct MenuEntry { pub path: Vec<String>, diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index f7728f4c33..ec205e4f54 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -115,7 +115,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { for (i, e) in matches.iter().enumerate() { let resp = ui.add( egui::Button::new(e.shown.as_str()) - .shortcut_text(menus::pretty_shortcut(&e.shortcut)) + .shortcut_text(menus::shown_shortcut(&e.shortcut)) .min_size(egui::vec2(500.0, 24.0)) .selected(i == sel), ); diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 4d6164f111..c048421c3d 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -271,6 +271,57 @@ pub fn chord_from_event(key: Key, m: Modifiers) -> Option<String> { crate::shortcuts::parse(&s).map(|_| s) } +ui_mirror!(fn backtick_store() -> Option<String>); + +/// Notes what the backtick key (left of 1) typed in `events`: the one-character text whose key, a +/// press of it without modifiers, comes right before it (egui-winit) or, when no press comes +/// before, right after it (eframe's web build with no text field focused). egui reports that key +/// as [`Key::Backtick`] on layouts where it types a character egui has no key for, such as `"` on +/// Turkish Q. +pub(crate) fn note_backtick_text(events: &[egui::Event]) { + let is_press = |e: Option<&egui::Event>| matches!(e, Some(egui::Event::Key { pressed: true, .. })); + let is_backtick = + |e: Option<&egui::Event>| matches!(e, Some(egui::Event::Key { key: Key::Backtick, pressed: true, modifiers, .. }) if modifiers.is_none()); + let typed = events.iter().enumerate().rev().find_map(|(j, e)| match e { + egui::Event::Text(t) if t.chars().count() == 1 && !t.chars().any(char::is_whitespace) => { + let before = j.checked_sub(1).and_then(|j| events.get(j)); + (is_backtick(before) || (!is_press(before) && is_backtick(events.get(j + 1)))).then(|| t.clone()) + } + _ => None, + }); + if let Some(t) = typed + && let Ok(mut store) = backtick_store().write() + && store.as_deref() != Some(t.as_str()) + { + *store = Some(t); + } +} + +/// The character the backtick key types on the layout in use, once a press of it has been seen, +/// when it is neither `` ` `` nor `~`. +pub(crate) fn backtick_text() -> Option<String> { + backtick_store().read().ok().and_then(|t| t.clone()).filter(|t| t != "`" && t != "~") +} + +/// `text` as the editor shows it: an unshifted backtick key shows the character it types on the +/// layout in use (`"` on Turkish Q), so it reads as the key the user pressed. +fn on_layout(text: String, typed: Option<&str>) -> String { + let Some(typed) = typed else { return text }; + match vc_chord(&text) { + Some(c) if c.key == craft_keymap::Key::Backtick && !c.mods.shift => match text.strip_suffix('~') { + Some(mods) => format!("{mods}{typed}"), + None => text, + }, + _ => text, + } +} + +/// `text` with the backtick key shown as the character it types on the layout in use +/// ([`backtick_text`]), as the editor shows it. +pub(crate) fn as_typed(text: &str) -> String { + on_layout(text.to_string(), backtick_text().as_deref()) +} + // ---------- entries & conflicts ---------- #[derive(Clone, Debug)] @@ -506,15 +557,17 @@ pub fn reset_one(overrides: &mut Overrides, key: &str) { overrides.remove(&crate::keymap::stored_key(key)); } -/// Text shown for all active chords in a dialog row. -fn dialog_shortcuts_with(km: &Keymap, key: &str) -> Option<String> { +/// Text shown for all active chords in a dialog row, with the backtick key shown as `typed` +/// ([`backtick_text`]). +fn dialog_shortcuts_with(km: &Keymap, key: &str, typed: Option<&str>) -> Option<String> { + let shown = |s: String| menus::pretty_shortcut(&on_layout(s, typed)); let bindings = km.bindings(&command_of(key)); if bindings.len() > 1 { - let primary = effective_with(km, key).map(|s| menus::pretty_shortcut(&s))?; - let additional = bindings.iter().skip(1).map(|b| menus::pretty_shortcut(&crate::keymap::binding_text(b))); + let primary = effective_with(km, key).map(shown)?; + let additional = bindings.iter().skip(1).map(|b| shown(crate::keymap::binding_text(b))); return Some(std::iter::once(primary).chain(additional).collect::<Vec<_>>().join(" · ")); } - effective_with(km, key).map(|s| menus::pretty_shortcut(&s)) + effective_with(km, key).map(shown) } /// Overrides of a preset (both presets are the registry defaults for now). @@ -698,6 +751,8 @@ pub fn is_recording(app: &VectorcraftApp) -> bool { struct DialogView { /// The dialog's `overrides` field this was built from. source: Value, + /// The [`backtick_text`] the texts show. + backtick: Option<String>, keymap: Keymap, texts: Vec<Option<String>>, conflicts: usize, @@ -706,17 +761,19 @@ struct DialogView { impl DialogView { fn new(overrides: Overrides) -> DialogView { let keymap = keymap_with(&overrides); - let texts = entries().iter().map(|e| dialog_shortcuts_with(&keymap, &e.key)).collect(); + let backtick = backtick_text(); + let texts = entries().iter().map(|e| dialog_shortcuts_with(&keymap, &e.key, backtick.as_deref())).collect(); let conflicts = conflicts_in(&keymap).len(); - DialogView { source: stored::to_value(keymap.overrides()), keymap, texts, conflicts } + DialogView { source: stored::to_value(keymap.overrides()), backtick, keymap, texts, conflicts } } - /// The view of `d`'s working set, from the cache unless the set changed. The dialog's - /// `overrides` field is left in its stored form. + /// The view of `d`'s working set, from the cache unless the set or the backtick key's + /// character changed. The dialog's `overrides` field is left in its stored form. fn of(ctx: &egui::Context, d: &mut Dialog) -> Arc<DialogView> { let id = egui::Id::unique("dialog-shortcuts-view"); let source = d.fields.get("overrides").unwrap_or(&Value::Null); - if let Some(v) = ctx.data(|m| m.get_temp::<Arc<DialogView>>(id)).filter(|v| v.source == *source) { + let backtick = backtick_text(); + if let Some(v) = ctx.data(|m| m.get_temp::<Arc<DialogView>>(id)).filter(|v| v.source == *source && v.backtick == backtick) { return v; } let v = Arc::new(DialogView::new(dialog_overrides(d))); @@ -729,6 +786,7 @@ impl DialogView { pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(mut d) = app.ui.dialog.clone() else { return }; let t = Tokens::get(ctx); + ctx.input(|i| note_backtick_text(&i.events)); // The working set, as a keymap: copied only by an edit this frame. let view = DialogView::of(ctx, &mut d); let mut km = Cow::Borrowed(&view.keymap); @@ -823,7 +881,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { for (i, e) in entries().iter().enumerate().filter(|(_, e)| e.is_tool == tools && listed(km.overrides(), e)) { let sc = match &km { Cow::Borrowed(_) => view.texts.get(i).cloned().flatten(), - Cow::Owned(km) => dialog_shortcuts_with(km, &e.key), + Cow::Owned(km) => dialog_shortcuts_with(km, &e.key, view.backtick.as_deref()), }; let matches = e.label.to_lowercase().contains(&q) || tl!(&e.label).to_lowercase().contains(&q) @@ -1010,7 +1068,10 @@ fn record(d: &mut Dialog, km: &mut Keymap, key: &str, chord: &str) { "__message".into(), json!(crate::i18n::fmt( tl!("⚠ {chord} was already used by {names} — it has been removed there."), - &[("chord", &menus::pretty_shortcut(chord)), ("names", &names.join(", "))] + &[ + ("chord", &menus::pretty_shortcut(&on_layout(chord.to_string(), backtick_text().as_deref()))), + ("names", &names.join(", ")) + ] )), ); d.fields.insert("__conflict".into(), json!(first)); @@ -1126,6 +1187,60 @@ mod tests { assert_eq!(crate::keymap::override_text(&dialog_overrides(&d), "tool:groupSelection").as_deref(), Some("Shift+A")); } + /// On Turkish Q the key left of 1 types `"`, which egui reports as the backtick key: the + /// recorded shortcut is that key, saved as `~` as before, and its row shows `"`. On a US + /// layout the row still shows `~`. + #[test] + fn the_backtick_key_shows_what_it_types() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + open(&mut app); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + let at = entries().iter().position(|e| e.key == "edit.clear").unwrap(); + let press = |key| egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: Modifiers::NONE }; + let text = |t: &str| egui::Event::Text(t.into()); + let mut record_with = |events: Vec<egui::Event>| { + app.ui.dialog.as_mut().unwrap().fields.insert("__recording".into(), json!("edit.clear")); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(&mut app, ui.ctx())); + out.textures_delta.clear(); + let d = app.ui.dialog.clone().unwrap(); + let shown = DialogView::new(dialog_overrides(&d)).texts[at].clone(); + (crate::keymap::override_text(&dialog_overrides(&d), "edit.clear"), shown) + }; + assert_eq!(record_with(vec![press(Key::Backtick), text("\"")]), (Some("~".to_string()), Some("\"".to_string()))); + assert_eq!(record_with(vec![press(Key::Backtick), text("`")]), (Some("~".to_string()), Some("~".to_string()))); + // eframe's web build with no text field focused sends the text before its key. + assert_eq!(record_with(vec![text("\""), press(Key::Backtick)]), (Some("~".to_string()), Some("\"".to_string()))); + // A text right after another key's press is that key's. + note_backtick_text(&[press(Key::Num2), text("'"), press(Key::Backtick)]); + assert_eq!(backtick_text().as_deref(), Some("\"")); + note_backtick_text(&[text("`"), press(Key::Backtick)]); + assert_eq!(backtick_text(), None); + // Only the unshifted key types that character. + assert_eq!(on_layout("Shift+~".into(), Some("\"")), "Shift+~"); + assert_eq!(on_layout("Cmd+~".into(), Some("\"")), "Cmd+\""); + assert_eq!(on_layout("Cmd+K".into(), Some("\"")), "Cmd+K"); + } + + #[test] + fn menus_and_tooltips_show_the_backtick_key_as_it_types() { + let mut ui = UiState::default(); + crate::keymap::set_override(&mut ui.shortcut_overrides, "edit.clear", "Cmd+~"); + crate::keymap::set_override(&mut ui.shortcut_overrides, "tool:measure", "~"); + sync(&ui); + let measure = vectorcraft_tools::tool_info("measure").unwrap(); + let press = |key| egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: Modifiers::NONE }; + let clear = || menus::shown_shortcut(menus::shortcut_of("edit.clear").unwrap()); + note_backtick_text(&[press(Key::Backtick), egui::Event::Text("`".into())]); + assert_eq!(clear(), menus::pretty_shortcut("Cmd+~")); + assert!(crate::toolbar::tip(measure).ends_with("(~)")); + note_backtick_text(&[press(Key::Backtick), egui::Event::Text("\"".into())]); + assert_eq!(clear(), menus::pretty_shortcut("Cmd+\"")); + assert!(crate::toolbar::tip(measure).ends_with("(\")"), "{}", crate::toolbar::tip(measure)); + assert_eq!(menus::shown_shortcut("Shift+~"), menus::pretty_shortcut("Shift+~")); + sync(&UiState::default()); + } + #[test] fn saved_modifier_only_overrides_give_the_default_back() { let mut ui = UiState::default(); diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index cb66d71c1d..e8e5d07fed 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -169,6 +169,7 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { if !crate::take_frame_once(&mut app.shortcuts_frames, frame) { return; } + ctx.input(|i| crate::shortcut_editor::note_backtick_text(&i.events)); if !(ctx.input(|input| input.focused) || app.forwarded_frame && ctx.viewport_id() == egui::ViewportId::ROOT) { crate::ime::controls_without_editor(app, ctx); return; @@ -357,25 +358,26 @@ fn remember_escape_pair(ctx: &egui::Context, key: Key, escape_pair: Option<bool> fn single_key_shortcuts(app: &mut VectorcraftApp, ctx: &egui::Context) { // Single-key tool shortcuts (no Cmd/Ctrl/Alt). With a layout without Latin letters (Persian, // Arabic, Russian, Greek…) the key's position stands in for what it types (#793). - let events: Vec<(String, Modifiers)> = ctx.input(|i| { + // A text's key is the press that typed it ([`typing_presses`]). + let events: Vec<(String, Modifiers, Option<Key>)> = ctx.input(|i| { let typed_by = typing_presses(&i.events); i.events .iter() .zip(typed_by) .filter_map(|(e, by)| match e { egui::Event::Text(t) => { - let physical = match by.and_then(|k| i.events.get(k)) { - Some(egui::Event::Key { physical_key, .. }) => *physical_key, - _ => None, + let (physical, key) = match by.and_then(|k| i.events.get(k)) { + Some(egui::Event::Key { key, physical_key, .. }) => (*physical_key, Some(*key)), + _ => (None, None), }; - Some((latin(t, physical), i.modifiers)) + Some((latin(t, physical), i.modifiers, key)) } _ => None, }) .collect() }); let keymap = crate::shortcut_editor::current(); - for (text, m) in events { + for (text, m, pressed) in events { if m.command || m.alt || m.ctrl { continue; } @@ -384,11 +386,15 @@ fn single_key_shortcuts(app: &mut VectorcraftApp, ctx: &egui::Context) { // A shifted punctuation character can also be written with its Shift (the Curvature tool's // Shift+~ arrives as `~`). let shifted = m.shift.then(|| format!("Shift+{text}")); - let hits: Vec<CommandRef> = [Some(key), Some(text), shifted] - .into_iter() - .flatten() - .filter_map(|t| crate::keymap::vc_chord(&t).and_then(|c| crate::keymap::lookup(&keymap.keymap, &c))) - .collect(); + let mut chords: Vec<craft_keymap::Chord> = + [Some(key), Some(text), shifted].into_iter().flatten().filter_map(|t| crate::keymap::vc_chord(&t)).collect(); + // A character no chord names (`"`, which the backtick key types on Turkish Q) is read as + // the key that typed it, as the Keyboard Shortcuts editor records that press. + if chords.is_empty() { + let typed_by = pressed.and_then(|k| crate::shortcut_editor::chord_from_event(k, Modifiers { shift: m.shift, ..Modifiers::NONE })); + chords.extend(typed_by.and_then(|t| crate::keymap::vc_chord(&t))); + } + let hits: Vec<CommandRef> = chords.iter().filter_map(|c| crate::keymap::lookup(&keymap.keymap, c)).collect(); // Single-key command shortcuts (X, Shift+X, D, /, Shift+D, F, Shift+F by default) before // tools. let Some(hit) = hits.iter().find(|c| !c.id.starts_with("tool:")).or(hits.first()) else { continue }; diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index c5005fba9d..38365f5ed1 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1744,6 +1744,55 @@ fn a_repeated_keys_text_is_no_shortcut_press() { assert_eq!(only_text.len(), 1); } +/// A shortcut on the backtick key runs whatever character the key types: `"` on Turkish Q, +/// which egui reports as the backtick key, and `` ` `` on a US layout. A shortcut saved as `~` +/// is that key's. +#[test] +fn a_shortcut_on_the_backtick_key_runs_on_every_layout() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let recorded = crate::shortcut_editor::chord_from_event(Key::Backtick, Modifiers::NONE).unwrap(); + assert_eq!(recorded, "~"); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.clear", "~"); + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let press = egui::Event::Key { key: Key::Backtick, physical_key: Some(Key::Backtick), pressed: true, repeat: false, modifiers: Modifiers::NONE }; + for typed in ["\"", "`"] { + let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + assert_eq!(count(&app), 1); + frame(&mut app, vec![press.clone(), egui::Event::Text(typed.into())]); + assert_eq!(count(&app), 0, "the key typing {typed} runs Edit › Clear"); + } + // A character no key names, typed by a key with no shortcut, runs nothing. + let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let num2 = egui::Event::Key { key: Key::Num2, physical_key: Some(Key::Num2), pressed: true, repeat: false, modifiers: Modifiers::NONE }; + frame(&mut app, vec![num2, egui::Event::Text("\"".into())]); + assert_eq!(count(&app), 1); +} + +/// eframe's web build with no text field focused sends the text before its key: the key after +/// the `"` it typed is read when no press comes right before it. +#[test] +fn a_shortcut_on_the_backtick_key_runs_when_its_text_comes_first() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.clear", "~"); + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let press = egui::Event::Key { key: Key::Backtick, physical_key: Some(Key::Backtick), pressed: true, repeat: false, modifiers: Modifiers::NONE }; + let select_new = |app: &mut VectorcraftApp| { + let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + }; + select_new(&mut app); + frame(&mut app, vec![egui::Event::Text("\"".into()), press.clone()]); + assert_eq!(count(&app), 0, "the key after the text typed it"); + // An earlier press that is not next to the text does not stand in for its key. + select_new(&mut app); + frame(&mut app, vec![press, egui::Event::ModifiersChanged(Modifiers::NONE), egui::Event::Text("\"".into())]); + assert_eq!(count(&app), 1); +} + /// Shortcuts reach tools, panels (`window.panel {panel}`) and commands through the keymap, /// and a held Cmd+= keeps zooming in. #[test] diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 33a2eb10b8..32c2ad971a 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -68,7 +68,7 @@ pub const BASIC: &[(&str, &[&[&str]])] = &[ pub(crate) fn tip(t: &ToolInfo) -> String { match crate::shortcut_editor::tool_shortcut(t.id) { - Some(s) => format!("{} ({})", tl!(t.label), s), + Some(s) => format!("{} ({})", tl!(t.label), crate::shortcut_editor::as_typed(s)), None => tl!(t.label).to_string(), } } @@ -694,7 +694,10 @@ const ROW_END: f32 = 18.0; /// The name of `tool` in `lang` and its shortcut in brackets, as a flyout row draws them. fn row_text(ui: &Ui, lang: crate::i18n::Lang, tool: &ToolInfo, color: Color32) -> RowText { let lay = |s: String| ui.painter().layout_no_wrap(s, egui::FontId::proportional(13.0), color); - (lay(crate::i18n::tr(lang, tool.label).to_string()), crate::shortcut_editor::tool_shortcut(tool.id).map(|sc| lay(format!("({sc})")))) + ( + lay(crate::i18n::tr(lang, tool.label).to_string()), + crate::shortcut_editor::tool_shortcut(tool.id).map(|sc| lay(format!("({})", crate::shortcut_editor::as_typed(sc)))), + ) } /// The width of a flyout's rows: 250 pt, or what its longest name needs to stay clear of its diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2f6ee32b76..5d1ce531d2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -633,6 +633,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Shortcut sets other apps save as text (`.kys`) open in Import Shortcut Set from File › Open, from Edit › Keyboard Shortcuts › Import… in the desktop app, or from a drop on the window. It matches each entry to a tool, command or panel by name and decodes the file's key and modifier codes where VectorCraft's default shortcuts agree on them; the user answers the rest, and Apply fills the Keyboard Shortcuts dialog's working set. The answers are kept with the preferences for the next import (`shortcutSet.read`, `importMatches.*`). - On Windows and Linux the app bar is the window's title bar (its own minimize, maximize and close buttons, drag to move, edges to resize), with the dragon app icon as the brand mark; dialogs and menus size to their content. As on a native menu bar, once one menu is open, moving the pointer onto another title opens that one. - Edit › Keyboard Shortcuts lists items of the menu bar and panel menus, as the reference app's [Customize keyboard shortcuts](https://web.archive.org/web/20221205131209id_/https://helpx.adobe.com/illustrator/using/customizing-keyboard-shortcuts.html) page describes for its Menu Commands. A menu command with no default shortcut that needs a value a key press does not give, such as File › Document Setup › Units (`document.setUnits {units}`), is listed only while the user has changed its shortcut. A command stays listed when a menu bar item runs it without a value or when it opens a dialog run without one, as the Variables panel's commands do. + - A shortcut on the key left of 1 runs whatever character that key types, and Edit › Keyboard Shortcuts, the menus in the window, the command palette and tool tips show it as that character once the key has been pressed: `"` on a Turkish Q layout, `~` on a US layout as before. Shortcuts saved as `~` keep working (#4559). - On Windows a maximized window stays inside the work area with the taskbar on any edge (#3242, #3723). - On Windows a maximized window stops one pixel short of each monitor edge where an auto-hidden taskbar sits. - **Tools:** From a1a3a9910450addaefdaffe7b0de8c83ca274e80 Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:00:19 +0430 Subject: [PATCH 050/260] Fix #3592: a gradient mesh from a file is budgeted at about a million quads A mesh read from a file can have any number of patches, and the view any zoom: a 150 x 150 mesh from a 3 MB file exported at 20x asked for about 23 million quads (2 GB), and the command's own cap of 50 rows and columns does not apply to a loaded one. One tessellation now makes at most 1,048,576 quads, the subdivision per patch giving way before that, and a mesh with more patches than that is malformed, like a point count that does not fit. --- crates/doc/src/live.rs | 23 +++++++++++++++++++++++ crates/doc/src/live/mesh.rs | 18 +++++++++++++++--- docs/gaps.md | 9 ++++++++- docs/target-app-parity.md | 3 ++- 4 files changed, 48 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 6a29b5b9ef..258035c10f 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -181,6 +181,29 @@ mod tests { assert!((p.x - 37.0).abs() < 1e-6 && (p.y - 81.0).abs() < 1e-6, "{p:?}"); } + /// #3592: a mesh read from a file can have any number of patches, and the view any zoom, so the + /// quads one tessellation makes are budgeted: the subdivision per patch gives way before memory + /// does, and each patch stays at least one quad. + #[test] + fn a_large_mesh_tessellates_within_the_quad_budget() { + let mesh = |n: u32| GradientMesh::from_surface(n, n, &|u, v| Point::new(u * 300.0, v * 300.0), &|u, v| Color::rgb(u as f32, v as f32, 0.5)); + // 3,600 patches at 32 x 32 would be 3.7 million quads. + let m = mesh(60); + let quads = m.quads(32); + assert!(quads.len() <= GradientMesh::MAX_QUADS, "{} quads", quads.len()); + assert!(quads.len() >= 3600 * 4, "still finer than a quad per patch: {}", quads.len()); + // A small mesh keeps the subdivision asked for. + assert_eq!(mesh(3).quads(8).len(), 9 * 64); + // The finest the view asks for, on a mesh of 22,500 patches, is a few quads per patch. + let big = mesh(150).quads(64); + assert!(big.len() <= GradientMesh::MAX_QUADS && big.len() >= 22_500, "{} quads", big.len()); + // More patches than the budget has quads is malformed, as a point count that doesn't fit is. + let point = MeshPoint { p: Point::ZERO, color: Color::rgb(0.0, 0.0, 0.0), opacity: 1.0, handles: [Vec2::ZERO; 4] }; + let huge = GradientMesh { rows: 2000, cols: 2000, points: vec![point; 2001 * 2001] }; + assert!(!huge.is_valid()); + assert!(huge.quads(1).is_empty()); + } + /// A file's rows and columns can be anything: a point count too large to compute is no match /// for the points (u32::MAX × u32::MAX wrapped to 0 and passed for a grid without points). #[test] diff --git a/crates/doc/src/live/mesh.rs b/crates/doc/src/live/mesh.rs index dbbfc66bdd..e86eecff9d 100644 --- a/crates/doc/src/live/mesh.rs +++ b/crates/doc/src/live/mesh.rs @@ -170,11 +170,22 @@ pub(super) fn grid_len(rows: u32, cols: u32) -> Option<usize> { } impl GradientMesh { + /// The most quads one tessellation ([`Self::quads`]) makes, and so the most patches a mesh can + /// have: about 170 bytes a quad, so about 170 MB. A file's mesh can have any number of patches + /// and the view any zoom; the subdivision per patch gives way before memory does, and a mesh + /// with more patches than that is malformed, like a point count that doesn't fit (#3592). + pub const MAX_QUADS: usize = 1 << 20; + pub fn idx(&self, r: usize, c: usize) -> usize { r * (self.cols as usize + 1) + c } pub fn is_valid(&self) -> bool { - self.rows >= 1 && self.cols >= 1 && grid_len(self.rows, self.cols) == Some(self.points.len()) + self.rows >= 1 && self.cols >= 1 && grid_len(self.rows, self.cols) == Some(self.points.len()) && self.patches() <= Self::MAX_QUADS + } + + /// The number of patches (rows times columns), saturating. + fn patches(&self) -> usize { + (self.rows as usize).saturating_mul(self.cols as usize) } /// A 1×1 mesh from its four corners (bottom-left, top-left, top-right, bottom-right in u/v @@ -352,8 +363,9 @@ impl GradientMesh { if !self.is_valid() { return vec![]; } - let n = n.clamp(1, 64); - let mut out = Vec::with_capacity(self.rows as usize * self.cols as usize * n * n); + // Finer than the budget allows gives way: a quad per patch is the least. + let n = n.clamp(1, 64).min(((Self::MAX_QUADS / self.patches()) as f64).sqrt() as usize).max(1); + let mut out = Vec::with_capacity(self.patches() * n * n); let mut grid = vec![Point::ZERO; (n + 1) * (n + 1)]; let mut colors = vec![(Color::default(), 0.0f32); (n + 1) * (n + 1)]; for r in 0..self.rows as usize { diff --git a/docs/gaps.md b/docs/gaps.md index 1fb18246a5..646ffa8648 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (G13: gradient presets done; G1: Average & Join with a corner or smooth choice, Cmd+Alt+Shift+J, done; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G8: a gradient mesh from a file is budgeted at about a million patches and quads, #3592; estimate unchanged; previously: G13: gradient presets done; G1: Average & Join with a corner or smooth choice, Cmd+Alt+Shift+J, done; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -224,6 +224,12 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall taken whole or not at all, and the walk that counts an art tile's anchors charges the whole budget for a tree it cannot finish, so nesting buys no room (#3594). The budget is per brushed stroke, not per document: many strokes that each reach it still add up, and a brush inside a symbol is bounded per stroke rather than per instantiation. +- **Done (2026-10-31):** a gradient mesh is budgeted (#3592). One tessellation makes at most 1,048,576 quads, and a + mesh with more patches than that (rows times columns) is malformed, like a point count that doesn't fit, so it draws + nothing instead of exhausting memory: a 150 x 150 mesh from a 3 MB file exported at 20x asked for about 23 million + quads (2 GB). Below the budget the subdivision per patch gives way a step at a time (a 60 x 60 mesh draws at 16 x 16 + quads a patch instead of 32 x 32); a small mesh is drawn as finely as before. The command's own cap of 50 rows and + columns is unchanged. - **Done (2026-10-29):** a blend makes at most 100,000 steps in all, counting the steps of the blends inside its keys and steps. Each step between keys that are blends is a copy of one, which makes its own steps when drawn, so step counts capped at 1,000 a pair multiplied by nesting: five levels of 15 steps were 1.3 million steps from a 23 KB @@ -660,6 +666,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | G8: a gradient mesh read from a file is budgeted: at most about a million quads per tessellation, and a mesh with more patches than that is malformed (#3592); estimate unchanged. | | 2026-10-30 | minor | G9: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | | 2026-10-30 | minor | G1: Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J) moves two open path ends to their midpoint and joins them there, the joined anchor a corner or a smooth point as its dialog's Points choice asks, in one undo step; the "Average and Join in one step" entry is done. Estimate unchanged | | 2026-10-30 | minor | G12: Preferences audit (#394): 5 options are stored but not acted on (Open Documents As Tabs, Units › East Asian Type, Hyphenation › Default Language, Scratch Disks, Legacy vector clipboard), each waiting on a subsystem; Highlight Alternate Glyphs, Real-time Drawing and the Devices options act. Estimate unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5d1ce531d2..a871b67478 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Path Precision Tools add-on: Shared Edge Merge Tool; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G8: a gradient mesh from a file is budgeted, #3592; scores unchanged; previously: Path Precision Tools add-on: Shared Edge Merge Tool; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -19,6 +19,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Hardening: a gradient mesh read from a file is budgeted at about a million quads, so a huge one no longer exhausts memory when drawn or exported (#3592); scores unchanged. | | 2026-10-30 | minor | File formats: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | | 2026-10-30 | minor | File formats: `.ai`/EPS editing-data fidelity from an audit of a user's files: All Caps and Small Caps (#4708); placed files at their box's corner, kept where they draw closer to the page (#4664, #4723, #4742); pages cropped to the art, with `UserUnit` (#4658, #4727); gradient mesh corners with handle weights of 0 and the state written after a mesh (#4738, #4744, #4748); type on a path spaced as the file lays it out (#4743); synthetic regressions in `crates/eps`; evidence added; scores unchanged. | | 2026-10-30 | minor | Effects: bounded length inputs clamp on commit and reject invalid text visibly (#4638); scores unchanged. | From 2c28ccf0207ad5e70b8f755227616ac216b53149 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 18:55:28 +0700 Subject: [PATCH 051/260] Gradient mesh: flat pieces follow the quad budget's subdivision A mesh over the quad budget is cut coarser than asked (#3592); its flat pieces now use the same subdivision, so each patch takes its own quads. --- crates/doc/src/live.rs | 15 +++++++++++++++ crates/doc/src/live/mesh.rs | 14 ++++++++++---- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 102a614b93..1b234c2122 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -204,6 +204,21 @@ mod tests { assert!(huge.quads(1).is_empty()); } + /// Flat pieces of a mesh over the quad budget follow the coarser subdivision [`GradientMesh::quads`] + /// gives way to: each patch's pieces are its own quads', so together they cover the mesh once. + #[test] + fn a_large_meshs_pieces_follow_the_quad_budget() { + let m = GradientMesh::from_surface(60, 60, &|u, v| Point::new(u * 300.0, v * 300.0), &|u, v| Color::rgb(u as f32, v as f32, 0.5)); + let area = |pts: &[Point]| { + let n = pts.len(); + (0..n).map(|i| pts[i].x * pts[(i + 1) % n].y - pts[(i + 1) % n].x * pts[i].y).sum::<f64>().abs() / 2.0 + }; + let pieces = m.pieces(32); + assert!(pieces.len() >= 3600, "{} pieces", pieces.len()); + let total: f64 = pieces.iter().map(|p| area(&p.pts)).sum(); + assert!((total - 90_000.0).abs() < 90.0, "covered {total}"); + } + /// A file's rows and columns can be anything: a point count too large to compute is no match /// for the points (u32::MAX × u32::MAX wrapped to 0 and passed for a grid without points). #[test] diff --git a/crates/doc/src/live/mesh.rs b/crates/doc/src/live/mesh.rs index 10540266a3..f72dd548cc 100644 --- a/crates/doc/src/live/mesh.rs +++ b/crates/doc/src/live/mesh.rs @@ -367,13 +367,19 @@ impl GradientMesh { (Color::rgb(rgb[0], rgb[1], rgb[2]), op) } - /// Tessellate into `n`×`n` quads per patch, each coloured at its centre and its corners. + /// The quads per patch side [`Self::quads`] cuts at when `n` is asked: 1 to 64, and coarser + /// where the patches at `n` would pass [`Self::MAX_QUADS`] (a quad per patch is the least). + fn subdivision(&self, n: usize) -> usize { + n.clamp(1, 64).min(((Self::MAX_QUADS / self.patches().max(1)) as f64).sqrt() as usize).max(1) + } + + /// Tessellate into `n`×`n` quads per patch ([`Self::subdivision`]), each coloured at its centre + /// and its corners. pub fn quads(&self, n: usize) -> Vec<MeshQuad> { if !self.is_valid() { return vec![]; } - // Finer than the budget allows gives way: a quad per patch is the least. - let n = n.clamp(1, 64).min(((Self::MAX_QUADS / self.patches()) as f64).sqrt() as usize).max(1); + let n = self.subdivision(n); let mut out = Vec::with_capacity(self.patches() * n * n); let mut grid = vec![Point::ZERO; (n + 1) * (n + 1)]; let mut colors = vec![(Color::default(), 0.0f32); (n + 1) * (n + 1)]; @@ -411,7 +417,7 @@ impl GradientMesh { /// all its quads. A piece's outline runs through its quads' outer corners, so it covers what /// they covered, and it takes the colour at its centre. pub fn pieces(&self, n: usize) -> Vec<MeshPiece> { - let n = n.clamp(1, 64); + let n = self.subdivision(n); let quads = self.quads(n); let cols = (self.cols as usize).max(1); let mut out = Vec::with_capacity(quads.len()); From 59eb658fd7176a852e3d6f1b00d73e697dc5dcd4 Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:24:26 +0430 Subject: [PATCH 052/260] Fix #2651: Grid Repeat Options has a Preview checkbox The grid options' public page lists a Preview option: the repeat on the canvas follows the fields while the dialog is open. Object > Repeat > Options had none, so a change showed only after OK. Now a Grid Repeat's dialog has the checkbox: Cancel puts the original back without a history step, OK keeps the previewed values as one undo step. Radial and Mirror Repeat Options are left as they are, since their public pages list no Preview. --- crates/ui-egui/src/dialogs.rs | 5 +- crates/ui-egui/src/dialogs/command.rs | 110 ++++++++++++++++++++++++-- docs/gaps.md | 4 +- docs/target-app-parity.md | 3 +- docs/ui-parity.md | 4 +- 5 files changed, 115 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index ba85dc4a25..acbad17508 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -468,9 +468,10 @@ pub fn cancel(app: &mut VectorcraftApp) { missing_fonts::requeue_replaced(app); if let Some(d) = app.ui.dialog.take() { // Toolbar-only Flare options start no preview and must not cancel a gesture - // that was already active before opening them. + // that was already active before opening them. The generic parameter dialog has a spec + // without a preview, yet previews some commands (Grid Repeat Options) when asked to. let owns_preview = d.kind != flare_options::KIND || d.fields.contains_key(form::PREVIEWED); - if spec(&d.kind).preview && owns_preview { + if (spec(&d.kind).preview && owns_preview) || d.fields.contains_key(form::PREVIEWED) { let _ = app.session.cancel_interaction(); } app.ui.dialog = parent(&d); diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 3ebefdc211..89ef90c883 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -16,13 +16,33 @@ pub(super) const SPEC: DialogSpec = DialogSpec { let (lengths, order) = (lengths(&command), order(&command)); let rank = |k: &str| order.iter().position(|o| *o == k).unwrap_or(order.len()); form::param_fields(ui, d, &|k| lengths.contains(&k), &|k| choices(&command, k), &rank, app.session.general_unit()); + if previews(d) { + let (cmd, params) = call(d); + form::preview(app, ui, d, &d.str("__label"), &cmd, params); + } false }, confirm, - passes: takes, + passes: |d, key| takes(d, key) || (key == "preview" && previews(d)), ..DialogSpec::FORM }; +/// Does this dialog show a Preview checkbox? Only Grid Repeat Options does: the public page for +/// the grid options lists one, and the radial and mirror pages do not. (Cancel rolls a preview +/// back whichever dialog started it.) +fn previews(d: &Dialog) -> bool { + d.str("__command") == "object.repeat.options" && d.fields.contains_key("gridType") +} + +/// The command the dialog runs and its parameters: the fields shown and the fixed ones. +fn call(d: &Dialog) -> (String, Value) { + let mut params = form::params(d); + if let (Some(o), Some(Value::Object(fixed))) = (params.as_object_mut(), d.fields.get("__params")) { + o.extend(fixed.clone()); + } + (d.str("__command"), params) +} + /// Does the dialog's command take parameter `key` (its params description names it)? fn takes(d: &Dialog, key: &str) -> bool { let id = d.str("__command"); @@ -100,12 +120,12 @@ const PIE_SORT: form::Choices = &[("All", "all"), ("First", "first"), ("None", " /// Graph Type › Tick Marks › Length. const GRAPH_TICK_LENGTH: form::Choices = &[("None", "none"), ("Short", "short"), ("Full Width", "full")]; -/// Closes before running, so a dialog the command opens stays open. +/// Closes before running, so a dialog the command opens stays open. A previewed one keeps its +/// preview as the one undo step. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { - let cmd = d.str("__command"); - let mut params = form::params(d); - if let (Some(o), Some(Value::Object(fixed))) = (params.as_object_mut(), d.fields.get("__params")) { - o.extend(fixed.clone()); + let (cmd, params) = call(d); + if previews(d) { + return form::commit_preview(app, &cmd, params); } app.ui.dialog = None; // A tool's click-to-size shape (Flare) goes on the active perspective plane while the grid shows. @@ -192,4 +212,82 @@ mod tests { assert_eq!(app.session.execute("graph.setType", &json!({})).unwrap()["type"], "stackedBar"); assert_eq!(app.session.execute("graph.setData", &json!({})).unwrap(), data); } + + /// A document with a rectangle made a 2 x 2 Grid Repeat and selected, its Repeat Options + /// dialog open. + fn grid_options_app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("object.repeat.grid", json!({"ids": [id], "rows": 2, "cols": 2})).unwrap(); + crate::menus::invoke(&mut app, "object.repeat.options", json!({})); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, "command"); + app + } + + /// One headless frame of the open dialog. + fn frame(app: &mut VectorcraftApp) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + } + + fn cols(app: &VectorcraftApp) -> u64 { + crate::panels::pattern_options::repeat_fields(app).unwrap()["cols"].as_u64().unwrap() + } + + /// #2651: the grid options' public page lists a Preview checkbox: with it on, the repeat on + /// the canvas follows the fields while the dialog is open; Cancel puts it back without a + /// step of history; OK keeps what was previewed as one step. + #[test] + fn grid_repeat_options_preview_on_the_canvas() { + let mut app = grid_options_app(); + let steps = app.session.doc().unwrap().history.undo.len(); + // Off: the fields change nothing until OK. + app.ui.dialog.as_mut().unwrap().fields.insert("cols".into(), json!(3)); + frame(&mut app); + assert_eq!(cols(&app), 2, "no preview without the checkbox"); + // On, the repeat follows the fields. + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + frame(&mut app); + assert_eq!(cols(&app), 3, "the canvas shows 3 columns while the dialog is open"); + app.ui.dialog.as_mut().unwrap().fields.insert("cols".into(), json!(4)); + frame(&mut app); + assert_eq!(cols(&app), 4, "and follows the next edit"); + // Cancel puts the original back and leaves no history. + crate::dialogs::cancel(&mut app); + assert_eq!(cols(&app), 2, "Cancel restores the original repeat"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps, "and adds no undo step"); + assert!(!app.session.in_interaction()); + // OK keeps the previewed values as one undo step. + crate::menus::invoke(&mut app, "object.repeat.options", json!({})); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("cols".into(), json!(5)); + crate::dialogs::set_field(d, "preview".into(), json!(true)); + frame(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(cols(&app), 5); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(cols(&app), 2, "one Undo takes the whole change back"); + } + + /// Radial and Mirror Repeat Options have no Preview (their public pages list none): their + /// fields apply on OK only, and the dialog takes no `preview`. + #[test] + fn radial_repeat_options_have_no_preview() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("object.repeat.radial", json!({"ids": [id], "instances": 4})).unwrap(); + crate::menus::invoke(&mut app, "object.repeat.options", json!({})); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(!crate::dialogs::accepts_field(d, "preview")); + app.ui.dialog.as_mut().unwrap().fields.insert("instances".into(), json!(7)); + frame(&mut app); + assert_eq!(crate::panels::pattern_options::repeat_fields(&app).unwrap()["instances"], 4); + assert!(!app.session.in_interaction()); + } } diff --git a/docs/gaps.md b/docs/gaps.md index 646ffa8648..608779f7af 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G8: a gradient mesh from a file is budgeted at about a million patches and quads, #3592; estimate unchanged; previously: G13: gradient presets done; G1: Average & Join with a corner or smooth choice, Cmd+Alt+Shift+J, done; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G1: Grid Repeat Options has a Preview checkbox, #2651; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -94,6 +94,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done:** the Properties panel has the additional contextual controls of the public Properties panel overview: Blend Options in Quick Actions for one blend with the Blend tool, Merge Live Paint for a Live Paint group selected with more paths to merge (Live Paint Make and Merge refuse type, images and other objects that aren't paths, which used to vanish among the group's sources), the Width Profile list in Appearance with the Width tool or a variable-width stroke, an applied effect's Delete icon beside fx (with several effects it opens the Appearance panel), and Corner and Corner Radius for corners selected with Direct Selection (public doc cited in target-app-parity.md). Broader G1 estimates unchanged. - **Done (#2691):** a selected Grid Repeat ([public page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html)) shows a handle below the grid, one right of it and one past its bottom-right corner: dragging them adds or removes rows, columns or both (1 to 500). A slider between the first two columns and one between the first two rows set the horizontal and vertical spacing, staying halfway across the gap under the pointer. Each drag is one undo step through `object.repeat.options` and Escape cancels it; the controls hide with the edges or the bounding box, and bounding-box handles keep priority where they meet. Radial Repeat handles remain. Estimates unchanged. +- **Done (#2651):** Object › Repeat › Options… for a Grid Repeat has a Preview checkbox ([public page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html)): while it is on the repeat on the canvas follows the fields, Cancel puts the original back without a history step and OK keeps the previewed values as one undo step. Radial and Mirror Repeat Options have none, as their public pages list none. Estimate unchanged. - **Done (#2877):** a selected Mirror Repeat shows its axis: drag the line or the center handle to move it, an end handle to rotate it (Shift: 45°); each drag is one undo step and Escape cancels it. Bounding-box handles take priority over the axis line; the center and end handles keep their actions. Broader G1 estimates unchanged. - **Existing-guide Escape cancellation:** Selection and Direct/Group Selection clear pending presses and cancel begun guide previews. App-input regressions cover preselected-guide document and interaction-start selection restoration, Undo/Redo and saved state, and later on-canvas motion/release. All eight app-input checks and the Direct Selection Escape control passed in current full CI; [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area). The broader G1 scope and estimate remain unchanged. @@ -677,6 +678,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | 2026-10-26 | minor | G9: EPS save-back: an opened EPS saves back to its own path as EPS, keeping the chosen artboard's page frame and transparent margins and the complete editable VectorCraft document; Save's TIFF preview is capped at 1024 px (Export keeps 2048); partly read, preview-only or damaged-editing-data sources still need confirmation before they are overwritten. This narrows G9's save-back workflow only; its import-fidelity items (layer and group structure, guides, open speed, live objects) and estimate are unchanged, and writing Illustrator's own editing data stays out of scope (#868) | | 2026-10-26 | minor | G7: View › New View… / Edit Views… ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)): the View menu lists every one of a document's 25 saved views (it listed 10), Edit Views… lists them to rename or delete in one undo step (`view.saved.edit {edits}`), and a file's views are checked when it opens; New View/Edit Views leave G7's missing list; estimate unchanged | | 2026-10-25 | minor | G4: a double-click on a threaded port with the Selection tool breaks the thread there (`text.thread.break {id, port}`): the story flows into the frames before the break, the frames after it are left empty and stay threaded with each other when two or more; a double-click on a port with no thread does nothing; estimate unchanged | +| 2026-10-31 | minor | G1: Grid Repeat Options has a Preview checkbox (#2651); estimate unchanged. | | 2026-10-25 | minor | G1: a selected Grid Repeat shows handles: the one below the grid adds or removes rows, the one right of it columns, the one past its bottom-right corner both, and the sliders between the first two columns and rows set the horizontal and vertical spacing; each drag is one undo step and Escape cancels it (#2691); bounding-box handles keep priority where they meet; Radial Repeat handles remain; estimates unchanged. | | 2026-10-25 | minor | Floating panels open in OS windows of their own on the desktop (inside the window on the web and on Wayland); saved layouts from earlier versions convert to the shared docking layout (#4135); scores and estimates unchanged (estimated) | | 2026-10-24 | minor | Recolor Artwork › Assign: double-clicking a row's new color opens the Color Picker over the dialog; its OK sets the row's new color in the model it was picked in (a CMYK mix stays CMYK, RGB becomes CMYK in a CMYK document), Cancel leaves the row as it was. A Lab new color is kept, but a Lab color can't be typed yet: the picker's Lab fields work in RGB, as for fill and stroke (part of #4028; Lab entry, swatch libraries and the row menu remain). Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a871b67478..b29ba24552 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G8: a gradient mesh from a file is budgeted, #3592; scores unchanged; previously: Path Precision Tools add-on: Shared Edge Merge Tool; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G1: Grid Repeat Options has a Preview checkbox, #2651; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -19,6 +19,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Patterns: Grid Repeat Options has a Preview checkbox, as the public grid options page lists (#2651); scores unchanged. | | 2026-10-31 | minor | Hardening: a gradient mesh read from a file is budgeted at about a million quads, so a huge one no longer exhausts memory when drawn or exported (#3592); scores unchanged. | | 2026-10-30 | minor | File formats: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | | 2026-10-30 | minor | File formats: `.ai`/EPS editing-data fidelity from an audit of a user's files: All Caps and Small Caps (#4708); placed files at their box's corner, kept where they draw closer to the page (#4664, #4723, #4742); pages cropped to the art, with `UserUnit` (#4658, #4727); gradient mesh corners with handle weights of 0 and the state written after a mesh (#4738, #4744, #4748); type on a path spaced as the file lays it out (#4743); synthetic regressions in `crates/eps`; evidence added; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3313a18d2e..6e6ed4b9b8 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Path Precision Tools add-on: Shared Edge Merge Tool; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G1: Grid Repeat Options has a Preview checkbox, #2651; scores unchanged; previously: Path Precision Tools add-on: Shared Edge Merge Tool; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -274,6 +274,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Command search: Up and Down move through the results, Enter runs the highlighted one | done | #1798 (#1757) | | Pathfinder panel: a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled | done | #1642 (#1635) | | Selected Grid Repeat shows row, column and corner handles and spacing sliders; bounding-box handles take priority where they meet | done | #2691, `tools/src/repeat_grid.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html); drags preview and commit `object.repeat.options` as one undo step, Escape cancels; Radial Repeat has no handles yet | +| Grid Repeat Options (Object › Repeat › Options…) has a Preview checkbox: the repeat on the canvas follows the fields while the dialog is open, Cancel puts the original back without a history step, OK keeps the previewed values as one undo step | done | #2651; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html) lists the Preview option for the grid options only, so Radial and Mirror Repeat Options have none; `dialogs/command.rs` tests | | Selected Mirror Repeat shows a prominent axis with move and rotation handles; bounding-box handles take priority over the axis line | done | #2877, `tools/src/mirror.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html) | | Object › Expand on radial, grid and mirror repeats makes groups of their instances | done | #1765 (#1756) | | Object › Expand… is dimmed while the selection has appearance attributes (effects, several fills or strokes, a fill or stroke with its own transparency or effects, a brush); its tooltip and the status bar say to use Object › Expand Appearance first, which leaves a stroked line with Zig Zag a stroked zig-zag line that Expand then outlines | done | #3089; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html); `dialogs/expand.rs` tests, engine `tests_objexpand`. `object.expand` (agents, scripts) still bakes effects in one step | @@ -375,6 +376,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Grid Repeat Options has a Preview checkbox (#2651); scores and estimates unchanged | | 2026-10-31 | minor | Path Precision Tools add-on: the Shared Edge Merge Tool and Keep Shared Points Together; scores and estimates unchanged | | 2026-10-31 | minor | Path Precision Tools add-on: live Path Effects in Effect › Path Effects; scores and estimates unchanged | | 2026-10-31 | minor | Path Precision Tools add-on: the Corner Tool (editable corners, panel section) and Slide Anchor Along Path; scores and estimates unchanged | From f65d28378f76fca3965724ccdb3edb239662869a Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Sat, 31 Oct 2026 13:57:02 +0430 Subject: [PATCH 053/260] Fix #995: a width-profile stroke keeps its shape when the view zooms out The canvas keeps a hairline visible by raising a stroke's weight to half a device pixel. A width profile multiplies that weight, so a 1 pt stroke with a 6x width point swelled to twice its size at 25% zoom and shrank back on zooming in. The minimum now goes to the profile's widest point instead; plain strokes are unchanged. --- crates/doc/src/appearance/profile.rs | 9 ++++ crates/render/src/renderer/paint.rs | 7 +++- crates/render/src/tests.rs | 1 + crates/render/src/tests/widthzoom.rs | 63 ++++++++++++++++++++++++++++ docs/target-app-parity.md | 4 +- 5 files changed, 81 insertions(+), 3 deletions(-) create mode 100644 crates/render/src/tests/widthzoom.rs diff --git a/crates/doc/src/appearance/profile.rs b/crates/doc/src/appearance/profile.rs index ccae9666bd..09142df0c0 100644 --- a/crates/doc/src/appearance/profile.rs +++ b/crates/doc/src/appearance/profile.rs @@ -53,6 +53,15 @@ impl WidthProfile { // Two swells between narrow necks. ProfilePreset { id: "wave", label: "Wave", points: &[(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)] }, ]; + /// The widest the stroke gets, as a multiple of its weight: the largest total of the left and + /// right factors at any of the points (between them the profile is straight), 1 for a profile + /// without points. + pub fn widest(&self) -> f64 { + if self.points.is_empty() { + return 1.0; + } + self.points.iter().map(|&(_, l, r)| (l.max(0.0) + r.max(0.0)) / 2.0).fold(0.0, f64::max) + } /// The built-in profile with this id. pub fn preset(id: &str) -> Option<Self> { Self::PRESETS.iter().find(|p| p.id == id).map(|p| Self { points: p.points.to_vec() }) diff --git a/crates/render/src/renderer/paint.rs b/crates/render/src/renderer/paint.rs index 9a6a48142b..3214ffe58d 100644 --- a/crates/render/src/renderer/paint.rs +++ b/crates/render/src/renderer/paint.rs @@ -109,8 +109,11 @@ impl Renderer { } ctx.set_transform(f.view * xf); let closed = effects::stroke::is_closed(bp); - // Keep hairlines visible when zoomed far out (at least ~1 device pixel). - let width = effects::stroke::aligned_width(st, closed).max(f.px * 0.5 / xf.determinant().abs().sqrt().max(1e-9)); + // Keep hairlines visible when zoomed far out (at least ~1 device pixel). A width profile + // multiplies the weight, so it is the profile's widest point that is kept visible: raising + // the weight further would swell the whole stroke while the view zooms out (#995). + let widest = st.profile.as_ref().map_or(1.0, |p| p.widest().max(1e-3)); + let width = effects::stroke::aligned_width(st, closed).max(f.px * 0.5 / xf.determinant().abs().sqrt().max(1e-9) / widest); let inside = st.align == StrokeAlign::Inside && closed; if inside { ctx.set_fill_rule(fill_rule(rule)); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 767f1eda8a..643701fc72 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -29,6 +29,7 @@ mod setup; mod strokegradient; mod tileedge; mod viewraster; +mod widthzoom; fn rect_node(d: &mut Document, r: Rect, fill: Paint, stroke: Paint, w: f64) -> Node { let id = d.alloc_id(); diff --git a/crates/render/src/tests/widthzoom.rs b/crates/render/src/tests/widthzoom.rs new file mode 100644 index 0000000000..a59387589f --- /dev/null +++ b/crates/render/src/tests/widthzoom.rs @@ -0,0 +1,63 @@ +//! A stroke with a width profile keeps its shape when the view zooms out (#995): only a stroke too +//! thin to see is thickened, and then by what its widest point needs, not all of it at once. + +use vectorcraft_color::Paint; +use vectorcraft_doc::{Appearance, AppearanceItem, Node, StrokeLayer, WidthProfile}; +use vectorcraft_geom::PathData; + +use crate::*; + +const SIZE: u32 = 200; + +/// A line across a 200×200 page, stroked black `weight` pt with `profile`, drawn at `scale`. +fn render(weight: f64, profile: Option<WidthProfile>, scale: f64) -> Rendered { + let mut st = StrokeLayer::new(Paint::solid(vectorcraft_color::Color::BLACK), weight); + st.profile = profile; + let mut p = BezPath::new(); + p.move_to((20.0, 100.0)); + p.line_to((180.0, 100.0)); + let mut d = Document::new(SIZE as f64, SIZE as f64); + let n = Node::path(d.alloc_id(), PathData::from_bezpath(&p), Appearance { items: vec![AppearanceItem::Stroke(st)], ..Default::default() }); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + Renderer::new().render(&d, SIZE, SIZE, Affine::scale(scale), &RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }) +} + +/// Device pixels of ink in the column through the middle of the line (coverage summed, so a +/// stroke narrower than a pixel still counts what it covers). +fn ink_at_middle(img: &Rendered, scale: f64) -> f64 { + let x = (100.0 * scale) as u32; + (0..SIZE).map(|y| 1.0 - img.pixel(x, y)[0] as f64 / 255.0).sum() +} + +/// Thin at both ends, six times the weight in the middle. +fn swell() -> WidthProfile { + WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 6.0, 6.0), (1.0, 1.0, 1.0)] } +} + +#[test] +fn a_thin_width_stroke_keeps_its_thickness_in_document_terms_when_zoomed_out() { + let whole = ink_at_middle(&render(1.0, Some(swell()), 1.0), 1.0); + assert!((whole - 6.0).abs() < 0.3, "six points at full size: {whole}"); + for scale in [0.5, 0.25, 0.125] { + let ink = ink_at_middle(&render(1.0, Some(swell()), scale), scale); + let in_points = ink / scale; + assert!((in_points - whole).abs() < whole * 0.05, "at {scale}: {in_points} pt against {whole} pt"); + } +} + +#[test] +fn a_stroke_too_thin_to_see_is_kept_visible_by_its_widest_point() { + // 0.1 pt, twice that in the middle: at a quarter size even the middle is a twentieth of a + // pixel, so it is thickened to the half pixel a plain hairline gets, and the profile's ends + // stay half of it. + let thin = WidthProfile { points: vec![(0.0, 0.5, 0.5), (0.5, 1.0, 1.0), (1.0, 0.5, 0.5)] }; + let plain = ink_at_middle(&render(0.1, None, 0.25), 0.25); + let img = render(0.1, Some(thin), 0.25); + let shaped = ink_at_middle(&img, 0.25); + assert!((plain - 0.5).abs() < 0.1, "a plain hairline gets half a pixel: {plain}"); + assert!((shaped - 0.5).abs() < 0.1, "the widest point of a profile gets it too: {shaped}"); + // Seven pixels in, 28 pt along the page: just past the line's start at 20 pt. + let end: f64 = (0..SIZE).map(|y| 1.0 - img.pixel(7, y)[0] as f64 / 255.0).sum(); + assert!(end < shaped * 0.75, "the thin end stays thinner than the middle: {end} against {shaped}"); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b29ba24552..5bc104bc84 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G1: Grid Repeat Options has a Preview checkbox, #2651; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (a width-profile stroke keeps its shape when the view zooms out, #995) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -19,6 +19,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Width tool: a stroke with a width profile keeps its shape while the view zooms out; the minimum visible width goes to its widest point instead of scaling the whole profile (#995); scores unchanged. | | 2026-10-31 | minor | Patterns: Grid Repeat Options has a Preview checkbox, as the public grid options page lists (#2651); scores unchanged. | | 2026-10-31 | minor | Hardening: a gradient mesh read from a file is budgeted at about a million quads, so a huge one no longer exhausts memory when drawn or exported (#3592); scores unchanged. | | 2026-10-30 | minor | File formats: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | @@ -507,6 +508,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Width-point finite-arithmetic follow-up (G1/M3):** Adjoining adjustments avoid intermediate overflow; non-finite normalized or resulting factors are rejected before committing. Engine regressions in `tests/widthpoints.rs` cover finite extremes, small nonzero results, atomic rejection, Undo/Redo and native save/reopen. Historical focused validation on the `a3357121` integration observed 2 expected RED failures with 11 passing controls, then all 13 tests passing with the repair; none were ignored. All three added regressions passed in current full CI. A full CI retry on the five-unit combined source at `a0671777` passed all seven stages with 6,613 test outcomes on 2026-10-14. An earlier full-CI run on the identical source panicked in the randomized `ai_mutated_save_never_panics` test; the cause remains unresolved. This five-fix batch does not claim to repair that failure. Scores and hours unchanged. - **Width-point creation (G1):** double-click a stroked segment with the Width tool to open Width Point Edit using sampled side widths. OK creates the point and optionally adjusts adjoining widths in one undo step. Cancel or Delete discards a prospective point without changing the document or redo history. Command and pointer tests cover profiles, compound paths, adjoining adjustment, existing-point editing and Undo/Redo. Message-catalog checks and full CI passed; the original capture verifies opening and Cancel, and the dialog layout was reviewed (2026-10-13: 28 focused Width tests, all seven cargo xtask ci stages, and a headless opening/Cancel capture with original PNG review). [Variable-width strokes](https://helpx.adobe.com/illustrator/using/stroke-object.html). - **Escape deselects width points:** with the Width tool, Escape deselects the selected width points, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for deselecting a width point. The path, its widths and the undo history do not change. With no width point selected, Escape does what it does with the other tools, such as leaving isolation mode. +- **Width strokes zoomed out (#995):** a stroke with a width profile keeps its shape while the view zooms out. The canvas keeps a hairline visible (at least half a device pixel); for a profiled stroke it is the profile's widest point that gets that minimum, not the weight, so a 1 pt stroke with a 6x width point is no longer drawn twice as thick at 25% zoom than at 100%. Plain strokes are unchanged. Test: `render::tests::widthzoom`. - **Rulers (#1212):** drag the intersection to preview and set a document zero point, or double-click it to reset to the active artboard's top-left. Transform, Properties and Control X/Y fields measure from it and convert entered positions back to absolute command coordinates. The origin survives every native format version and compression; geometry, guides and patterns stay in place. Public reference: [Use rulers](https://helpx.adobe.com/ca/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html). - **Global and artboard rulers:** View › Rulers › Change to Global / Artboard Rulers (Cmd+Alt+R, `view.globalRulers`). A new document has artboard rulers: the rulers and the Transform, Properties, Control and Info X/Y count from the active artboard's top-left corner, or the zero point dragged out for that artboard, which moves with it; with global rulers one document zero point serves every artboard. Guide readouts and Shift ruler-tick snapping follow the same zero point. The mode is saved with the document; files from before it open with global rulers, as they measured. Regression tests: `engine/tests/it/ruler_origin.rs`, `ui-egui/src/tests/ruler_origin.rs`, `tools/src/rulerguide.rs`. Public reference: [About rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/about-rulers.html). - **Video display options (#2849):** Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio, and View › Rulers › Show Video Rulers ([Set video display options for artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)). Each artboard has its own (`artboard.setProps`/`artboard.new` `showVideoSafeAreas`, `videoRulerPixelAspectRatio` 0.1–10, default 1), set in one undo step and written to the native format only when on or not 1, so other documents save byte for byte as before. The help page names the safe areas without numbers; our choice is [EBU R 95](https://tech.ebu.ch/docs/r/r095.pdf)'s (note 5): the canvas outlines the action-safe area 3.5% and the title-safe (graphics-safe) area 5% in from each edge, 1 point wide and turned with the view; exports and print leave them out. Show Video Rulers (`view.videoRulers`) shows the rulers counting the active artboard in pixels from its top-left corner, whatever the ruler origin: a pixel is as many points wide as the ratio and one point tall, so a 720 × 480 pt artboard at 0.9 reads 800 × 480. Hide Video Rulers returns them to the General unit; Shift ruler-tick snapping of new guides keeps the General unit. Regression tests: `tests/panelcmds.rs` (`artboard_video_display_options_*`, `artboard_display_marks_stay_out_of_exports`), `tests/docsetup.rs` (`an_artboard_shows_its_video_safe_areas`), `canvas.rs` (`video_rulers_count_the_artboard_in_pixels_of_its_aspect_ratio`), `tests/ruler_origin.rs` (`show_video_rulers_counts_the_active_artboard_in_pixels`), `dialogs/tests.rs` (`artboard_options_show_video_display_options`). From 63b685758f5759c4b33d46d5d8dcdb309bfa16ea Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Sat, 31 Oct 2026 11:15:57 +0430 Subject: [PATCH 054/260] Snapping: a line end dragged with Direct Selection snaps square to straight paths and tangent to curves (#2530) --- crates/tools/src/direct.rs | 40 +++++++++++++- crates/tools/src/direct/tests.rs | 95 ++++++++++++++++++++++++++++++++ crates/tools/src/guides/snap.rs | 8 +++ docs/gaps.md | 21 +++++-- docs/target-app-parity.md | 11 ++-- docs/ui-parity.md | 5 +- 6 files changed, 166 insertions(+), 14 deletions(-) diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 623d2b5c5c..c27466935e 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -180,6 +180,10 @@ pub struct DirectSelectionTool { guides: Vec<Overlay>, /// What the dragged anchors snap to, gathered when the drag begins. anchor_snap: Option<PointSnap>, + /// With one open path's end anchor dragged along a straight segment, that segment's other end: + /// the dragged end may land square to a straight path or grazing a curve (Smart Guides › + /// Geometric Guides). Set when the drag begins. + line_end: Option<Leave>, /// What the anchor holding paths moved whole snaps to while Alt makes a copy: the original left /// behind too. Gathered with [`Self::anchor_snap`], before the previews move the original. copy_snap: Option<PointSnap>, @@ -227,6 +231,7 @@ impl DirectSelectionTool { mesh: MeshEdit::default(), guides: vec![], anchor_snap: None, + line_end: None, copy_snap: None, handle_snap: HandleSnap::default(), move_snap: None, @@ -406,6 +411,38 @@ fn anchor_owners(cx: &ToolContext, f: fn(&Node) -> bool) -> Vec<NodeId> { v } +/// Where a line's end anchor `grab`bed for a drag leaves from, when it is one: the only anchor +/// selected, the end of an open subpath whose one segment is straight, and no other art moving +/// with it. That segment's other end stays put, so the end snaps square to straight paths and +/// grazing curves; mid-line anchors and ends of curved segments do not (Illustrator limits Snap +/// to Tangent and Snap to Perpendicular to line endpoints). +fn line_end_leave(cx: &ToolContext, grab: Point) -> Option<Leave> { + let sel = cx.selection; + if !sel.segments.is_empty() || sel.anchors.len() != 1 { + return None; + } + let (&id, set) = sel.anchors.iter().next()?; + if set.len() != 1 || sel.objects.iter().any(|o| *o != id) { + return None; + } + let &(si, ai) = set.iter().next()?; + let sp = cx.doc.node(id)?.path_data()?.subpaths.get(si)?; + let n = sp.anchors.len(); + if sp.closed || ai >= n || sp.anchors[ai].p.distance(grab) > 1e-6 { + return None; + } + let (other, seg) = if n < 2 { + return None; + } else if ai == 0 { + (1, 0) + } else if ai == n - 1 { + (n - 2, n - 2) + } else { + return None; + }; + sp.segment_is_line(seg).then(|| Leave::contact(sp.anchors[other].p)) +} + /// The anchor within `tol` of `p` nearest to it, of the topmost selected path or area type frame /// that has one, else of the topmost visible one: (id, si, ai, where it is). Selected objects come /// first so an object above can't take the press from the one being edited (#1508), as @@ -1230,6 +1267,7 @@ impl DirectSelectionTool { out.push(Action::Begin("Move".into())); self.state = State::MoveAnchors { start, grab, began: true }; self.anchor_snap = Some(PointSnap::new(cx, || Targets::for_anchor_drag(cx.doc, cx.selection))); + self.line_end = line_end_leave(cx, grab); } let mut d = move_delta(start, p, ev.mods.shift, cx.constrain_angle); let unsnapped = d; @@ -1238,7 +1276,7 @@ impl DirectSelectionTool { self.guides.clear(); if let Some(snap) = &self.anchor_snap { let shift = ev.mods.shift.then(|| Leave::segment(cx, grab, true)); - let (q, guides) = snap.snap_from(cx, grab + (p - start), shift.as_ref()); + let (q, guides) = snap.snap_from(cx, grab + (p - start), shift.as_ref().or(self.line_end.as_ref())); (d, self.guides) = (q - grab, guides); } self.snapped = snapped(d, unsnapped, ev.mods.shift, &self.guides); diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index d3f394d99f..cb852c5531 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -1477,6 +1477,101 @@ fn dragged_end_of_a_slanted_line_stays_on_its_direction() { assert!(matches!(guides[..], [(a, b)] if a == Point::new(300.0, 400.0) && (b - Point::new(420.0, 310.0)).hypot() < 1e-9), "{guides:?}"); } +/// Drawn lines snap square to a straight path and grazing a curve (Smart Guides › Geometric +/// Guides); so does an existing line whose end anchor is dragged with Direct Selection. Each +/// option switches its own snap off. Only a line's end snaps so: the middle anchor of a +/// polyline, an end of a curved segment, a closed path's anchor, several anchors dragged together, +/// a Shift drag and an end out of reach do not, nor does Group Selection, which moves the path whole. +#[test] +fn dragged_line_ends_snap_perpendicular_to_segments_and_tangent_to_curves() { + use vectorcraft_geom::{BezPath, PathData, SubPath, shapes}; + let near = |v: &serde_json::Value, (x, y): (f64, f64), eps: f64| (v["dx"].as_f64().unwrap() - x).hypot(v["dy"].as_f64().unwrap() - y) < eps; + // The rect's right side (x = 200) and a circle (centre (500, 500), radius 50), with one more + // path: its id, and the document. + let with = |path: PathData| { + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let (circle, id) = (d.alloc_id(), d.alloc_id()); + let ring = + vectorcraft_doc::Node::path(circle, shapes::ellipse(Rect::new(450.0, 450.0, 550.0, 550.0)), vectorcraft_doc::Appearance::default_art()); + d.insert(Some(l), 1, ring).unwrap(); + d.insert(Some(l), 2, vectorcraft_doc::Node::path(id, path, vectorcraft_doc::Appearance::default_art())).unwrap(); + (d, id) + }; + let p = paint(); + let none = Mods::default(); + let mut t = DirectSelectionTool::new(false); + // A line (300, 160)–(260, 170), its end dragged to 3.6 pt from the foot of the perpendicular + // from (300, 160) to the rect's right side: (200, 160). + let (d, id) = with(shapes::line(Point::new(300.0, 160.0), Point::new(260.0, 170.0))); + let end = anchors_of(id, &[(0, 1)]); + let c = cx(&d, &end, &p); + let (v, labels) = drag(&mut t, &c, (260.0, 170.0), (202.0, 163.0), none); + assert!(near(&v, (-60.0, -10.0), 1e-6) && labels == ["perpendicular"], "{v} {labels:?}"); + // The other end snaps the same way about this one: square to the side at (200, 170). + let start = anchors_of(id, &[(0, 0)]); + let c = cx(&d, &start, &p); + let (v, labels) = drag(&mut t, &c, (300.0, 160.0), (202.0, 172.0), none); + assert!(near(&v, (-100.0, 10.0), 1e-6) && labels == ["perpendicular"], "{v} {labels:?}"); + // Perpendicular off: the end only lands on the path, where the pointer is; tangent off does + // not change that. + let c = ToolContext { snap_perpendicular: false, ..cx(&d, &end, &p) }; + let (v, labels) = drag(&mut t, &c, (260.0, 170.0), (202.0, 163.0), none); + assert!(near(&v, (-60.0, -7.0), 1e-6) && labels == ["path"], "{v} {labels:?}"); + let c = ToolContext { snap_tangent: false, ..cx(&d, &end, &p) }; + assert_eq!(drag(&mut t, &c, (260.0, 170.0), (202.0, 163.0), none).1, ["perpendicular"]); + // With Smart Guides off, Snap to Point alone finds no contact. + let c = ToolContext { smart_guides: false, ..cx(&d, &end, &p) }; + assert_eq!(drag(&mut t, &c, (260.0, 170.0), (202.0, 163.0), none).1, Vec::<String>::new()); + // Out of reach: left alone. + let c = cx(&d, &end, &p); + let (v, labels) = drag(&mut t, &c, (260.0, 170.0), (240.0, 140.0), none); + assert!(near(&v, (-20.0, -30.0), 1e-9) && labels.is_empty(), "{v} {labels:?}"); + // Shift holds the move to its 45° step: no contact. + let shift = Mods { shift: true, ..none }; + assert!(!drag(&mut t, &c, (260.0, 170.0), (202.0, 163.0), shift).1.contains(&"perpendicular".to_string())); + // Group Selection moves the path whole: no contact either. + let mut group = DirectSelectionTool::new(true); + assert!(!drag(&mut group, &c, (260.0, 170.0), (202.0, 163.0), none).1.contains(&"perpendicular".to_string())); + + // A line (400, 500)–(420, 470) toward the circle: its end lands where the line from (400, 500) + // grazes it, at (475, 456.7). + let (d, id) = with(shapes::line(Point::new(400.0, 500.0), Point::new(420.0, 470.0))); + let end = anchors_of(id, &[(0, 1)]); + let c = cx(&d, &end, &p); + let (v, labels) = drag(&mut t, &c, (420.0, 470.0), (477.0, 459.0), none); + assert!(near(&v, (55.0, 500.0 - 1875f64.sqrt() - 470.0), 0.1) && labels == ["tangent"], "{v} {labels:?}"); + let c = ToolContext { snap_tangent: false, ..cx(&d, &end, &p) }; + let (v, labels) = drag(&mut t, &c, (420.0, 470.0), (477.0, 459.0), none); + assert!(near(&v, (55.53, -13.61), 0.01) && labels == ["path"], "the end only lands on the circle: {v} {labels:?}"); + let c = ToolContext { snap_perpendicular: false, ..cx(&d, &end, &p) }; + assert_eq!(drag(&mut t, &c, (420.0, 470.0), (477.0, 459.0), none).1, ["tangent"]); + + // Not a line's end: the middle anchor of a polyline, and an anchor of a closed path. + let three = [Point::new(300.0, 160.0), Point::new(260.0, 170.0), Point::new(240.0, 230.0)]; + let (d, id) = with(PathData::single(SubPath::polyline(&three, false))); + let mid = anchors_of(id, &[(0, 1)]); + let c = cx(&d, &mid, &p); + assert_eq!(drag(&mut t, &c, (260.0, 170.0), (202.0, 163.0), none).1, ["path"]); + let (d, id) = with(PathData::single(SubPath::polyline(&three, true))); + let corner = anchors_of(id, &[(0, 1)]); + let c = cx(&d, &corner, &p); + assert_eq!(drag(&mut t, &c, (260.0, 170.0), (202.0, 163.0), none).1, ["path"]); + // The end of a curved segment: no contact either. + let mut curve = BezPath::new(); + curve.move_to(Point::new(300.0, 160.0)); + curve.curve_to(Point::new(290.0, 150.0), Point::new(270.0, 160.0), Point::new(260.0, 170.0)); + let (d, id) = with(PathData::from_bezpath(&curve)); + let end = anchors_of(id, &[(0, 1)]); + let c = cx(&d, &end, &p); + assert_eq!(drag(&mut t, &c, (260.0, 170.0), (202.0, 163.0), none).1, ["path"]); + // A line end dragged with another anchor selected: the pair moves rigidly, no contact. + let (d, id) = with(shapes::line(Point::new(300.0, 160.0), Point::new(260.0, 170.0))); + let both = anchors_of(id, &[(0, 0), (0, 1)]); + let c = cx(&d, &both, &p); + assert!(!drag(&mut t, &c, (260.0, 170.0), (202.0, 163.0), none).1.contains(&"perpendicular".to_string())); +} + /// Group Selection (and Direct Selection on a whole path) moves objects snapping as the /// Selection tool does: B's left side lines up with A's right one. #[test] diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index 14a36b4223..4766455f88 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -230,6 +230,14 @@ impl Leave { self } + /// The straight segment from the anchor `at` to a point being dragged (an open path's end + /// moved with Direct Selection): the point may land square to a segment or grazing a curve, + /// but is not held to Shift's angles or the construction guides, which a moved anchor + /// does not follow. + pub fn contact(at: Point) -> Self { + Self { at, shift: None, angles: &[], contact: true } + } + /// A box dragged from its corner or centre `at` (Rectangle, Ellipse, Arc, the grids, and /// Artboard, which passes no Shift): Shift keeps the dragged corner on a diagonal, the box a /// square. diff --git a/docs/gaps.md b/docs/gaps.md index 608779f7af..16da466298 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G1: Grid Repeat Options has a Preview checkbox, #2651; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G13: Direct Selection snaps a dragged line end square to straight paths and grazing curves; G13: gradient presets done; G1: Average & Join with a corner or smooth choice, Cmd+Alt+Shift+J, done; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -465,15 +465,23 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall perceptual mix with dither's noise (an image with the noise in SVG and PDF); a stroke has no noise. - **Missing (asked for by users, from earlier versions):** radial gradients in Image Trace's Gradients option, which traces linear ones only (draft #1849). Inside the estimate below. -- **Partial (#2530):** tangent snapping to curves and perpendicular snapping to straight target - segments for drawn lines. Controls are saved under Preferences › Smart Guides › Geometric Guides - and available from Control bar › Snapping; both default to on. Existing-line endpoint editing and - other tool cases remain unverified. [Public source](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/snap-to-perpendicular.html). +- **Done (#2530):** tangent snapping to curves and perpendicular snapping to straight target + segments, as the public [perpendicular](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/snap-to-perpendicular.html) + and [tangent](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/snap-to-tangent.html) + pages describe, for the Line Segment and Pen tools' new lines and for existing lines: dragging the end + anchor of an open path's straight segment with Direct Selection lands it square to + another straight path (the foot of the perpendicular from the segment's other end) or grazing a curve, with + the "perpendicular" or "tangent" label (and the square-corner mark) Smart Guides show for drawn lines. As + the pages say, only line endpoints snap: the middle anchor of a path, the end of a curved segment, a closed + path's anchor, several anchors dragged together and Shift-constrained drags (which keep their angle step) do + not, and a curve is never a perpendicular target. Controls are saved under Preferences › Smart Guides › + Geometric Guides and available from Control bar › Snapping; both default to on. Tests: + `dragged_line_ends_snap_perpendicular_to_segments_and_tangent_to_curves` in `crates/tools/src/direct/tests.rs`. - **Done (2026-10-30):** gradient presets (30.0): the Gradient panel's Presets menu applies one of the built-in gradient libraries' presets (by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the gradient as a preset (kept with the preferences) and deletes saved ones; `gradient.presets.*` commands. -- **Missing:** remaining tangent/perpendicular snapping cases and the consolidated +- **Missing:** the consolidated snapping options (30.0); artboard colors in exports and print, and managing artboards from the canvas other than locking and unlocking them from the Artboard tool's right-click menu (30.0); the Blend panel with ease in/out and separate colour acceleration (30.7); @@ -667,6 +675,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | G13: Direct Selection snaps the end of an existing straight line, dragged by its end anchor, square to straight paths and grazing curves (Smart Guides › Geometric Guides: Snap to Perpendicular and Snap to Tangent), the case the public Snap to Perpendicular and Snap to Tangent pages add to drawing with the Line Segment and Pen tools (#2530). Scores and estimates unchanged. | | 2026-10-31 | minor | G8: a gradient mesh read from a file is budgeted: at most about a million quads per tessellation, and a mesh with more patches than that is malformed (#3592); estimate unchanged. | | 2026-10-30 | minor | G9: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | | 2026-10-30 | minor | G1: Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J) moves two open path ends to their midpoint and joins them there, the joined anchor a corner or a smooth point as its dialog's Points choice asks, in one undo step; the "Average and Join in one step" entry is done. Estimate unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5bc104bc84..0f2883ae6b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (a width-profile stroke keeps its shape when the view zooms out, #995) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G13: Direct Selection snaps a dragged line end square to straight paths and grazing curves; Path Precision Tools add-on: Shared Edge Merge Tool; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -141,10 +141,10 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), guides lost (#779), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC/JPEG 2000 import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. | | View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated; document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | | View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated | -| Guides, grids, smart guides, snapping, rulers | 3 | 80% | 30.0's tangent snapping to curves and perpendicular snapping to straight segments for lines drawn with the Pen, Curvature and Line Segment tools (Preferences › Smart Guides › Geometric Guides and Control bar › Snapping, #2530; other tool and drag cases remain), "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score unchanged | -| Guides, grids, smart guides, snapping, rulers | 3 | 80% | 30.0's tangent snapping to curves and perpendicular snapping to straight segments for lines drawn with the Pen, Curvature and Line Segment tools (Preferences › Smart Guides › Geometric Guides and Control bar › Snapping, #2530; other tool and drag cases remain), "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), global/artboard ruler mode switch, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score unchanged | -| Guides, grids, smart guides, snapping, rulers | 3 | 80% | 30.0's tangent snapping to curves and perpendicular snapping to straight segments for lines drawn with the Pen, Curvature and Line Segment tools (Preferences › Smart Guides › Geometric Guides and Control bar › Snapping, #2530; other tool and drag cases remain), "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), video rulers, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; status-bar X/Y uses the active ruler origin and General units | -| Guides, grids, smart guides, snapping, rulers | 3 | 80% | 30.0's tangent snapping to curves and perpendicular snapping to straight segments for lines drawn with the Pen, Curvature and Line Segment tools (Preferences › Smart Guides › Geometric Guides and Control bar › Snapping, #2530; other tool and drag cases remain), "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), global/artboard ruler mode switch and video rulers, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; status-bar X/Y uses the active ruler origin and General units | +| Guides, grids, smart guides, snapping, rulers | 3 | 80% | 30.0's tangent snapping to curves and perpendicular snapping to straight segments for lines drawn with the Pen, Curvature and Line Segment tools and for an existing line's end dragged with Direct Selection (Preferences › Smart Guides › Geometric Guides and Control bar › Snapping, #2530; the public pages name no other tool), "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score unchanged | +| Guides, grids, smart guides, snapping, rulers | 3 | 80% | 30.0's tangent snapping to curves and perpendicular snapping to straight segments for lines drawn with the Pen, Curvature and Line Segment tools and for an existing line's end dragged with Direct Selection (Preferences › Smart Guides › Geometric Guides and Control bar › Snapping, #2530; the public pages name no other tool), "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), global/artboard ruler mode switch, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score unchanged | +| Guides, grids, smart guides, snapping, rulers | 3 | 80% | 30.0's tangent snapping to curves and perpendicular snapping to straight segments for lines drawn with the Pen, Curvature and Line Segment tools and for an existing line's end dragged with Direct Selection (Preferences › Smart Guides › Geometric Guides and Control bar › Snapping, #2530; the public pages name no other tool), "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), video rulers, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; status-bar X/Y uses the active ruler origin and General units | +| Guides, grids, smart guides, snapping, rulers | 3 | 80% | 30.0's tangent snapping to curves and perpendicular snapping to straight segments for lines drawn with the Pen, Curvature and Line Segment tools and for an existing line's end dragged with Direct Selection (Preferences › Smart Guides › Geometric Guides and Control bar › Snapping, #2530; the public pages name no other tool), "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), global/artboard ruler mode switch and video rulers, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; status-bar X/Y uses the active ruler origin and General units | | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | @@ -1361,6 +1361,7 @@ add-on. | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Guides and snapping: Snap to Perpendicular and Snap to Tangent apply to an existing line's end dragged with Direct Selection, as the public pages describe for editing existing lines (the end anchor of a straight segment, not mid-line anchors or curved segments); a regression test covers both snaps, both toggles and non-snapping controls (#2530); scores and estimates unchanged. | | 2026-10-30 | minor | File formats: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | | 2026-10-31 | minor | Path Precision Tools add-on: the Shared Edge Merge Tool and Keep Shared Points Together; evidence added; scores unchanged. | | 2026-10-31 | minor | Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path; evidence added; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 6e6ed4b9b8..73e52f87a7 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G1: Grid Repeat Options has a Preview checkbox, #2651; scores unchanged; previously: Path Precision Tools add-on: Shared Edge Merge Tool; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Direct Selection snaps a dragged line end square to straight paths and grazing curves; Path Precision Tools add-on: Shared Edge Merge Tool; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -152,7 +152,7 @@ tools, never checked side by side) isn't captured row by row. | Snapping tolerance preference | done | | | Snap to Point, Snap to Grid, Snap to Pixel; Pixel Preview | done | #1840: with Snap to Grid on, anchors and objects snap to the grid even when Snap to Pixel is also ticked (#1816 waits for the reporter) | | Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`); new type and drawing snap to live-text baselines and glyph bounds when Smart Guides are on (#3124). Character panel menu › Show Snap to Glyph Options: a checkbox for each guide (Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides, Anchor Point), dimmed while Snap to Glyph is off (#4232) | -| Tangent and perpendicular snapping for line endpoints (new in 30.0) | partial | #2530: tangent snapping to curves and perpendicular snapping to straight segments for drawn lines; saved Preferences › Smart Guides › Geometric Guides controls, on by default. Other tool/drag cases remain. [Public source](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/snap-to-perpendicular.html) | +| Tangent and perpendicular snapping for line endpoints (new in 30.0) | done | #2530: tangent snapping to curves and perpendicular snapping to straight segments for lines drawn with the Line Segment, Pen and Curvature tools, and for an existing line whose end anchor is dragged with Direct Selection (the only anchor selected, an open path's end on a straight segment; Shift keeps its angle step instead; Group Selection moves the path whole and does not snap so); mid-line anchors, curved segments' ends and curves as perpendicular targets are excluded, as the pages say. Saved Preferences › Smart Guides › Geometric Guides controls, on by default. [Perpendicular](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/snap-to-perpendicular.html) and [tangent](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/snap-to-tangent.html) pages; test `dragged_line_ends_snap_perpendicular_to_segments_and_tangent_to_curves` | | Snapping panel/popover consolidating the snap options (30.0) | partial | Control bar › Snapping provides quick access through existing view commands and prefs.set; no View › Snapping submenu. Floating-panel parity remains unverified. | | Customisable rotation snap angle (#973) | missing | Illustrator: Constrain Angle and construction angles only | | Ruler guides: drag out, select, move, delete, lock, Make/Release Guides | done | #414, #451; marquee selects unlocked ruler guides | @@ -376,6 +376,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Smart guides and snapping: Snap to Perpendicular and Snap to Tangent for an existing line's end dragged with Direct Selection (#2530), so the tangent and perpendicular row is done; scores and estimates unchanged | | 2026-10-31 | minor | Grid Repeat Options has a Preview checkbox (#2651); scores and estimates unchanged | | 2026-10-31 | minor | Path Precision Tools add-on: the Shared Edge Merge Tool and Keep Shared Points Together; scores and estimates unchanged | | 2026-10-31 | minor | Path Precision Tools add-on: live Path Effects in Effect › Path Effects; scores and estimates unchanged | From acb5a9721b7e3fc0d847e572217b93ef259d4ae5 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sat, 31 Oct 2026 06:23:05 +0300 Subject: [PATCH 055/260] pathops: simplify the add-anchors segment check for clippy's nonminimal_bool Pre-existing lint on main that stops cargo xtask ci at clippy; the same one-line change other open PRs carry. --- crates/pathops/src/addons/pathtools.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index 8e0474c9a8..b98778cc56 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -185,7 +185,7 @@ pub fn add_anchors(sp: &SubPath, which: SegmentKind, spacing: AnchorSpacing, cap }; let c = sp.segment(seg); let len = c.arclen(ACCURACY); - if !picked || !(len > TINY && len.is_finite()) { + if !(picked && len > TINY && len.is_finite()) { continue; } let (count, step) = match spacing { From c7dc443ee14a53f2ebdc94aa98fae780ca7a52a0 Mon Sep 17 00:00:00 2001 From: SusieeTheFemboy <96988330+SusieeTheLinuxUser@users.noreply.github.com> Date: Sat, 24 Oct 2026 03:30:54 +0200 Subject: [PATCH 056/260] SVG import: a feConvolveMatrix order that overflows usvg's multiply is refused MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit usvg 0.48 casts the filter's order attribute through i32, so a value like 1066570220609 saturates and the u32 order_x * order_y multiply overflows. Only debug and overflow-checks builds panic on that; release builds already import the file — the multiply wraps, and VectorCraft drops the filter as an unsupported primitive with a warning, so nothing reaches the document, render or export (observed on main in a --release build: both repro files import without error; with a one-entry kernelMatrix the wrapped product 2147483647² mod 2³² = 1 even passes usvg's length check and leaves a filter claiming a 2147483647×2147483647 kernel, still dropped downstream). The import now parses order the way usvg does (svgtypes numbers, the same as-i32 cast with its saturation, the first side defaulting the second, both positive or both back to the 3×3 default) and refuses exactly the one case: when the product of the two sides overflows u32 (checked_mul). Any order usvg can multiply keeps importing as before, however large on its own, and a missing, unparseable or non-positive order still falls back to 3. Regression tests cover the overflow repros, the release wrap case, large but fitting orders (100, 80 80, 65535 65535, 2147483647 1), the pass-through shapes, and sane kernels, in debug and in release. Co-Authored-By: GLM-5.3-Flash <noreply@z.ai> --- crates/svg/src/import.rs | 41 ++++++++++++++ crates/svg/tests/convolve_overflow.rs | 82 +++++++++++++++++++++++++++ 2 files changed, 123 insertions(+) create mode 100644 crates/svg/tests/convolve_overflow.rs diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index ff2e63c357..18f4f088d6 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -62,6 +62,44 @@ fn parse(svg: &str) -> Result<roxmltree::Document<'_>, SvgError> { .map_err(|e| SvgError::Parse(e.to_string())) } +const SVG_NS: &str = "http://www.w3.org/2000/svg"; + +/// Refuse the one `feConvolveMatrix` usvg cannot handle: an `order` whose two sides overflow the +/// `order_x * order_y` u32 multiply its parser makes (`usvg-0.48.1/src/parser/filter.rs:673`, and +/// `tree/filter.rs:458` through `ConvolveMatrixData::new`). usvg parses `order` through f64 and +/// `as i32`, so a large finite value like `1066570220609` saturates to i32::MAX — positive, so it +/// passes the positivity guard — and the multiply overflows: a debug or overflow-checks build +/// panics while opening the file. A release build wraps instead, and with a one-entry +/// `kernelMatrix` the wrapped product passes usvg's length check, leaving a filter that claims a +/// 2147483647×2147483647 kernel (which VectorCraft then drops as an unsupported filter primitive, +/// so nothing reaches the document). Any order usvg can multiply — however large — keeps +/// importing exactly as before: a missing, unparseable or non-positive `order` falls back to 3, +/// and a `kernelMatrix` that fails to parse or match the order leaves the filter empty, which +/// usvg drops. The attribute read here is the one usvg reads: unprefixed (XML keeps unprefixed +/// attributes outside any namespace), on an element in the SVG namespace, with entities resolved +/// by the parse above. +fn convolve_matrices_ok(xml: &roxmltree::Document) -> Result<(), SvgError> { + for fe in xml.descendants() { + if !fe.has_tag_name((SVG_NS, "feConvolveMatrix")) { + continue; + } + if let Some(value) = fe.attribute("order") { + // The parse usvg does: svgtypes numbers, `as i32` (saturation included), the first + // side defaulting the second, and both positive or both back to the 3×3 default. + let side = |n: Option<Result<f64, svgtypes::Error>>, default: i32| n.and_then(|v| v.ok()).map(|v| v as i32).unwrap_or(default); + let mut numbers = svgtypes::NumberListParser::from(value); + let x = side(numbers.next(), 3); + let y = side(numbers.next(), x); + if x > 0 && y > 0 && (x as u32).checked_mul(y as u32).is_none() { + return Err(SvgError::Parse(format!( + "a feConvolveMatrix filter's order is {x}×{y}, which overflows the kernel-size multiply usvg makes" + ))); + } + } + } + Ok(()) +} + /// The document SVG text `svg` holds, read with `opts`, and the warnings about what it couldn't keep. pub(crate) fn import(svg: &str, opts: &ImportOptions, max_nodes: usize) -> Result<(Document, Vec<String>), SvgError> { // Before anything reads the tree: the XML reader, usvg, and what is made of its tree, all by @@ -81,6 +119,9 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions, max_nodes: usize) -> Resul Cow::Borrowed(_) => xml, Cow::Owned(edited) => parse(edited)?, }; + // Before usvg sees the XML: its parser overflows a hostile feConvolveMatrix's order + // (`convolve_matrices_ok` below), and there is no panic guard to fall back on. + convolve_matrices_ok(&xml)?; let svg = svg.as_ref(); let units = RootUnits::of(xml.root_element()); let root_name = root_layer_name(xml.root_element()); diff --git a/crates/svg/tests/convolve_overflow.rs b/crates/svg/tests/convolve_overflow.rs new file mode 100644 index 0000000000..4c080e1944 --- /dev/null +++ b/crates/svg/tests/convolve_overflow.rs @@ -0,0 +1,82 @@ +//! A `<feConvolveMatrix>` whose `order` overflows usvg's `order_x * order_y` u32 multiply must be +//! refused before usvg sees it: usvg 0.48 parses the attribute through f64 and casts it with +//! `as i32`, so a large value like `1066570220609` saturates to i32::MAX and the multiply +//! overflows (a debug or overflow-checks build panics). A release build wraps instead, and with a +//! one-entry `kernelMatrix` the wrapped product passes usvg's length check, leaving a filter that +//! claims a 2147483647×2147483647 kernel. Everything else is usvg's pass-through and must keep +//! importing, however large the order is on its own. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use vectorcraft_svg::import; + +/// An overflowing `order` with a `kernelMatrix` that parses (usvg `parser/filter.rs`). +#[test] +fn convolve_matrix_overflowing_order_with_kernel_is_refused() { + let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix kernelMatrix="1 2 3 4" order="1066570220609 17"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#; + let r = import(svg); + assert!(r.is_err(), "an order that overflows the multiply must be refused, not imported"); +} + +/// The release-wrap case: a one-entry `kernelMatrix`, whose wrapped `order_x * order_y` product +/// (2147483647² mod 2³² = 1) passes usvg's length check. +#[test] +fn convolve_matrix_overflowing_order_with_wrapping_kernel_is_refused() { + let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="2147483647" kernelMatrix="1"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#; + let r = import(svg); + assert!(r.is_err(), "an overflowing order must be refused even when a kernel would wrap past the length check"); +} + +/// An `order` whose second side fails to parse defaults it to the first (svgtypes rejects +/// out-of-range numbers like `-1e999`), so this is huge on both sides and refused too. +#[test] +fn convolve_matrix_overflowing_order_with_defaulted_second_side_is_refused() { + let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix kernelMatrix="-60173 1e-999 1e999 0" order="946183596582 -1e999" divisor="-1e999"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#; + let r = import(svg); + assert!(r.is_err(), "an order that overflows the multiply must be refused, not imported"); +} + +/// An order usvg can multiply keeps importing, however large on its own: only the overflowing +/// product is refused. +#[test] +fn convolve_matrix_large_but_fitting_order_still_imports() { + for order in ["100", "80 80", "65535 65535", "2147483647 1"] { + let svg = format!( + r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="{order}"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"# + ); + assert!(import(&svg).is_ok(), "order={order} fits the u32 multiply and must keep importing"); + } +} + +/// usvg falls back to 3 when an order doesn't parse or isn't positive: those keep importing. +#[test] +fn convolve_matrix_nonpositive_or_unparseable_order_still_imports() { + let kernel = r#"kernelMatrix="0 0 0 0 1 0 0 0 0""#; + for order in ["0", "-3", "-1e999", "nan"] { + let svg = format!( + r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="{order}" {kernel}/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"# + ); + assert!(import(&svg).is_ok(), "order={order} is usvg's pass-through and must keep importing"); + } +} + +/// A `kernelMatrix` that doesn't parse or doesn't match the order leaves the filter empty, which +/// usvg drops: the file keeps importing (the filter is drawn without, as a warning). +#[test] +fn convolve_matrix_unparseable_or_mismatched_kernel_still_imports() { + let mismatched = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="3" kernelMatrix="0 0 0 0 1 0 0 0"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#; + assert!(import(mismatched).is_ok(), "a kernel of the wrong length is usvg's pass-through"); + let unparseable = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="3" kernelMatrix="1e999 0 0 0 0 0 0 0 0"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#; + assert!(import(unparseable).is_ok(), "an unparseable kernel is usvg's pass-through"); +} + +/// Sane kernels keep importing: 3×3, 2×2, and a defaulted order. +#[test] +fn sane_convolve_matrices_still_import() { + let three = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="3" kernelMatrix="0 0 0 0 1 0 0 0 0"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#; + assert!(import(three).is_ok(), "an ordinary filter must still import"); + let two = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="2" kernelMatrix="0 1 1 0"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#; + assert!(import(two).is_ok(), "a small kernel must still import"); + let defaulted = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix kernelMatrix="0 0 0 0 1 0 0 0 0"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#; + assert!(import(defaulted).is_ok(), "a filter without order must still import"); +} From 1883e5342da72d6c77c885ef5245d42b7f74ec67 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sat, 31 Oct 2026 07:44:34 +0300 Subject: [PATCH 057/260] PDF import: find installed fonts named with hyphens or a composite font's CMap - A composite (Type 0) font is noted by its descendant CIDFont's BaseFont (ISO 32000-1 9.7.4.1), not its own BaseFont, which ends in "-" and the CMap name (9.7.6.1, e.g. Name-Identity-H); without one, the CMap name is taken off the end of the BaseFont. - A font name's family is the longest part before a hyphen (or the comma of Arial,Bold) that names an available family, so Noto-Sans-Bold is Noto Sans, Bold and Noto-Sans-CJK-JP is Noto Sans CJK JP; a shorter family still matches when no longer one is available. - A missing font is split only at a comma or before the first part that is a style word (Helvetica-BoldOblique); otherwise the whole name is its family (MS-PGothic is reported as MS PGothic, not MS). Synthetic tests (no host fonts): Families::of builds the family list. # Conflicts: # docs/file-format-parity.md # docs/gaps.md # docs/type-parity.md --- crates/pdf/src/import_scan.rs | 22 ++++++- crates/pdf/src/import_text.rs | 81 +++++++++++++++++++++---- crates/pdf/src/tests/import_fidelity.rs | 68 +++++++++++++++++++++ docs/file-format-parity.md | 5 +- docs/gaps.md | 4 +- docs/type-parity.md | 3 +- 6 files changed, 165 insertions(+), 18 deletions(-) diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index dac1a7b644..9263bcd5a3 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -634,11 +634,11 @@ impl Walker<'_, '_> { fn note_fonts(&mut self, res: &Resources<'_>) { for key in res.fonts.keys() { if let Some(f) = res.fonts.get::<Dict<'_>>(key.as_ref()) - && let Some(name) = f.get::<Name<'_>>(b"BaseFont") + && let Some(name) = font_name(&f) { self.fonts.entry(f.cache_key()).or_insert_with(|| { let embedded = embeds_glyphs(&f); - FontNote { name: String::from_utf8_lossy(name.as_ref()).into_owned(), embedded, vertical: vertical_metrics(&f, embedded) } + FontNote { name, embedded, vertical: vertical_metrics(&f, embedded) } }); } } @@ -1009,6 +1009,24 @@ fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) { } } +/// The PostScript name of font `f`: its `BaseFont`. A composite (Type 0) font's `BaseFont` is its +/// CIDFont's name, a hyphen and its CMap's (`Name-Identity-H`, ISO 32000-1 §9.7.6.1), so its +/// descendant CIDFont's `BaseFont` is taken, the font program's own name (§9.7.4.1); without one, +/// the `BaseFont` without the CMap's name on its end. +fn font_name(f: &Dict<'_>) -> Option<String> { + let base = String::from_utf8_lossy(f.get::<Name<'_>>(b"BaseFont")?.as_ref()).into_owned(); + if f.get::<Name<'_>>(b"Subtype").is_none_or(|s| s.as_ref() != b"Type0") { + return Some(base); + } + let descendant = f.get::<Array<'_>>(b"DescendantFonts").and_then(|a| a.iter::<Dict<'_>>().next()); + if let Some(name) = descendant.and_then(|d| d.get::<Name<'_>>(b"BaseFont")).filter(|n| !n.as_ref().is_empty()) { + return Some(String::from_utf8_lossy(name.as_ref()).into_owned()); + } + let cmap = f.get::<Name<'_>>(b"Encoding").map(|n| String::from_utf8_lossy(n.as_ref()).into_owned()); + let stripped = cmap.and_then(|c| base.strip_suffix(c.as_str())?.strip_suffix('-').filter(|b| !b.is_empty()).map(str::to_string)); + Some(stripped.unwrap_or(base)) +} + /// Whether font `f` carries its own glyphs: a font program in its descriptor (a composite font's in /// its descendant's), or a Type 3 font's glyph procedures. A font that doesn't is drawn with a /// stand-in, whose glyphs say nothing about which installed face the document means. diff --git a/crates/pdf/src/import_text.rs b/crates/pdf/src/import_text.rs index dddb0075ec..373437cfa4 100644 --- a/crates/pdf/src/import_text.rs +++ b/crates/pdf/src/import_text.rs @@ -965,6 +965,12 @@ impl Families { Self(vectorcraft_text::FontDb::global().families().into_iter().map(|f| (norm(&f), f)).collect()) } + /// Just the families `names`, for tests that mustn't depend on the fonts installed. + #[cfg(test)] + pub fn of(names: &[&str]) -> Self { + Self(names.iter().map(|f| (norm(f), f.to_string())).collect()) + } + /// The family and style of a font with base (PostScript) name `name`, or of weight `weight` /// and slant `italic` when the name has no style; whether the family is available. pub fn resolve(&self, name: &str, weight: Option<u32>, italic: bool) -> (String, String, bool) { @@ -977,22 +983,73 @@ impl Families { if let Some((family, style)) = vectorcraft_text::FontDb::global().by_postscript_name(name) { return (family, style, true); } - let (fam, style) = name.split_once(['-', ',']).unwrap_or((name, "")); - let found = [fam, strip_ps(fam)].iter().find_map(|f| self.0.get(&norm(f)).cloned()); - let style = match spaced(strip_ps(style)).as_str() { - "" | "Roman" | "Book" | "Normal" | "Plain" => match (weight.is_some_and(|w| w >= 600) || style.contains("Bold"), italic) { - (true, true) => "Bold Italic".to_string(), - (true, false) => "Bold".to_string(), - (false, true) => "Italic".to_string(), - (false, false) => "Regular".to_string(), + // The longest part of the name before a hyphen (or the comma of `Arial,Bold`, ISO 32000-1 + // §9.6.3) that names an available family, the rest its style: a family can hold hyphens + // (`Noto-Sans-Bold` is Noto Sans, Bold). + let cuts = std::iter::once(name.len()).chain(name.rmatch_indices(['-', ',']).map(|(i, _)| i)); + for cut in cuts { + let (fam, style) = (name.get(..cut).unwrap_or(name), name.get(cut + 1..).unwrap_or("")); + if let Some(f) = [fam, strip_ps(fam)].iter().find_map(|f| self.0.get(&norm(f)).cloned()) { + return (f, style_of(style, weight, italic), true); + } + } + // Not available: split at a comma, or before the first part that is a style + // (`Helvetica-BoldOblique`, `Noto-Sans-Bold`, `AGaramondPro-Bold-SC700`); otherwise the + // whole name is the family (`Noto-Sans`, `MS-PGothic`). + let style_at = |i: usize| name.get(i + 1..).and_then(|rest| rest.split('-').next()).is_some_and(|part| is_style(strip_ps(part))); + let (fam, style) = match name.split_once(',') { + Some(split) => split, + None => match name.match_indices('-').map(|(i, _)| i).find(|&i| style_at(i)) { + Some(i) => (name.get(..i).unwrap_or(name), name.get(i + 1..).unwrap_or("")), + None => (name, ""), }, - s => s.to_string(), }; - match found { - Some(f) => (f, style, true), - None => (spaced(strip_ps(fam)).trim().to_string(), style, false), + let family = spaced(strip_ps(fam)).split(['-', ' ']).filter(|w| !w.is_empty()).collect::<Vec<_>>().join(" "); + (family, style_of(style, weight, italic), false) + } +} + +/// The style a PostScript name's `style` part names, or the one of weight `weight` and slant +/// `italic` when the part names none (`Roman`, `Book`…). +fn style_of(style: &str, weight: Option<u32>, italic: bool) -> String { + match spaced(strip_ps(style)).as_str() { + "" | "Roman" | "Book" | "Normal" | "Plain" => match (weight.is_some_and(|w| w >= 600) || style.contains("Bold"), italic) { + (true, true) => "Bold Italic".to_string(), + (true, false) => "Bold".to_string(), + (false, true) => "Italic".to_string(), + (false, false) => "Regular".to_string(), + }, + s => s.to_string(), + } +} + +/// Whether `s` is made of style words and their usual abbreviations (`BoldOblique`, `SemiboldIt`, +/// `XBold`, `W6`), any case: the last part of a font name that names its style. +fn is_style(s: &str) -> bool { + const WORDS: &str = "bd bk black blk bold book cn cnd compressed con condensed demi ex expanded ext extended extra hairline heavy hv it ita italic light lt md \ + med medium narrow normal obl oblique plain reg regular rg roman sb semi slanted smb super th thin ul ultra w wide x xb xl"; + let s = s.to_ascii_lowercase(); + let s = s.as_bytes(); + // Which starts of `s` the words and digit runs before them reach (a word break, so + // `XBold` is X, Bold even though `xb` also starts it). + let mut reached = vec![false; s.len() + 1]; + if let Some(r) = reached.first_mut() { + *r = !s.is_empty(); + } + for i in 0..s.len() { + if !reached.get(i).copied().unwrap_or(false) { + continue; + } + let rest = s.get(i..).unwrap_or_default(); + let digits = rest.iter().take_while(|b| b.is_ascii_digit()).count(); + let ends = WORDS.split_ascii_whitespace().filter(|w| rest.starts_with(w.as_bytes())).map(|w| i + w.len()); + for end in ends.chain((digits > 0).then_some(i + digits)) { + if let Some(r) = reached.get_mut(end) { + *r = true; + } } } + reached.last().copied().unwrap_or(false) } /// Hebrew or Arabic comes from a PDF in visual order (each glyph where it is drawn): put `t`'s text diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index e08d2e74ac..e60f3e98c5 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -406,6 +406,74 @@ fn font_names_resolve_to_available_families() { assert_eq!((family.as_str(), style.as_str(), found), ("Missing Sans Pro", "Bold Italic", false)); } +/// A family can hold hyphens (`Noto-Sans-Bold` is Noto Sans, Bold): the longest part of the name +/// before a hyphen that names an available family is the family, the rest its style. Synthetic +/// family names, so the host's fonts don't matter. +#[test] +fn hyphenated_font_names_resolve_to_the_longest_available_family() { + let f = crate::import_text::Families::of(&["Vctest", "Vctest Sans", "Vctest Sans CJK JP", "Vctest Mono"]); + let ok = |family: &str, style: &str| (family.to_string(), style.to_string(), true); + assert_eq!(f.resolve("HUHQIP+Vctest-Sans", None, false), ok("Vctest Sans", "Regular")); + assert_eq!(f.resolve("Vctest-Sans-Bold", None, false), ok("Vctest Sans", "Bold")); + assert_eq!(f.resolve("Vctest-Sans-Italic", None, false), ok("Vctest Sans", "Italic")); + assert_eq!(f.resolve("Vctest-Sans", Some(700), true), ok("Vctest Sans", "Bold Italic")); + assert_eq!(f.resolve("Vctest-Sans-CJK-JP", None, false), ok("Vctest Sans CJK JP", "Regular")); + // The family is there but not the style: the family, which then draws its closest style. + assert_eq!(f.resolve("Vctest-Mono-Bold", None, false), ok("Vctest Mono", "Bold")); + // A shorter family still takes the name when no longer one is available. + assert_eq!(f.resolve("Vctest-BoldOblique", None, false), ok("Vctest", "Bold Oblique")); + assert_eq!(f.resolve("Vctest,Bold", None, false), ok("Vctest", "Bold")); +} + +/// A missing font's name is split only at a comma (`Arial,Bold`) or before the first part that is +/// a style (`Family-BoldOblique`); otherwise the whole name is the family, so the missing font is +/// reported as `Vcmissing Sans`, not `Vcmissing`. +#[test] +fn a_missing_font_is_split_only_before_a_style() { + let f = crate::import_text::Families::of(&[]); + let missing = |family: &str, style: &str| (family.to_string(), style.to_string(), false); + assert_eq!(f.resolve("Vcmissing-Sans", None, false), missing("Vcmissing Sans", "Regular")); + assert_eq!(f.resolve("Vcmissing-Sans-CJK-JP", None, false), missing("Vcmissing Sans CJK JP", "Regular")); + assert_eq!(f.resolve("Vcmissing-Sans-BoldOblique", None, false), missing("Vcmissing Sans", "Bold Oblique")); + assert_eq!(f.resolve("VcmissingPro-SemiboldIt", None, false), missing("Vcmissing Pro", "Semibold It")); + assert_eq!(f.resolve("VcmissingPSMT-XBold", None, false), missing("Vcmissing", "XBold")); + assert_eq!(f.resolve("Vcmissing-Bold-SC700", None, false), missing("Vcmissing", "Bold-SC 700")); + assert_eq!(f.resolve("Vcmissing-Regular-Regular", None, false), missing("Vcmissing", "Regular-Regular")); + assert_eq!(f.resolve("Vcmissing,Bold", None, false), missing("Vcmissing", "Bold")); + assert_eq!(f.resolve("-Vcmissing", None, false), missing("Vcmissing", "Regular")); + assert_eq!(f.resolve("Vcmissing-Roman", Some(700), false), missing("Vcmissing", "Bold")); + assert_eq!(f.resolve("Vcmissing-", None, true), missing("Vcmissing", "Italic")); + assert_eq!(f.resolve("-Bold", None, false), missing("", "Bold")); +} + +/// A composite (Type 0) font's base name is its CIDFont's name, a hyphen and its CMap's +/// (`SomeFont-Italic-Identity-H`, ISO 32000-1 §9.7.6.1): the font is noted by its CIDFont's name, +/// the PostScript name of the font program (§9.7.4.1), so it is found among the installed fonts. +#[test] +fn a_composite_font_is_noted_by_its_cid_font_name() { + let noted = |font: &str| { + let resources = format!("/Font << /F1 {font} >>"); + let bytes = one_page("BT /F1 24 Tf 10 30 Td <0001> Tj ET", &resources, &[]); + let pdf = craft_pdf::syntax::Pdf::new(bytes).unwrap(); + let mut fonts = crate::import_scan::FontNames::new(); + let mut ocgs = crate::import_scan::Ocgs::read(&pdf); + crate::import_scan::scan_page(&pdf.pages()[0], &mut ocgs, false, &mut fonts, pdf.decode_limits().max_decoded_stream()).unwrap(); + fonts.into_values().map(|f| f.name).collect::<Vec<_>>() + }; + let type0 = |base: &str, enc: &str, descendant: &str| { + let info = "/CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >>"; + format!( + "<< /Type /Font /Subtype /Type0 /BaseFont /{base} /Encoding /{enc} /DescendantFonts [<< /Type /Font /Subtype /CIDFontType0 {descendant} {info} >>] >>" + ) + }; + assert_eq!(noted(&type0("MGZJFV+Vctest-Italic-Identity-H", "Identity-H", "/BaseFont /MGZJFV+Vctest-Italic")), ["MGZJFV+Vctest-Italic"]); + // No name in the descendant: the CMap's name comes off the end of the base name. + assert_eq!(noted(&type0("Vctest-Italic-UniJIS-UCS2-H", "UniJIS-UCS2-H", "")), ["Vctest-Italic"]); + // A base name without the CMap's is kept, as is a simple font's. + assert_eq!(noted(&type0("Vctest-Italic", "Identity-H", "")), ["Vctest-Italic"]); + assert_eq!(noted("<< /Type /Font /Subtype /Type1 /BaseFont /Vctest-Identity-H >>"), ["Vctest-Identity-H"]); +} + /// A value of the page's font dictionary that the reader can't parse (a name with a broken `#` /// escape, a number with a stray `-`) is left out when the page's fonts are noted, and the fonts /// after it are noted. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index fac518fdde..ce464cc58c 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (DXF export: LAYOUT objects write only DXF Reference group codes, for strict readers such as Autodesk Fusion, #3085) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (PDF import: fonts named with hyphens or with a composite font's CMap find the installed family) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -94,7 +94,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | VectorCraft `.vectorcraft` / `.vctemplate` | — | yes | yes | lossless JSON, versioned, save down to v1; property-tested round trips (`format/tests/prop_format.rs`); documents with a lot of path data are written as compact JSON, about a fifth of the size (#1492); a save falls back to a plain fsync and to writing elsewhere and copying in when the folder refuses the usual steps (#1625, #1649, part of #1620; not confirmed on a real network share); the size limits on embedded data also apply to files read from memory (#1783), and saving over a private file on Unix leaves no readable temporary copy beside it (#1778) | | Illustrator template `.ait` | open, save | yes | PDF-compatible only, from Save as Template (`.vctemplate` stays its default) | New from Template opens a saved `.ait` untitled with its layers and art (`tests_pdfedit.rs`) | | Illustrator `.ai` | open, save | yes (PDF-compatible + editing-data structure, File Info) | PDF-compatible, or legacy version 7 (layers and groups) | see above; no real-file corpus | -| PDF | open, place, save | yes (layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160) | +| PDF | open, place, save | yes (layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160) | | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CID-keyed CJK type not read; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as `<title>`, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`) | @@ -132,6 +132,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | PDF import finds an installed font whose PDF name holds hyphens (`Noto-Sans-Bold` is Noto Sans, Bold: the longest part before a hyphen that names an installed family) and a composite font by its CIDFont's name rather than its base name, which ends in the CMap's (`Name-Identity-H`, [ISO 32000-1 §9.7.6.1](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)); a missing font is split only before a style part (`Helvetica-BoldOblique`), so it is reported as `MS PGothic`, not `MS`; scores unchanged (estimated) | | 2026-10-31 | minor | DXF export (2000–2018): the LAYOUT objects wrote the paper image origin as a point at group codes 148 and 158, but PLOTSETTINGS defines 148 and 149 and no 158, so strict readers could reject the file (Autodesk Fusion reported "DXF File failed to insert", #3085). They now write 148/149, the shade plot mode, resolution and DPI (76–78, 2004 and later) and flag 1024 on the Model layout; the plot style ACDBPLACEHOLDER no longer carries a subclass marker. Test `r2000_and_later_files_have_the_structure_cad_apps_require` (required sections and table entries, handles and references, LAYOUT group codes); exports pass ezdxf's recover and audit; not tested in Fusion itself; scores unchanged | | 2026-10-31 | minor | `.ai`/EPS editing data: an envelope whose contents are being edited is written the other way round from one that isn't: its contents, a group on `%_` lines, then its dictionary, which holds the mesh that shapes them. Those contents were read as art, so the undistorted art drew over the distorted art the page draws. The group on `%_` lines before an envelope's dictionary is now left out whatever it holds (text in it stays as hidden text, as the dictionary's own does), as the envelope's mesh already was (#2405). Test `import::ai::tests::an_envelope_s_contents_being_edited_are_not_read_as_art`; checked locally against a user's file: it opens from its layers, 0.0% from its page (it was 9.7%, over the 5% limit); scores unchanged | | 2026-10-31 | minor | `.ai`/EPS editing data: a transparency (`Xy`) set by art inside a dictionary, as an area text's frame (its `/ConfiningPath`) or a mask's art sets one, stays the current one after the dictionary: the writer goes on from it, so the objects after such a text have no `Xy` of their own. It was dropped when the dictionary closed, and a user's file drew its logo, calligraphy, footer and type after an area text with the Lighten of the glow before it, so they faded into the light background. Test `import::ai::tests::a_transparency_set_in_a_dictionary_s_art_stays_after_it`; checked locally against that file: 8.1% → 1.7% from its page, so it opens from its layers (5% is the limit); scores unchanged | diff --git a/docs/gaps.md b/docs/gaps.md index 16da466298..eb8d42b54e 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G13: Direct Selection snaps a dragged line end square to straight paths and grazing curves; G13: gradient presets done; G1: Average & Join with a corner or smooth choice, Cmd+Alt+Shift+J, done; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G4: PDF import finds installed fonts whose PDF names hold hyphens or a composite font's CMap; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -330,6 +330,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Improved:** mixed paragraph alignments leave the existing Paragraph/Properties alignment buttons unselected; choosing an alignment still uses the range-aware command. Headless regressions, full integration CI and visual review pass. Other mixed paragraph fields remain; estimate unchanged. - **Improved:** Paragraph panel left/right/first-line indents and space before/after show blank when paragraphs in scope differ; uniform values still display and edits apply through `text.setFormat`. Headless regression in `panels/paragraph.rs`; estimate unchanged. - **Improved (#1258):** full font names (name ID 4) resolve the face instead of falling back, and Missing Fonts searches recognize the same aliases. Synthetic regressions cover loaded/cataloged fonts, localized names, real-family precedence and variable default faces. Windows font-service activation still needs reporter QA; estimate unchanged. +- **Improved:** PDF import finds an installed font whose PDF name holds hyphens (`Noto-Sans-Bold`, `Noto-Sans-CJK-JP`) or a composite font's CMap (`SomeFont-Italic-Identity-H`; ISO 32000-1 §9.7.6.1), and names a missing one by the whole name unless a style part follows (`MS-PGothic` is MS PGothic). Synthetic regressions in `crates/pdf/src/tests/import_fidelity.rs`; estimate unchanged. - **Done:** Paragraph panel menu › Roman Hanging Punctuation (#2756), per paragraph; estimate unchanged. - **Improved:** hanging punctuation (Roman Hanging Punctuation and Optical Margin Alignment) keeps its published amounts when justification scales glyphs, and Standard burasagari counts a hung line start as room; paragraph-level tests with both composers; estimate unchanged. - **Done:** Paragraph panel menu › Justification… (#2755): word and letter spacing, glyph scaling (Minimum, Desired, @@ -675,6 +676,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | G4: PDF import finds an installed font whose PDF name holds hyphens (`Noto-Sans-Bold` is Noto Sans, Bold: the longest part before a hyphen that names an installed family) and a composite font by its CIDFont's name rather than its base name, which ends in the CMap's (`Name-Identity-H`, [ISO 32000-1 §9.7.6.1](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)); a missing font is split only before a style part (`Helvetica-BoldOblique`), so it is reported as `MS PGothic`, not `MS`. Estimate unchanged. | | 2026-10-31 | minor | G13: Direct Selection snaps the end of an existing straight line, dragged by its end anchor, square to straight paths and grazing curves (Smart Guides › Geometric Guides: Snap to Perpendicular and Snap to Tangent), the case the public Snap to Perpendicular and Snap to Tangent pages add to drawing with the Line Segment and Pen tools (#2530). Scores and estimates unchanged. | | 2026-10-31 | minor | G8: a gradient mesh read from a file is budgeted: at most about a million quads per tessellation, and a mesh with more patches than that is malformed (#3592); estimate unchanged. | | 2026-10-30 | minor | G9: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | diff --git a/docs/type-parity.md b/docs/type-parity.md index dbf195b8a8..4de41b37c3 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Highlight Alternate Glyphs: an optional feature (such as `salt`) that changes a lam-alef ligature is highlighted again, only the required ligature staying clear, and a lam-alef with any combining mark (Arabic Extended-A/B/C included) counts as the ligature (#394); scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (PDF import finds installed fonts whose PDF names hold hyphens or a composite font's CMap; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -71,6 +71,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | PDF import finds an installed font whose PDF name holds hyphens (`Noto-Sans-Bold` is Noto Sans, Bold: the longest part before a hyphen that names an installed family) and a composite font by its CIDFont's name rather than its base name, which ends in the CMap's (`Name-Identity-H`, [ISO 32000-1 §9.7.6.1](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)); a missing font is split only before a style part (`Helvetica-BoldOblique`), so it is reported as `MS PGothic`, not `MS`; scores unchanged | | 2026-10-31 | minor | Highlight Alternate Glyphs: an optional feature (such as `salt`) that changes a lam-alef ligature is highlighted again, only the required ligature staying clear, and a lam-alef with any combining mark (Arabic Extended-A/B/C included) counts as the ligature (#394); scores unchanged | | 2026-10-30 | minor | Highlight Alternate Glyphs leaves the required lam-alef ligature unhighlighted also in older Arabic fonts (such as legacy Arial) that put it in `liga` rather than `rlig` (#394); scores unchanged | | 2026-10-30 | minor | Character panel menu › Show Snap to Glyph Options shows the Snap to Glyph section (Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides, Anchor Point; `view.snapToGlyph.options`) (#4232); scores unchanged | From bd0601c7809c5d81c7189741bba2d2747abbd8be Mon Sep 17 00:00:00 2001 From: marshiyar <57055687+marshiyar@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:21:04 -0700 Subject: [PATCH 058/260] EPS import: big operators are charged for the bytes and objects they touch (#3584) putinterval, copy of a string, roll, counttomark, clear to mark and cvn worked on up to 4 MiB or 100,000 objects for the one operation each is charged, so a small file looped over them could keep the importer busy for hours within the operation budget. Each now spends one operation per 256 bytes or objects. Fixes #3584 --- crates/eps/src/import/interp.rs | 21 +++++++++++++++++++-- crates/eps/src/import/tests.rs | 15 +++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index 5e8d12661b..68053f29bd 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -335,6 +335,12 @@ impl<'a> Interp<'a> { /// Count `ops` operations' worth of work against [`MAX_OPS`]: what an operator that costs /// far more than one operation (laying out type) does in a loop has to end too. + /// Charge for work on `n` bytes or objects in one operator: one operation per 256, as `search` + /// charges per 64 bytes, so a loop of big copies runs out of the budget. + fn spend_bytes(&mut self, n: usize) -> Res { + self.spend((n / 256) as u64) + } + pub fn spend(&mut self, ops: u64) -> Res { self.ops = self.ops.saturating_add(ops); if self.ops > MAX_OPS { @@ -661,6 +667,7 @@ impl<'a> Interp<'a> { let n = self.pop_count()?; let at = self.stack.len().checked_sub(n).ok_or(PsError::Ps("rangecheck", String::new()))?; if n > 0 { + self.spend_bytes(n)?; let k = j.rem_euclid(n as i64) as usize; if let Some(s) = self.stack.get_mut(at..) { s.rotate_right(k); @@ -687,6 +694,7 @@ impl<'a> Interp<'a> { self.pop_to_mark()?; } CountToMark => { + self.spend_bytes(self.stack.len())?; let n = self.stack.iter().rev().position(|o| matches!(o, Obj::Mark)).ok_or(PsError::Ps("unmatchedmark", String::new()))?; self.push(Obj::Int(n as i64))?; } @@ -860,6 +868,7 @@ impl<'a> Interp<'a> { } Cvn => { let s = self.pop_str()?; + self.spend_bytes(s.len())?; // The name is a copy of the string (a bigger one when bytes are replaced). self.alloc(s.len().saturating_mul(3))?; let n: Rc<str> = Rc::from(String::from_utf8_lossy(&s.borrow()).as_ref()); @@ -966,8 +975,14 @@ impl<'a> Interp<'a> { let src = self.pop()?; let at = self.pop_count()?; let written = match (self.pop()?, src) { - (Obj::Array { items, .. }, Obj::Array { items: from, .. }) => items.write(at, &from.to_vec()), - (Obj::Str(s), Obj::Str(from)) => s.write(at, &from.to_vec()), + (Obj::Array { items, .. }, Obj::Array { items: from, .. }) => { + self.spend_bytes(from.len())?; + items.write(at, &from.to_vec()) + } + (Obj::Str(s), Obj::Str(from)) => { + self.spend_bytes(from.len())?; + s.write(at, &from.to_vec()) + } _ => return ps_err("typecheck", ""), }; if !written { @@ -1171,6 +1186,7 @@ impl<'a> Interp<'a> { /// The objects above the topmost mark, which is removed. fn pop_to_mark(&mut self) -> Res<Vec<Obj>> { + self.spend_bytes(self.stack.len())?; let at = self.stack.iter().rposition(|o| matches!(o, Obj::Mark)).ok_or(PsError::Ps("unmatchedmark", String::new()))?; let items = self.stack.split_off(at + 1); self.stack.pop(); @@ -1202,6 +1218,7 @@ impl<'a> Interp<'a> { } Obj::Str(s) => { let from = self.pop_str()?.to_vec(); + self.spend_bytes(from.len())?; if !s.write(0, &from) { return ps_err("rangecheck", "copy"); } diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index d722078b77..aa97f32cb5 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -1307,6 +1307,21 @@ fn search_in_a_loop_runs_out_of_the_budget() { runs_out_of_budget(&format!("{make} {{ h n search {{ pop pop pop }} {{ pop }} ifelse }} loop")); } +/// #3584: operators that touch up to 4 MiB or 100,000 objects are charged for it, so a loop of them +/// runs out of the operation budget instead of keeping the importer busy for hours. +#[test] +fn big_operators_in_a_loop_run_out_of_the_budget() { + let strings = "/a 4194304 string def /b 4194304 string def"; + for body in [ + format!("{strings} {{ a 0 b putinterval }} loop"), + format!("{strings} {{ b a copy pop }} loop"), + "99990 { 0 } repeat { 99990 1 roll } loop".to_string(), + "mark 99990 { 0 } repeat { counttomark pop } loop".to_string(), + ] { + runs_out_of_budget(&body); + } +} + /// #3568: an image dictionary with more data sources than colour components is a `rangecheck`. #[test] fn an_image_with_more_data_sources_than_components_is_refused() { From feb12cf3126f26fd5106a89ed8d21c4238e91681 Mon Sep 17 00:00:00 2001 From: marshiyar <57055687+marshiyar@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:43:20 -0700 Subject: [PATCH 059/260] Swatch libraries: a device name with an extension gets the - before its first dot (#3602) CON.txt became CON.txt-.json, whose first part is still CON. It is now CON-.txt.json. --- crates/engine/src/cmd/swatchlib.rs | 7 +++++-- crates/engine/src/tests/swatchlib.rs | 7 +++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index d3652aa4e1..50033eff77 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -332,14 +332,17 @@ fn library_tab_name(file: &str, lib_name: &str) -> String { /// The file name of library `name` with extension `ext`: characters file systems reject become /// `-`, and dots and spaces at either end are dropped. A name with nothing left is `Library`, and -/// one that is a Windows device name (`CON`, `NUL`, `COM1`…) gets a `-` after it. +/// one that is a Windows device name (`CON`, `NUL`, `COM1`…, also with an extension) gets a `-` +/// after its first part (`CON-.json`, `CON-.txt.json`). pub fn library_file_name(name: &str, ext: &str) -> String { let base: String = name.chars().map(|c| if "/\\:*?\"<>|".contains(c) || c.is_control() { '-' } else { c }).collect(); let base = base.trim_matches(['.', ' ']); if base.is_empty() { format!("Library.{ext}") } else if crate::file_access::is_device_name(base) { - format!("{base}-.{ext}") + // The part before the first dot is what makes it a device, so the `-` goes there. + let (stem, rest) = base.split_once('.').map_or((base, String::new()), |(stem, rest)| (stem, format!(".{rest}"))); + format!("{stem}-{rest}.{ext}") } else { format!("{base}.{ext}") } diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index d6c9f84520..7337d6b744 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -642,11 +642,14 @@ fn gradient_libraries_are_listed_and_gradient_swatches_rename_and_take_new_gradi #[test] fn a_library_file_name_is_never_a_windows_device_name() { use crate::cmd::swatchlib::library_file_name; - for (title, ext) in [("CON", "json"), ("nul", "json"), ("Com1", "acb"), ("LPT9", "ase"), ("aux.", "json")] { + for (title, ext) in + [("CON", "json"), ("nul", "json"), ("Com1", "acb"), ("LPT9", "ase"), ("aux.", "json"), ("CON.txt", "json"), ("nul.tar.gz", "acb")] + { let file = library_file_name(title, ext); assert!(!crate::file_access::is_device_name(&file), "{title}: {file}"); assert!( - file.ends_with(&format!(".{ext}")) && file.to_ascii_lowercase().contains(&title.trim_end_matches('.').to_ascii_lowercase()), + file.ends_with(&format!(".{ext}")) + && file.to_ascii_lowercase().starts_with(&title.split('.').next().unwrap_or_default().to_ascii_lowercase()), "{title}: {file}" ); } From 811ba8727bd65b65d0f933f846bfe6ec07f9a581 Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Sat, 31 Oct 2026 13:27:50 +0430 Subject: [PATCH 060/260] Fix #3604: automation file access refuses an NTFS alternate data stream name on Windows With write root ...\out, a save to ...\out\x.svg:evil was accepted: it stays inside the root, but writes a hidden stream no folder listing shows. A ':' in any name after the drive is now refused with the device names. The check is a plain name test, so it is covered on every platform; the check-then-open race (item 1 of the report) is a documented limitation and is not touched. --- crates/engine/src/file_access.rs | 43 ++++++++++++++++++++++++++++++-- docs/control-protocol.md | 5 ++-- docs/mcp.md | 3 ++- 3 files changed, 46 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 56db72a222..d110149dac 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -213,8 +213,10 @@ fn resolve(path: &str) -> Result<PathBuf, String> { return Err("automation path rejected: path is empty".into()); } // Checked as given: making `…\NUL` absolute gives the device path `\\.\NUL` on Windows. - if cfg!(windows) && Path::new(path).components().any(|c| matches!(c, Component::Normal(n) if is_device_name(&n.to_string_lossy()))) { - return Err(format!("automation path rejected: reserved device names are not allowed: {path}")); + if cfg!(windows) + && let Some(why) = windows_name_refusal(path) + { + return Err(format!("automation path rejected: {why}: {path}")); } let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {path}: {e}"))?; // The names below the nearest existing folder, last first. @@ -280,6 +282,18 @@ pub(crate) fn is_device_name(component: &str) -> bool { matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT") } +/// Why Windows would not take `path` as an ordinary file name, for the first of its components +/// that is a device name, or holds a `:` (a drive letter's own colon belongs to the prefix, not to +/// a name, so only a stream such as `x.svg:evil` has one). (Judged by name alone, so it can be +/// tested on any platform; `resolve` applies it on Windows only.) +fn windows_name_refusal(path: &str) -> Option<&'static str> { + Path::new(path).components().find_map(|c| match c { + Component::Normal(n) if is_device_name(&n.to_string_lossy()) => Some("reserved device names are not allowed"), + Component::Normal(n) if n.to_string_lossy().contains(':') => Some("alternate data streams are not allowed"), + _ => None, + }) +} + #[cfg(test)] mod tests { use super::*; @@ -497,4 +511,29 @@ mod tests { assert!(!is_device_name(f), "{f}"); } } + + /// #3604: on Windows `x.svg:evil` writes a hidden NTFS alternate data stream of `x.svg`, which + /// stays inside the root yet shows in no folder listing, so a `:` in any component after the + /// drive is refused (a drive letter's own colon is not a component). + #[test] + fn alternate_data_streams_are_refused() { + for p in ["x.svg:evil", "out/x.svg:evil", "out/x.svg:evil:$DATA", "out/sub:evil/x.svg", "out/x.svg::$DATA", "out/:evil"] { + assert_eq!(windows_name_refusal(p), Some("alternate data streams are not allowed"), "{p}"); + } + for p in ["x.svg", "out/x.svg", "out/a b.svg", "out/x.svg.evil", "out/NUL"] { + assert_ne!(windows_name_refusal(p), Some("alternate data streams are not allowed"), "{p}"); + } + assert_eq!(windows_name_refusal("out/NUL"), Some("reserved device names are not allowed")); + assert_eq!(windows_name_refusal("out/x.svg"), None); + } + + #[cfg(windows)] + #[test] + fn windows_refuses_a_stream_inside_a_write_root() { + let (base, roots) = folders("streams"); + let e = roots.check(&s(base.join("out").join("x.svg:evil")), Access::Write).unwrap_err(); + assert!(e.contains("alternate data streams"), "{e}"); + assert_eq!(roots.check(&s(base.join("out/x.svg")), Access::Write), Ok(())); + let _ = std::fs::remove_dir_all(base); + } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 2f2a86d26f..1e718c9da5 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1,6 +1,6 @@ # Control protocol -> **Last updated:** 2026-10-25 · **Change:** Object → Expand… dimmed while the selection has an appearance Expand Appearance expands (`object.expand.info`'s `appearance`, #3089); previously: brush library panels (`window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary`); previously: Transform Each opens on the values it was last confirmed with; its Copy button confirms with `copy: true` (#1732); previously: panel docking on craft-ui's layout: `ui.docking`, the parameters of `window.panel.float` and `window.panel.dock`; previously: `ui.screenshot`'s 64 MiB inline-PNG cap and its path-plus-data downgrade; symbol library panels (`window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary`); synthetic input budgets (#1709); bounded transport waits (#1726). +> **Last updated:** 2026-10-31 · **Change:** Confining file access refuses a `:` in a name after the drive on Windows, an NTFS alternate data stream such as `x.svg:evil` (#3604); previously: Object → Expand… dimmed while the selection has an appearance Expand Appearance expands (`object.expand.info`'s `appearance`, #3089); previously: brush library panels (`window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary`); previously: Transform Each opens on the values it was last confirmed with; its Copy button confirms with `copy: true` (#1732); previously: panel docking on craft-ui's layout: `ui.docking`, the parameters of `window.panel.float` and `window.panel.dock`; previously: `ui.screenshot`'s 64 MiB inline-PNG cap and its path-plus-data downgrade; symbol library panels (`window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary`); synthetic input budgets (#1709); bounded transport waits (#1726). `vectorcraft --control <port>` listens on `127.0.0.1:<port>` (loopback only). The port must be a number from 1 to 65535 (`--control=<port>` works too), given once; otherwise the app prints an error and exits @@ -68,7 +68,7 @@ writes (save, export, package, captures, library saves…) inside a write root; ordinary error reply. Paths are made absolute against the app's working directory, links are followed (for a file that doesn't exist yet, its folder's), and the comparison is by whole folder names (`/work2` is not inside `/work`), ignoring case on Windows; `..` below a folder that doesn't exist, a link that leads -nowhere and Windows device names are refused. A root left out grants none of its access. The roots must be +nowhere, Windows device names and, on Windows, a `:` in any name after the drive (an NTFS alternate data stream such as `x.svg:evil`) are refused. A root left out grants none of its access. The roots must be existing folders, or the app doesn't start; without `--control` they are ignored. See `docs/mcp.md` › Confining file access for the details. @@ -955,6 +955,7 @@ hidden tab (whose frames the browser pauses) answers when it is shown again. | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Confining file access: on Windows a `:` in a name after the drive (an NTFS alternate data stream) is refused with the device names (#3604). | | 2026-10-25 | minor | Panel docking on craft-ui's layout: `ui.docking`, the floating and dock parameters, native floating windows. | | 2026-10-24 | minor | Documented the brush library panel commands (`window.brushLibrary`, `.other`, `ui.saveBrushLibrary`, `window.userBrushLibrary1`…`10`). | | 2026-10-24 | minor | Documented `ui.screenshot`'s 64 MiB inline-PNG reply cap: with `path` the file is still written and `pngBase64` is omitted when over the cap; a path-less `data: true` request fails before encoding. | diff --git a/docs/mcp.md b/docs/mcp.md index 81681d6c2f..90ce4f6c3a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -125,7 +125,8 @@ the suite) keep the agent to the folders you give it: doesn't exist is refused, as is a link that leads nowhere (writing through it would create its target). The result is compared with the root by whole folder names: `/work2/x` is not inside `/work`. On Windows case is ignored, UNC paths (`\\server\share\…`) are resolved like drive-letter ones, and - device names (`CON`, `NUL`, `COM1`…) are refused. + device names (`CON`, `NUL`, `COM1`…) and a `:` in a name after the drive (an NTFS alternate data stream + such as `x.svg:evil`, which hides data in a stream no folder listing shows) are refused. - With `--connect`, the server makes the paths of `open_file`, `save_file`, `export` (`path` or `options.path`) and `screenshot {path}` absolute against its own working directory before it sends them to the app. Paths inside `run_command` and `command_batch` params go to the app as given, and the From f9a523b55e01e1706343729275a6f6e0d3d61bf0 Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Sat, 31 Oct 2026 12:46:52 +0430 Subject: [PATCH 061/260] Docs: Snapping is no longer a main gap in the parity table (#2530) The tangent and perpendicular case is done for every tool the public pages name; its evidence stays in the revision row and in gaps.md and ui-parity.md. --- docs/target-app-parity.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0f2883ae6b..58e42441c6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -141,10 +141,10 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), guides lost (#779), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC/JPEG 2000 import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. | | View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated; document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | | View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated | -| Guides, grids, smart guides, snapping, rulers | 3 | 80% | 30.0's tangent snapping to curves and perpendicular snapping to straight segments for lines drawn with the Pen, Curvature and Line Segment tools and for an existing line's end dragged with Direct Selection (Preferences › Smart Guides › Geometric Guides and Control bar › Snapping, #2530; the public pages name no other tool), "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score unchanged | -| Guides, grids, smart guides, snapping, rulers | 3 | 80% | 30.0's tangent snapping to curves and perpendicular snapping to straight segments for lines drawn with the Pen, Curvature and Line Segment tools and for an existing line's end dragged with Direct Selection (Preferences › Smart Guides › Geometric Guides and Control bar › Snapping, #2530; the public pages name no other tool), "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), global/artboard ruler mode switch, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score unchanged | -| Guides, grids, smart guides, snapping, rulers | 3 | 80% | 30.0's tangent snapping to curves and perpendicular snapping to straight segments for lines drawn with the Pen, Curvature and Line Segment tools and for an existing line's end dragged with Direct Selection (Preferences › Smart Guides › Geometric Guides and Control bar › Snapping, #2530; the public pages name no other tool), "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), video rulers, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; status-bar X/Y uses the active ruler origin and General units | -| Guides, grids, smart guides, snapping, rulers | 3 | 80% | 30.0's tangent snapping to curves and perpendicular snapping to straight segments for lines drawn with the Pen, Curvature and Line Segment tools and for an existing line's end dragged with Direct Selection (Preferences › Smart Guides › Geometric Guides and Control bar › Snapping, #2530; the public pages name no other tool), "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), global/artboard ruler mode switch and video rulers, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; status-bar X/Y uses the active ruler origin and General units | +| Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score unchanged | +| Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), global/artboard ruler mode switch, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score unchanged | +| Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), video rulers, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; status-bar X/Y uses the active ruler origin and General units | +| Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), global/artboard ruler mode switch and video rulers, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; status-bar X/Y uses the active ruler origin and General units | | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | From a5a7c4638ae214e7eb31de6dcbcf0c40632e11a3 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 06:28:15 +0100 Subject: [PATCH 062/260] Fix closing smart quote read as opening after same-glyph quote Found while testing crates/doc/src/setup.rs:111-113 (Quotes::opens / is_open), used by Quotes::apply at :122-131 Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- crates/doc/src/setup.rs | 36 ++++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index 875fcf3a0c..ca08eca4a4 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -107,14 +107,17 @@ impl Quotes { /// Single-quote pairs offered by Document Setup. pub const SINGLE_CHOICES: &[[char; 2]] = &[['‘', '’'], ['‚', '‘'], ['‚', '’'], ['’', '’'], ['‹', '›'], ['›', '‹'], ['『', '』'], ['\'', '\'']]; - /// Is `c` one of these opening quotes? + /// Is `c` one of these opening quotes? A typographic glyph that is also a closing quote does not + /// count; a straight quote has no direction, so it still opens. fn is_open(&self, c: char) -> bool { - c == self.double[0] || c == self.single[0] + (c == self.double[0] || c == self.single[0]) && (c.is_ascii() || (c != self.double[1] && c != self.single[1])) } /// A quote opens after nothing, whitespace, an opening bracket, a dash or another opening quote. - fn opens(&self, prev: Option<char>) -> bool { - prev.is_none_or(|p| p.is_whitespace() || matches!(p, '(' | '[' | '{' | '—' | '–') || self.is_open(p)) + /// `quote_opened` says whether `prev` is a quote this conversion just produced, and if so whether + /// it opened; that settles glyphs which serve as both opening and closing quote. + fn opens(&self, prev: Option<char>, quote_opened: Option<bool>) -> bool { + prev.is_none_or(|p| p.is_whitespace() || matches!(p, '(' | '[' | '{' | '—' | '–') || quote_opened.unwrap_or_else(|| self.is_open(p))) } /// `text` with straight quotes (`"` and `'`) replaced by these quotes: opening or closing by @@ -122,11 +125,16 @@ impl Quotes { /// and is updated to its last character, so text can be converted in pieces. pub fn apply(&self, text: &str, prev: &mut Option<char>) -> String { let mut out = String::with_capacity(text.len()); + let mut quote_opened = None; for c in text.chars() { - let r = match c { - '"' => self.double[usize::from(!self.opens(*prev))], - '\'' => self.single[usize::from(!self.opens(*prev))], - c => c, + quote_opened = match c { + '"' | '\'' => Some(self.opens(*prev, quote_opened)), + _ => None, + }; + let r = match (c, quote_opened) { + ('"', Some(open)) => self.double[usize::from(!open)], + ('\'', Some(open)) => self.single[usize::from(!open)], + (c, _) => c, }; out.push(r); *prev = Some(r); @@ -326,6 +334,18 @@ mod tests { assert_eq!((a.as_str(), b.as_str()), ("“", "“")); } + #[test] + fn closing_quote_equal_to_other_kinds_opening_quote_still_closes() { + let q = Quotes { double: ['”', '”'], single: ['‘', '’'] }; + let mut prev = None; + assert_eq!(q.apply("'\"a\"'", &mut prev), "‘”a”’"); + let q = Quotes { double: ['"', '"'], single: ['‘', '’'] }; + let mut prev = None; + assert_eq!(q.apply("'\"a\"'", &mut prev), "‘\"a\"’"); + let mut prev = None; + assert_eq!(q.apply("\"'a'\"", &mut prev), "\"‘a’\""); + } + #[test] fn bleed_grows_the_artboard() { let s = DocSetup { bleed: [9.0, 9.0, 4.0, 2.0], ..Default::default() }; From d0e1a045c166e9793c51cce6efe0d993e50f4356 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:25:04 +0000 Subject: [PATCH 063/260] Show 0.00 instead of -0.00 in Unit::readout for tiny negatives Found while testing crates/doc/src/units.rs:163-165 (readout) Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- crates/doc/src/tests/units.rs | 7 +++++++ crates/doc/src/units.rs | 5 ++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/tests/units.rs b/crates/doc/src/tests/units.rs index 909a0adf3b..88075a5dc0 100644 --- a/crates/doc/src/tests/units.rs +++ b/crates/doc/src/tests/units.rs @@ -144,3 +144,10 @@ fn mixed_mul_div() { assert_eq!(Unit::Points.parse("10*2/5"), Some(4.0)); assert_eq!(Unit::Points.parse("10*2/5 px"), Some(Unit::Pixels.to_pt(4.0))); } + +#[test] +fn readout_has_no_negative_zero() { + assert_eq!(Unit::Points.readout(-0.001), "0.00 pt"); + assert_eq!(Unit::Points.readout(-0.0), "0.00 pt"); + assert_eq!(Unit::Points.readout(-12.5), "-12.50 pt"); +} diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index 2c1fc86534..6a5edf75ac 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -161,7 +161,10 @@ impl Unit { /// A point value as the canvas measurement labels show it: two decimals and the suffix /// (`12.50 mm`). pub fn readout(self, pt: f64) -> String { - format!("{:.2} {}", self.from_pt(pt), self.suffix()) + let s = format!("{:.2}", self.from_pt(pt)); + // A small negative value rounds to `-0.00`; show it as `0.00`. + let s = if s == "-0.00" { "0.00" } else { &s }; + format!("{} {}", s, self.suffix()) } } From 18709b0b63a365658a0d1ed09b88648a84e5748c Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 05:06:34 +0100 Subject: [PATCH 064/260] Reject multiple leading '#' in the colour panel hex parser Found while testing crates/ui-egui/src/panels/color.rs:199-205 (parse_hex) Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- crates/ui-egui/src/panels/color.rs | 3 ++- crates/ui-egui/src/panels/color/tests.rs | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index f9567e9888..00e32808a5 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -197,7 +197,8 @@ pub fn hex_digits(c: &Color) -> String { /// Parse a hex field (`E67828`, `#e67828`, `fff`). pub fn parse_hex(s: &str) -> Option<Color> { - let s = s.trim().trim_start_matches('#'); + let s = s.trim(); + let s = s.strip_prefix('#').unwrap_or(s); if !(s.len() == 3 || s.len() == 6) || !s.chars().all(|c| c.is_ascii_hexdigit()) { return None; } diff --git a/crates/ui-egui/src/panels/color/tests.rs b/crates/ui-egui/src/panels/color/tests.rs index 548851e6b8..cf02301a62 100644 --- a/crates/ui-egui/src/panels/color/tests.rs +++ b/crates/ui-egui/src/panels/color/tests.rs @@ -673,4 +673,6 @@ fn spectrum_and_hex() { assert_eq!(parse_hex("#fff").unwrap().to_hex(), "#ffffff"); assert!(parse_hex("zz").is_none()); assert!(parse_hex("12345").is_none()); + assert!(parse_hex("##e67828").is_none()); + assert!(parse_hex("###fff").is_none()); } From 3602bd6ea358b4498dd5f91129ca1f0ec28639ae Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sat, 31 Oct 2026 06:23:05 +0300 Subject: [PATCH 065/260] fix(ai-import): type from the text document takes its character style's attributes Type made from an Illustrator file's text document took each character attribute its run doesn't set from the document's base attributes, not from the character style the run names ([Normal Character Style] or another of the file's). Where the two differ the type came in wrong: a file whose base fill is white and whose Normal Character Style is black came in with its text white, invisible, so the layers differed from the page wherever the page's own type didn't stand in for it. A run now takes its own attributes, then its character style's (and the styles that one is based on, up to 16), then the document's. --- crates/eps/src/import/ate.rs | 70 ++++++++++++++++++++++----- crates/eps/src/import/tests_native.rs | 40 +++++++++++++++ docs/file-format-parity.md | 7 +-- 3 files changed, 102 insertions(+), 15 deletions(-) diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 875a046fc0..a5b22f92d2 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -235,6 +235,11 @@ fn read(bytes: &[u8]) -> Option<Val> { } } +/// Most character styles read of a text document, and most styles a run's style is followed +/// through to the ones they are based on. +const MAX_SHEETS: usize = 4096; +const MAX_SHEETS_BASED_ON: usize = 16; + /// Most frames read of one story, and most path segments of a frame. const MAX_FRAMES: usize = 4096; const MAX_SEGMENTS: usize = 1 << 16; @@ -309,6 +314,9 @@ pub(super) struct Texts { /// The character and paragraph styles a story starts from. defaults: Val, para_defaults: Val, + /// The document's character styles (`[Normal Character Style]` first), each a name, the + /// character style it is based on (key 5, an index into these) and its attributes (key 6). + char_sheets: Vec<Val>, frames: Vec<Val>, } @@ -352,6 +360,16 @@ impl Texts { fonts, defaults: main.get("2")?.clone(), para_defaults: main.get("3").cloned().unwrap_or(Val::Dict(BTreeMap::new())), + char_sheets: doc + .get("0")? + .get("5") + .and_then(|s| s.get("0")) + .map(Val::list) + .unwrap_or_default() + .iter() + .take(MAX_SHEETS) + .map(|s| s.get("0").cloned().unwrap_or(Val::Dict(BTreeMap::new()))) + .collect(), frames: doc.get("0")?.get("8")?.get("0")?.list().to_vec(), }) } @@ -440,8 +458,7 @@ impl Texts { let mut runs = vec![]; for run in s.get("0")?.get("6").map(|p| p.get("0").map(Val::list).unwrap_or_default()).unwrap_or_default() { let n = run.get("1").and_then(Val::num)? as usize; - let props = run.get("0").and_then(|r| r.get("0")).and_then(|r| r.get("6")); - runs.push((n, self.style(props))); + runs.push((n, self.style(run.get("0").and_then(|r| r.get("0"))))); } if runs.is_empty() { runs.push((text.chars().count(), self.style(None))); @@ -465,9 +482,19 @@ impl Texts { } } - /// A character style: its own keys, else the document's. - fn style(&self, s: Option<&Val>) -> Style { - let pick = |k: &str| s.and_then(|s| s.get(k)).or_else(|| self.defaults.get(k)); + /// A run's character style (`run`: its attributes, key 6, and the character style it is based + /// on, key 5): its own keys, else those of its character style and the ones that is based on, + /// else the document's. + fn style(&self, run: Option<&Val>) -> Style { + // The run's attributes, then its character style's, then the styles each is based on. + let mut chain = vec![]; + let mut at = run; + for _ in 0..=MAX_SHEETS_BASED_ON { + let Some(style) = at else { break }; + chain.extend(style.get("6")); + at = style.get("5").and_then(Val::num).filter(|i| i.is_finite() && *i >= 0.0).and_then(|i| self.char_sheets.get(i as usize)); + } + let pick = |k: &str| chain.iter().find_map(|s| s.get(k)).or_else(|| self.defaults.get(k)); let num = |k: &str| pick(k).and_then(Val::num); let on = |k: &str| !matches!(pick(k), Some(Val::Bool(false))); let font = num("0").and_then(|i| self.fonts.get(i as usize)).filter(|f| !f.is_empty()).cloned(); @@ -899,8 +926,14 @@ mod tests { #[test] fn right_to_left_paragraphs_swap_left_and_right_alignment() { - let texts = - Texts { stories: vec![], fonts: vec![], defaults: Val::Dict(BTreeMap::new()), para_defaults: read(b"/33 1").unwrap(), frames: vec![] }; + let texts = Texts { + stories: vec![], + fonts: vec![], + defaults: Val::Dict(BTreeMap::new()), + para_defaults: read(b"/33 1").unwrap(), + char_sheets: vec![], + frames: vec![], + }; let justify = |own: &[u8]| para_style(&texts.para(Some(&read(own).unwrap())), 1.0).justify; // Right to left from the document's defaults, or the paragraph's own. assert_eq!(justify(b"/0 0"), Justify::Right); @@ -915,9 +948,15 @@ mod tests { /// dimension's is) lies in a tall box, not a wide one. #[test] fn point_type_lies_along_its_baseline() { - let para = - Texts { stories: vec![], fonts: vec![], defaults: Val::Dict(BTreeMap::new()), para_defaults: Val::Dict(BTreeMap::new()), frames: vec![] } - .para(None); + let para = Texts { + stories: vec![], + fonts: vec![], + defaults: Val::Dict(BTreeMap::new()), + para_defaults: Val::Dict(BTreeMap::new()), + char_sheets: vec![], + frames: vec![], + } + .para(None); let mut s = story(" 80 mm ", &[0.0], ¶); let size = |s: &Story| s.region((0.0, 0.0), Affine::IDENTITY).map(|r| (r.width(), r.height())).unwrap(); let (w, h) = size(&s); @@ -933,8 +972,14 @@ mod tests { /// that doesn't say, goes by its letters. #[test] fn right_to_left_paragraphs_set_their_direction() { - let texts = - Texts { stories: vec![], fonts: vec![], defaults: Val::Dict(BTreeMap::new()), para_defaults: read(b"/33 1").unwrap(), frames: vec![] }; + let texts = Texts { + stories: vec![], + fonts: vec![], + defaults: Val::Dict(BTreeMap::new()), + para_defaults: read(b"/33 1").unwrap(), + char_sheets: vec![], + frames: vec![], + }; let direction = |own: &[u8]| para_style(&texts.para(Some(&read(own).unwrap())), 1.0).direction; assert_eq!(direction(b"/0 2"), Some(ParaDirection::RightToLeft), "from the document's defaults"); assert_eq!(direction(b"/0 2 /33 0"), None, "the paragraph's own"); @@ -973,6 +1018,7 @@ mod tests { fonts: vec![], defaults: Val::Dict(BTreeMap::new()), para_defaults: Val::Dict(BTreeMap::new()), + char_sheets: vec![], frames: vec![read(doc.as_bytes()).unwrap()], }; texts.frame(0) diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 0f34869b79..ee4beca057 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -841,6 +841,46 @@ fn type_on_a_hidden_layer_comes_from_the_text_document() { assert!(!r.warnings.iter().any(|w| w.contains("couldn't be read")), "{:?}", r.warnings); } +/// A run that sets no colour of its own takes its character style's (here `[Normal Character +/// Style]`, black), not the text document's base attributes (here white, which hid the type). +/// A style takes what it doesn't set from the style it is based on, and a run's own setting wins. +#[test] +fn type_from_the_text_document_takes_its_character_styles_attributes() { + let own_fill = "/53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> "; + let run = |style: u8| format!("/5 {style} /6 << /0 0 /1 14.0 >>"); + let doc = text_document(&[ + ("Normal\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), + ("Based\r", 0, (8200.0, 8170.0), (0.0, 0.0), 0.0), + ("Own\r", 0, (8200.0, 8160.0), (0.0, 0.0), 0.0), + ]) + // The first two runs set no colour, the second of the style based on the normal one. + .replacen(own_fill, "", 2) + .replacen(&run(0), "/5 X", 1) + .replacen(&run(0), &run(1), 1) + .replacen("/5 X", &run(0), 1) + // The document's base attributes: grey level 1, white, with auto leading. + .replacen("/2 << /1 12.0 >>", "/2 << /1 12.0 /4 true /53 << /99 /SimplePaint /0 << /0 0 /1 [ 1.0 1.0 ] >> >> >>", 1) + // Its character styles: the normal one black with 18-point leading, and one based on it in red. + .replacen( + "/0 << /1 <<", + "/0 << /5 << /0 [ << /0 << /0 ([Normal Character Style]) /6 << /4 false /5 18.0 \ + /53 << /99 /SimplePaint /0 << /0 1 /1 [ 1.0 0.0 0.0 0.0 ] >> >> >> >> >> \ + << /0 << /0 (Red) /5 0 /6 << /53 << /99 /SimplePaint /0 << /0 1 /1 [ 1.0 1.0 0.0 0.0 ] >> >> >> >> >> ] >> /1 <<", + 1, + ); + let spare = text_object(0) + &text_object(1) + &text_object(2); + let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &spare)), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + let texts = text_of(&r.document.layers[1]); + assert_eq!(texts.iter().map(|t| t.plain_text()).collect::<Vec<_>>(), ["Normal", "Based", "Own"], "{:?}", r.warnings); + let style = |i: usize| (texts[i].runs[0].style.fill.clone(), texts[i].runs[0].style.leading); + let solid = vectorcraft_color::Paint::solid; + use vectorcraft_color::Color; + assert_eq!(style(0), (solid(Color::rgb(0.0, 0.0, 0.0)), Some(18.0)), "the normal style's"); + assert_eq!(style(1), (solid(Color::rgb(1.0, 0.0, 0.0)), Some(18.0)), "its style's colour, the leading of the one it's based on"); + assert_eq!(style(2), (solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), Some(18.0)), "the run's own colour"); +} + #[test] fn type_from_the_text_document_keeps_its_case_setting() { // Key 12 of a character style is its case: 1 Small Caps, 2 All Caps. The characters stay as diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 9c866d4223..bab11248d5 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (SVG export and Expand: a gradient mesh patch is cut no finer than its colour changes) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (type from an Illustrator file's text document takes the attributes of its character style) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -84,8 +84,8 @@ private editing data. VectorCraft: ### Illustrator's private editing data -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing; the page's drawing of it (often in pieces) is left out. Where the text document can't say (a frame of another kind, or a document that doesn't agree with the page), type that shows comes from the page into its text object's place (no group around it), and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5%, where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing; the page's drawing of it (often in pieces) is left out. Where the text document can't say (a frame of another kind, or a document that doesn't agree with the page), type that shows comes from the page into its text object's place (no group around it), and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5%, where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. Where the text document can't say (a frame of another kind, or a document that doesn't agree with the page), type that shows comes from the page into its text object's place (no group around it), and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5%, where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. Where the text document can't say (a frame of another kind, or a document that doesn't agree with the page), type that shows comes from the page into its text object's place (no group around it), and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5%, where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. ## Format by format @@ -132,6 +132,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | `.ai`/EPS editing data: type made from the file's text document took each character attribute its run doesn't set from the document's base attributes, not from the character style the run names (`[Normal Character Style]` or another of the file's, and the styles each is based on). Where they differ the type came in wrong: a user's file whose base fill is white and whose Normal Character Style is black came in with its text white, so most of its type was missing wherever the page's own type didn't stand in for it. A run now takes its own attributes, then its character style's, then the document's ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html)). Test `import::tests_native::type_from_the_text_document_takes_its_character_styles_attributes`; checked locally against 377 users' files: none newly opens from its PDF part, and with #4791 that file opens from its layers (6.3% → 1.1% from its page); scores unchanged | | 2026-10-31 | minor | SVG export (and Object › Expand, EPS, DXF, EMF and the other outputs that cut a gradient mesh into flat pieces): each patch was cut into 8 × 8 quads whatever its colours, so a patch of one colour became 64 identical pieces. Neighbouring quads are now joined into square blocks wherever the colour changes by no more than about one 8-bit step across the block, so a flat patch is one piece and a patch that shades strongly keeps all 64; a block's outline runs through its quads' corners, and a patch that folds over itself is not joined. A synthetic page of 400 meshes (6 × 6 patches, half flat) exports 468,000 pieces instead of 921,600 (35 MB instead of 66 MB), and resvg draws the two files identically. Tests `mesh_export` (crate `vectorcraft-svg`), `tests::live::mesh_expand_to_flat_pieces`; scores unchanged | | 2026-10-31 | minor | PDF import (and a `.ai`'s PDF part): a transparency group's knockout and isolate flags (`/K`, `/I`; ISO 32000-1, 11.4.6.3) come from the interpreter as it pushes the group. They were read from the file in order and matched to the groups pushed, but a group that adds nothing (full opacity, Normal, no mask, neither flag) is drawn straight onto its parent without being pushed, so every group after one lost its own flags and took another's; and a page drawing form groups more than 10,000 times failed to import (the list of their flags was capped), which it no longer does. A blend's steps written as a knockout group of falling opacity drew as solid dark shapes: a user's `.ai` with 143 such bubbles now draws them as light rings, as poppler does (its bubble area 4.9% → 1.2% of pixels off from poppler's render); 16 other users' PDFs with transparency groups (44 pages) draw the same. Test `tests::import_fidelity::knockout_groups_after_a_group_drawn_straight_keep_their_flag`; scores unchanged | | 2026-10-30 | minor | `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout; blends are written with knockout on) in the state block after its record, as a group takes the one after its end; it was left for the next object, so a blend's steps of falling opacity drew over each other instead of knocking each other out, and every such blend came in too dark (a user's file has 143, its bubbles came in as dark rings). Both a live blend and drawn steps kept as a group take it. Test `import::ai::tests::a_blends_transparency_follows_its_record`; checked locally against that file: it comes 1.3% → 0.6% nearer its page, though a mesh seen through a mesh-shaped opacity mask still keeps it just over the limit. When a blend is the layer's last object and the layer's own state block (`7 () XW`, then `LB`) follows, the state is the layer's and the blend keeps its own, as for meshes (#4748); scores unchanged | From 75d2736a2a4c20e270c3c7b3934639196cbcb9da Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:59:28 +0300 Subject: [PATCH 066/260] fix(eps): area type's first line goes where the file lays it out Area type made from the editing data's text document was laid out with its first baseline the font's ascent below the frame's top. The text document keeps where each of its lines starts, and the file's page draws them there: for some fonts the first line sits well above the font's ascent (Oswald's at about its cap height), so headings came in lower than on the page and the layers were taken to differ from it. When the file's first line is more than half a point from where it is laid out here, the first baseline is now fixed where the file has it (First Baseline: Fixed), measured in the text document's own frame so a copied object's type moves with its frame. # Conflicts: # docs/file-format-parity.md --- crates/eps/src/import/ate.rs | 63 ++++++++++++++++++++++++++++ crates/eps/src/import/native/plan.rs | 3 ++ docs/file-format-parity.md | 3 +- 3 files changed, 68 insertions(+), 1 deletion(-) diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index a5b22f92d2..6ad647cad3 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -803,6 +803,35 @@ impl Story { !self.lines.is_empty() && vectorcraft_text::fit_first_line(vectorcraft_text::FontDb::global(), t) } + /// Area type (`node`, the story's first frame as [`Self::node`] makes it with `template` and + /// `to_doc`) whose first line the file lays out higher or lower than it is laid out here, as its + /// page draws it: its first baseline is fixed where the file has it. The font's ascent below the + /// frame's top, the first baseline here, isn't where the app that wrote the file puts it for + /// every font. Whether it was. + pub(super) fn place_first_line(&self, node: &mut Node, template: (f64, f64), to_doc: Affine) -> bool { + // Closer than this (points of the document) and the line is where the file has it. + const SAME: f64 = 0.5; + let NodeKind::Text(t) = &mut node.kind else { return false }; + if !matches!(t.kind, TextKind::Area { .. }) || t.area.vertical_align != vectorcraft_doc::VerticalAlign::Top { + return false; + } + let Some((_, (x, y))) = self.line_starts(template).into_iter().next() else { return false }; + let want = (to_doc * Point::new(x, y)).y; + let db = vectorcraft_text::FontDb::global(); + // A frame too short for the line lays nothing out: as the line needs it (see `fit_first_line`). + let mut probe = TextObject::clone(t); + vectorcraft_text::fit_first_line(db, &mut probe); + let laid = vectorcraft_text::layout(db, &probe); + let Some(first) = laid.lines.first().filter(|l| l.region == 0) else { return false }; + let min = first.first_baseline + (want - first.baseline); + if (want - first.baseline).abs() <= SAME || !min.is_finite() || min <= 0.0 { + return false; + } + t.area.first_baseline = vectorcraft_doc::FirstBaseline::Fixed; + t.area.first_baseline_min = min; + true + } + /// The leading the file's own line positions imply: the distance from one line to the next, less /// the space between paragraphs that is part of it (a paragraph's space after and the next one's /// space before; a layout's lines are where that space has put them, and the text object adds it @@ -1249,4 +1278,38 @@ mod tests { let mut t = area(13.0); assert!(!story("Heading\r", &[], &Para::default()).fit_first_line(&mut t) && height(&t).unwrap().3 == 13.0); } + + #[test] + fn area_type_s_first_line_goes_where_the_file_lays_it_out() { + // GUARDS: area type's first baseline was the font's ascent below the frame's top, where the + // file's own layout (and its page) can have it higher: a heading came in lower than the page's. + let line = |a: (f64, f64), b: (f64, f64)| [a.0, a.1, a.0, a.1, b.0, b.1, b.0, b.1]; + let frame = vec![ + line((10.0, 20.0), (210.0, 20.0)), + line((210.0, 20.0), (210.0, 120.0)), + line((210.0, 120.0), (10.0, 120.0)), + line((10.0, 120.0), (10.0, 20.0)), + ]; + // The canvas is the document here: the art's y up, the document's down. + let (template, to_doc) = ((CANVAS_CENTRE, -CANVAS_CENTRE), Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0])); + let first = |s: &Story| { + let mut node = s.node(NodeId(0), 0, template, to_doc).unwrap(); + let placed = s.place_first_line(&mut node, template, to_doc); + let NodeKind::Text(t) = node.kind else { panic!("area type") }; + let l = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + (placed, l.lines.first().map(|l| l.baseline), t.area.first_baseline) + }; + let mut s = story("Heading\r", &[], &Para::default()); + s.frames = vec![FrameKind::Area(frame)]; + // Where this lays the line out on its own: the file agrees, and nothing changes. + s.lines = vec![(10.0, 20.0)]; + let (_, Some(own), _) = first(&s) else { panic!("a line") }; + s.lines = vec![(10.0, own)]; + assert_eq!(first(&s), (false, Some(own), vectorcraft_doc::FirstBaseline::Ascent)); + // Higher in the file: there. + s.lines = vec![(10.0, own - 3.0)]; + let (placed, at, fb) = first(&s); + assert!(placed && fb == vectorcraft_doc::FirstBaseline::Fixed, "{fb:?}"); + assert!(at.is_some_and(|y| (y - (own - 3.0)).abs() < 1e-6), "{at:?} for {}", own - 3.0); + } } diff --git a/crates/eps/src/import/native/plan.rs b/crates/eps/src/import/native/plan.rs index cc2772f8ed..4bb3675cd1 100644 --- a/crates/eps/src/import/native/plan.rs +++ b/crates/eps/src/import/native/plan.rs @@ -70,6 +70,9 @@ pub(super) fn plan( let Some(Some(story)) = stories.get(k) else { continue }; let Some(mut node) = story.node(NodeId(0), info.frame, t, to_doc) else { continue }; let mut region = story.region(t, to_doc); + // The first line where the file has it, in the text document's frame (that of a + // copied object is its original's, as its lines are). + story.place_first_line(&mut node, t, to_doc); // Area type and type on a path in the object's own frame: the text document's frame // of a copied object keeps its original's path. frame_text_from_art(info, &mut node, &mut region); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index bab11248d5..44a180f1f2 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (type from an Illustrator file's text document takes the attributes of its character style) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (area type from an Illustrator file's text document starts its first line where the file lays it out) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -132,6 +132,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | `.ai`/EPS editing data: area type made from the file's text document put its first baseline the font's ascent below the frame's top, where the file's own layout (and its page) can have it higher: Oswald's and Urbanist's headings came in a third and an eighth of their size lower than on the page, and each text over them was taken to differ. When the text document's first line is more than half a point from where it is laid out here, the first baseline is fixed (Area Type Options › First Baseline › Fixed) where the file has it; the type's own font metrics aren't changed. Test `import::ate::tests::area_type_s_first_line_goes_where_the_file_lays_it_out`; checked locally against users' files: two election posters come 5.4% → 1.1% and 8.6% → 4.3% from their pages, so they open from their layers, and another 1.7% → 0.3%; scores unchanged | | 2026-10-31 | minor | `.ai`/EPS editing data: type made from the file's text document took each character attribute its run doesn't set from the document's base attributes, not from the character style the run names (`[Normal Character Style]` or another of the file's, and the styles each is based on). Where they differ the type came in wrong: a user's file whose base fill is white and whose Normal Character Style is black came in with its text white, so most of its type was missing wherever the page's own type didn't stand in for it. A run now takes its own attributes, then its character style's, then the document's ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html)). Test `import::tests_native::type_from_the_text_document_takes_its_character_styles_attributes`; checked locally against 377 users' files: none newly opens from its PDF part, and with #4791 that file opens from its layers (6.3% → 1.1% from its page); scores unchanged | | 2026-10-31 | minor | SVG export (and Object › Expand, EPS, DXF, EMF and the other outputs that cut a gradient mesh into flat pieces): each patch was cut into 8 × 8 quads whatever its colours, so a patch of one colour became 64 identical pieces. Neighbouring quads are now joined into square blocks wherever the colour changes by no more than about one 8-bit step across the block, so a flat patch is one piece and a patch that shades strongly keeps all 64; a block's outline runs through its quads' corners, and a patch that folds over itself is not joined. A synthetic page of 400 meshes (6 × 6 patches, half flat) exports 468,000 pieces instead of 921,600 (35 MB instead of 66 MB), and resvg draws the two files identically. Tests `mesh_export` (crate `vectorcraft-svg`), `tests::live::mesh_expand_to_flat_pieces`; scores unchanged | | 2026-10-31 | minor | PDF import (and a `.ai`'s PDF part): a transparency group's knockout and isolate flags (`/K`, `/I`; ISO 32000-1, 11.4.6.3) come from the interpreter as it pushes the group. They were read from the file in order and matched to the groups pushed, but a group that adds nothing (full opacity, Normal, no mask, neither flag) is drawn straight onto its parent without being pushed, so every group after one lost its own flags and took another's; and a page drawing form groups more than 10,000 times failed to import (the list of their flags was capped), which it no longer does. A blend's steps written as a knockout group of falling opacity drew as solid dark shapes: a user's `.ai` with 143 such bubbles now draws them as light rings, as poppler does (its bubble area 4.9% → 1.2% of pixels off from poppler's render); 16 other users' PDFs with transparency groups (44 pages) draw the same. Test `tests::import_fidelity::knockout_groups_after_a_group_drawn_straight_keep_their_flag`; scores unchanged | From 5b15b3f56b5c57388d0933cfeb3a13f7907b224c Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:59:18 +0300 Subject: [PATCH 067/260] fix(eps): a transparency set in a dictionary's art stays after it Art inside a dictionary in the editing data, such as an area text's frame (`/ConfiningPath`) or a mask's art, can set a transparency (`Xy`). The writer goes on from it: the objects after an area text whose frame sets one have no `Xy` of their own. The reader dropped that state when the dictionary closed, so those objects took the transparency before the dictionary instead; in a user's file a Lighten glow before an area text made everything after it fade into the light background. The last transparency the art inside a dictionary sets is now the current one after it (and the enclosing dictionary's). Dictionaries outside the layers (the setup's styles) are left as they were. # Conflicts: # docs/file-format-parity.md --- crates/eps/src/import/ai/read/containers.rs | 6 +++++- crates/eps/src/import/ai/read/ops.rs | 22 +++++++++++++++++++++ crates/eps/src/import/ai/read/types.rs | 2 ++ crates/eps/src/import/ai/tests.rs | 15 ++++++++++++++ docs/file-format-parity.md | 3 ++- 5 files changed, 46 insertions(+), 2 deletions(-) diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 8d70933984..e13f97d0cd 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -24,6 +24,7 @@ impl<'a> Reader<'a> { base, clips: Vec::new(), compound_members: false, + state: None, }); self.after_object = false; Ok(()) @@ -260,13 +261,16 @@ impl<'a> Reader<'a> { return Ok(()); } let Some(f) = self.frames.pop() else { return Ok(()) }; - let Frame { kind, children, base, hidden, gs, after, mesh_ended, .. } = f; + let Frame { kind, children, base, hidden, gs, after, mesh_ended, state, .. } = f; let Kind::Obj(mut o) = kind else { return Ok(()) }; obj::close(&mut o, &mut self.stack, base); self.obj_hidden = hidden; // Art made inside a dictionary (type's paths, a mask's art) isn't kept, and doesn't end what // follows the object the dictionary is about: a mesh's state comes after its mask. self.gs = gs; + if let Some(state) = state { + self.keep_state(state); + } self.after_object = after; self.mesh_ended = mesh_ended; if matches!(self.frames.last(), Some(Frame { kind: Kind::Obj(_), .. })) { diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 65cec1b072..9deba88891 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -446,6 +446,28 @@ impl<'a> Reader<'a> { // art moves on, so a path's state before its paint isn't read as its layer's. self.layer_state = in_layer.then_some((gs.opacity, gs.blend, gs.isolate, gs.knockout)); } + self.note_state(); + } + + /// Inside a dictionary in the art (a text's frame, a mask's art), the transparency just set + /// stays after the dictionary: the writer goes on from it, so the objects after an area text + /// whose frame sets one have no `Xy` of their own. + fn note_state(&mut self) { + let gs = &self.gs; + let state = (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape); + if self.frames.iter().any(|f| matches!(f.kind, Kind::Layer(_))) + && let Some(f) = self.frames.iter_mut().rev().find(|f| matches!(f.kind, Kind::Obj(_))) + { + f.state = Some(state); + } + } + + /// A dictionary's art set transparency `state` (see [`Self::note_state`]): it is the current + /// one now, and the enclosing dictionary's. + pub(super) fn keep_state(&mut self, state: (f32, BlendMode, bool, Knockout, bool)) { + let gs = &mut self.gs; + (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape) = state; + self.note_state(); } /// `n (style) XW` after an object: `1 (style)` after the object written on `%_` lines, its diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index 481a5670ac..6d948ae81f 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -153,6 +153,8 @@ pub(super) struct Frame { pub(super) clips: Vec<usize>, /// A compound member group explicitly declares its subpaths' winding with `D`. pub(super) compound_members: bool, + /// A dictionary in the art: the transparency (`Xy`) its art set last, which stays after it. + pub(super) state: Option<(f32, BlendMode, bool, Knockout, bool)>, } /// What a reader of a pattern's definition has of its head, `(name) llx lly urx ury`: the operands diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 649d51c385..b5c155d6c6 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -508,6 +508,21 @@ fn a_masked_gradient_mesh_takes_the_transparency_written_after_its_mask() { } } +#[test] +fn a_transparency_set_in_a_dictionary_s_art_stays_after_it() { + // GUARDS: an area text's frame (its `/ConfiningPath` art) sets its own transparency; the objects + // after the text, with no `Xy` of their own, draw with it. Read as the dictionary's alone, they + // drew with the Lighten of the path before the text and vanished on a light background. + let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n/Art :\nX=\n0 Ap\n0 1 0 0 0 Xy\n0 w\n100 0 m\n100 10 L\nn\nX+\n\ + ; /ConfiningPath ,\n2 /TextAntialiasing ,\n;\n"; + let body = format!("9 0.5 0 0 0 Xy\n{RED}{}f\n{text}{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0), rect_path(20.0, 0.0, 30.0, 10.0)); + let a = art(&read_ok(&layer(&body)).doc); + let paths: Vec<_> = a.iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).collect(); + assert_eq!(paths.len(), 2, "{a:#?}"); + assert_eq!((paths[0].opacity, paths[0].blend), (0.5, BlendMode::Lighten), "the state before the text"); + assert_eq!((paths[1].opacity, paths[1].blend), (1.0, BlendMode::Normal), "the state the text's art set"); +} + #[test] fn gradients() { let defs = "%AI5_BeginGradient: (G)\n(G) 1 2 Bd\n[\n<00FF>\n0\n0 0 0 0 1 0 0 2 1 6 %_BS\n\ diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 44a180f1f2..ad10039d64 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (area type from an Illustrator file's text document starts its first line where the file lays it out) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (a transparency an Illustrator file sets in a dictionary's art, as an area text's frame does, stays for the objects after it) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -132,6 +132,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | `.ai`/EPS editing data: a transparency (`Xy`) set by art inside a dictionary, as an area text's frame (its `/ConfiningPath`) or a mask's art sets one, stays the current one after the dictionary: the writer goes on from it, so the objects after such a text have no `Xy` of their own. It was dropped when the dictionary closed, and a user's file drew its logo, calligraphy, footer and type after an area text with the Lighten of the glow before it, so they faded into the light background. Test `import::ai::tests::a_transparency_set_in_a_dictionary_s_art_stays_after_it`; checked locally against that file: 8.1% → 1.7% from its page, so it opens from its layers (5% is the limit); scores unchanged | | 2026-10-31 | minor | `.ai`/EPS editing data: area type made from the file's text document put its first baseline the font's ascent below the frame's top, where the file's own layout (and its page) can have it higher: Oswald's and Urbanist's headings came in a third and an eighth of their size lower than on the page, and each text over them was taken to differ. When the text document's first line is more than half a point from where it is laid out here, the first baseline is fixed (Area Type Options › First Baseline › Fixed) where the file has it; the type's own font metrics aren't changed. Test `import::ate::tests::area_type_s_first_line_goes_where_the_file_lays_it_out`; checked locally against users' files: two election posters come 5.4% → 1.1% and 8.6% → 4.3% from their pages, so they open from their layers, and another 1.7% → 0.3%; scores unchanged | | 2026-10-31 | minor | `.ai`/EPS editing data: type made from the file's text document took each character attribute its run doesn't set from the document's base attributes, not from the character style the run names (`[Normal Character Style]` or another of the file's, and the styles each is based on). Where they differ the type came in wrong: a user's file whose base fill is white and whose Normal Character Style is black came in with its text white, so most of its type was missing wherever the page's own type didn't stand in for it. A run now takes its own attributes, then its character style's, then the document's ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html)). Test `import::tests_native::type_from_the_text_document_takes_its_character_styles_attributes`; checked locally against 377 users' files: none newly opens from its PDF part, and with #4791 that file opens from its layers (6.3% → 1.1% from its page); scores unchanged | | 2026-10-31 | minor | SVG export (and Object › Expand, EPS, DXF, EMF and the other outputs that cut a gradient mesh into flat pieces): each patch was cut into 8 × 8 quads whatever its colours, so a patch of one colour became 64 identical pieces. Neighbouring quads are now joined into square blocks wherever the colour changes by no more than about one 8-bit step across the block, so a flat patch is one piece and a patch that shades strongly keeps all 64; a block's outline runs through its quads' corners, and a patch that folds over itself is not joined. A synthetic page of 400 meshes (6 × 6 patches, half flat) exports 468,000 pieces instead of 921,600 (35 MB instead of 66 MB), and resvg draws the two files identically. Tests `mesh_export` (crate `vectorcraft-svg`), `tests::live::mesh_expand_to_flat_pieces`; scores unchanged | From 7403003fb1c4a24ed349f5e8a732b8afcd096558 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:59:09 +0300 Subject: [PATCH 068/260] fix(eps): an envelope's contents being edited aren't read as art An envelope whose contents are being edited is written the other way round from one that isn't: its contents, a group on `%_` lines, then its dictionary, which holds the mesh that shapes them. Only a group of meshes was left out before an envelope's dictionary, so those contents were read as art and their undistorted shapes drew over the distorted art that follows on plain lines (and that the page draws). The group on `%_` lines before an envelope's dictionary is now left out whatever it holds; text in it stays as hidden text, as the dictionary's own source text does. # Conflicts: # docs/file-format-parity.md --- crates/eps/src/import/ai/read/containers.rs | 29 ++++++++++++--------- crates/eps/src/import/ai/read/document.rs | 7 ++--- crates/eps/src/import/ai/tests.rs | 27 +++++++++++++++++++ docs/file-format-parity.md | 3 ++- 4 files changed, 49 insertions(+), 17 deletions(-) diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index e13f97d0cd..992a9c5643 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -338,23 +338,26 @@ impl<'a> Reader<'a> { } } - /// Drop the object just read when it is an envelope's own mesh: a group on `%_` lines holding - /// only gradient meshes. Whether it was dropped. - pub(super) fn drop_envelope_mesh(&mut self) -> bool { - fn only_meshes(n: &Node) -> bool { - match &n.kind { - NodeKind::Mesh(_) => true, - NodeKind::Group { children, .. } => !children.is_empty() && children.iter().all(|c| only_meshes(c)), - _ => false, - } - } + /// Drop the object just read when it is an envelope's own: a group on `%_` lines, before the + /// envelope's dictionary. It holds the mesh that shapes the envelope, or, while the envelope's + /// contents are being edited, those contents (the mesh then is in the dictionary); either way the + /// distorted art follows on plain lines. The source text in the contents stays, hidden, as the + /// dictionary's does. Whether it was dropped. + pub(super) fn drop_envelope_art(&mut self) -> bool { let Some(n) = self.last_object() else { return false }; let id = n.id; - if !matches!(n.kind, NodeKind::Group { .. }) || !only_meshes(n) || !self.hidden_ids.contains(&id) { + if !matches!(n.kind, NodeKind::Group { .. }) || !self.hidden_ids.contains(&id) { return false; } - if let Some(f) = self.frames.last_mut() { - f.children.pop(); + let mut slots = vec![]; + if let Some(f) = self.frames.last_mut() + && let Some(group) = f.children.pop() + { + envelope_text_slots(&group, &mut slots); + for mut slot in slots { + slot.visible = false; + f.children.push(slot); + } } self.hidden_ids.remove(&id); self.after_object = false; diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index c1e98d0a25..fb540f1d1f 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -229,9 +229,10 @@ impl<'a> Reader<'a> { self.blend_roles.insert(id, (kind, o.text("ShapeBlendPathID"))); } // An envelope (a distortion, `AIDeformStyle` / `DeformValue`) is written on `%_` lines as - // a group holding the mesh that shapes it; the distorted art the file's PDF part draws - // follows on plain lines. That mesh isn't art, so it goes (#2405). - if (o.get("AIDeformStyle").is_some() || o.get("DeformValue").is_some()) && self.drop_envelope_mesh() { + // a group holding the mesh that shapes it (or its contents, while they are being edited); + // the distorted art the file's PDF part draws follows on plain lines. That group isn't + // art, so it goes (#2405). + if (o.get("AIDeformStyle").is_some() || o.get("DeformValue").is_some()) && self.drop_envelope_art() { return; } if let Some(mask) = o.obj("AI9_Mask").or_else(|| o.obj("Mask")) { diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index b5c155d6c6..cfb6d2b347 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -1687,6 +1687,33 @@ fn an_envelope_mesh_is_not_read_as_art() { assert!(art(&doc).iter().any(|n| has_mesh(n)), "{:#?}", art(&doc)); } +/// An envelope whose contents are being edited is written the other way round: its contents, a +/// group on `%_` lines, then its dictionary, which holds the mesh that shapes them. The contents +/// aren't drawn as they are, only the distorted art on the plain lines after them. +#[test] +fn an_envelope_s_contents_being_edited_are_not_read_as_art() { + let corner = |x: i32, y: i32, next: (i32, i32), prev: (i32, i32)| { + format!("%_[0.82 0.83 0.83 1 {x} {y} {} {} 1 {} {} 1] /N X#\n", next.0, next.1, prev.0, prev.1) + }; + let mesh = format!( + "%_/Mesh X!\n%_(DeviceRGB) /CS X#\n%_[0 0] /P X#\n{}{}{}{}%_0 /E X#\n%_/End X!\n%_0 0 Xd\n%_6 () XW\n", + corner(0, 0, (0, 10), (10, 0)), + corner(0, 40, (10, 40), (0, 30)), + corner(40, 40, (40, 30), (30, 40)), + corner(40, 0, (30, 0), (40, 10)), + ); + let contents: String = rect_path(0.0, 0.0, 80.0, 20.0).lines().map(|l| format!("%_{l}\n")).collect(); + let body = format!( + "%_u\n%_u\n%_0 0 1 0 0 0 1 Xa\n{contents}%_f\n%_U\n%_9 () XW\n%_U\n%_/ArtDictionary :\n%_1 /Bool (AIDeformEditModeKey) ,\n\ + %_3 /Int (AIDeformStyle) ,\n%_X=\n{mesh}%_X+\n%_ (AIDeformArtKey) ,\n%_;\n%_\n%_9 () XW\n{RED}{}f\n", + rect_path(0.0, 0.0, 40.0, 40.0) + ); + let doc = read_ok(&layer(&body)).doc; + let a = art(&doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert_eq!(fill(&a[0]).color(), Some(Color::rgb(1.0, 0.0, 0.0))); +} + #[test] fn a_gradient_mesh_reads_as_a_patch() { let corner = |rgb: &str, x: i32, y: i32, next: (i32, i32), prev: (i32, i32)| { diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index ad10039d64..118fddd9e8 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (a transparency an Illustrator file sets in a dictionary's art, as an area text's frame does, stays for the objects after it) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (an Illustrator envelope whose contents are being edited no longer draws its undistorted contents over its result) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -132,6 +132,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | `.ai`/EPS editing data: an envelope whose contents are being edited is written the other way round from one that isn't: its contents, a group on `%_` lines, then its dictionary, which holds the mesh that shapes them. Those contents were read as art, so the undistorted art drew over the distorted art the page draws. The group on `%_` lines before an envelope's dictionary is now left out whatever it holds (text in it stays as hidden text, as the dictionary's own does), as the envelope's mesh already was (#2405). Test `import::ai::tests::an_envelope_s_contents_being_edited_are_not_read_as_art`; checked locally against a user's file: it opens from its layers, 0.0% from its page (it was 9.7%, over the 5% limit); scores unchanged | | 2026-10-31 | minor | `.ai`/EPS editing data: a transparency (`Xy`) set by art inside a dictionary, as an area text's frame (its `/ConfiningPath`) or a mask's art sets one, stays the current one after the dictionary: the writer goes on from it, so the objects after such a text have no `Xy` of their own. It was dropped when the dictionary closed, and a user's file drew its logo, calligraphy, footer and type after an area text with the Lighten of the glow before it, so they faded into the light background. Test `import::ai::tests::a_transparency_set_in_a_dictionary_s_art_stays_after_it`; checked locally against that file: 8.1% → 1.7% from its page, so it opens from its layers (5% is the limit); scores unchanged | | 2026-10-31 | minor | `.ai`/EPS editing data: area type made from the file's text document put its first baseline the font's ascent below the frame's top, where the file's own layout (and its page) can have it higher: Oswald's and Urbanist's headings came in a third and an eighth of their size lower than on the page, and each text over them was taken to differ. When the text document's first line is more than half a point from where it is laid out here, the first baseline is fixed (Area Type Options › First Baseline › Fixed) where the file has it; the type's own font metrics aren't changed. Test `import::ate::tests::area_type_s_first_line_goes_where_the_file_lays_it_out`; checked locally against users' files: two election posters come 5.4% → 1.1% and 8.6% → 4.3% from their pages, so they open from their layers, and another 1.7% → 0.3%; scores unchanged | | 2026-10-31 | minor | `.ai`/EPS editing data: type made from the file's text document took each character attribute its run doesn't set from the document's base attributes, not from the character style the run names (`[Normal Character Style]` or another of the file's, and the styles each is based on). Where they differ the type came in wrong: a user's file whose base fill is white and whose Normal Character Style is black came in with its text white, so most of its type was missing wherever the page's own type didn't stand in for it. A run now takes its own attributes, then its character style's, then the document's ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html)). Test `import::tests_native::type_from_the_text_document_takes_its_character_styles_attributes`; checked locally against 377 users' files: none newly opens from its PDF part, and with #4791 that file opens from its layers (6.3% → 1.1% from its page); scores unchanged | From 4861fb9d8575a65ffe072bcba85d48588a764a53 Mon Sep 17 00:00:00 2001 From: marshiyar <57055687+marshiyar@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:12:50 -0700 Subject: [PATCH 069/260] Engine guard: a recovered panic restores every document's undo history and the active document (#3599) run_guarded put back only the active document's art, selection and interaction. An undo step pushed before the panic stayed (Undo then stepped to a state equal to the current one) and Redo was lost; other documents a command touched kept their half-applied edits; the active document was restored by index. It now snapshots every open document with its history and restores them, and the active document by uid. Fixes #3599 --- crates/engine/src/session/execute.rs | 21 ++++++++------- crates/engine/src/tests.rs | 40 ++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 24cd7096fc..d3ffe41631 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -199,27 +199,30 @@ impl Session { r } - /// A top-level command: a panic (a bug) becomes [`EngineError::Internal`] and the active - /// document goes back to how it was before the command, instead of crashing the frontend. + /// A top-level command: a panic (a bug) becomes [`EngineError::Internal`] and every open + /// document goes back to how it was before the command (its art, selection, interaction and + /// undo history), and the same document stays active, instead of crashing the frontend. pub(crate) fn run_guarded(&mut self, id: &str, f: impl FnOnce(&mut Self) -> Result<Value>) -> Result<Value> { - let snapshot = self.active().map(|d| (d.uid, d.doc.clone(), d.selection.clone(), d.interaction.clone())); - let active = self.active; + let snapshot: Vec<_> = + self.docs.iter().map(|d| (d.uid, d.doc.clone(), d.selection.clone(), d.interaction.clone(), d.history.clone())).collect(); + let active = self.active().map(|d| d.uid); let r = match guard::catch_panic(|| self.run_nested(f)) { Ok(r) => r, Err(msg) => { self.depth = 0; self.journal_note.clear(); - if let Some((uid, doc, selection, interaction)) = snapshot - && let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) - { + for (uid, doc, selection, interaction, history) in snapshot { + // A document the command closed stays closed. + let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) else { continue }; st.doc = doc; st.selection = selection; st.interaction = interaction; + st.history = history; cmd::globaledit::follow_history(st); st.revision += 1; } - if active.is_some_and(|i| i < self.docs.len()) { - self.active = active; + if let Some(i) = active.and_then(|uid| self.docs.iter().position(|d| d.uid == uid)) { + self.active = Some(i); } Err(EngineError::Internal { cmd: id.to_string(), msg }) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c0eb9e253f..c6a2a06bea 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3521,6 +3521,46 @@ fn a_panicking_command_rolls_back_instead_of_crashing() { assert_eq!(s.journal.last().map(|j| j.0.as_str()), Some("shape.rectangle")); } +/// A command that recorded an undo step and then panicked leaves Undo and Redo as they were. +#[test] +fn a_panic_after_an_edit_leaves_undo_and_redo_as_they_were() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + rect(&mut s, 200.0, 10.0, 50.0, 50.0); + s.execute("edit.undo", &json!({})).unwrap(); + let (undo, redo) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().history.redo.len()); + assert_eq!((undo, redo), (1, 1)); + let r = s.run_guarded("test.panic", |s| { + s.execute("edit.clear", &json!({"ids": [a.0]}))?; + s.run_nested(|_| panic!("boom")) + }); + assert!(matches!(r, Err(EngineError::Internal { .. }))); + let st = s.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.history.redo.len()), (undo, redo)); + assert!(st.doc.node(a).is_some()); +} + +/// A panic rolls back every document the command touched, and the active one stays the same. +#[test] +fn a_panic_rolls_back_other_documents_and_keeps_the_active_one() { + let mut s = session(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let second = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + let first_uid = s.doc().unwrap().uid; + let second_before = s.docs[1].doc.clone(); + let steps = s.docs[1].history.undo.len(); + let r = s.run_guarded("test.panic", |s| { + s.docs[1].history.undo.clear(); + Arc::make_mut(&mut s.docs[1].doc).remove(second)?; + s.run_nested(|_| panic!("boom")) + }); + assert!(matches!(r, Err(EngineError::Internal { .. }))); + assert!(Arc::ptr_eq(&s.docs[1].doc, &second_before)); + assert_eq!(s.docs[1].history.undo.len(), steps); + assert_eq!(s.doc().unwrap().uid, first_uid); +} + /// New layers and sublayers share one "Layer N" numbering, whatever art the document holds, and /// never repeat a name. #[test] From 22b1c6bc2e03620f57dc7544d40e2b76ef188dfc Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sat, 31 Oct 2026 05:35:20 +0300 Subject: [PATCH 070/260] Fix #3085: DXF LAYOUT objects write only the group codes the DXF Reference defines The PLOTSETTINGS part of each LAYOUT wrote the paper image origin as a point (148 and 158), but the origin is two values at 148 (x) and 149 (y), and 158 is not a PLOTSETTINGS code. Strict readers such as Autodesk Fusion can reject the file. The ezdxf re-save the reporter found Fusion accepts differs from our export in these objects, not in the geometry. - 148/149 for the paper image origin - shade plot mode, resolution level and DPI (76/77/78) from DXF 2004 - plot flag 1024 (model type) on the Model layout - the plot style ACDBPLACEHOLDER without a subclass marker Test r2000_and_later_files_have_the_structure_cad_apps_require checks the required sections and table entries, handles below $HANDSEED, references that resolve, and LAYOUT group codes. # Conflicts: # docs/file-format-parity.md --- crates/cad/src/tests.rs | 65 ++++++++++++++++++++++++++++++++++++++ crates/cad/src/writer.rs | 18 +++++++++-- docs/file-format-parity.md | 5 +-- 3 files changed, 83 insertions(+), 5 deletions(-) diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index f02047492a..c08417b8de 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -125,6 +125,71 @@ fn every_version_declares_its_acadver_and_is_well_formed() { assert_eq!(DxfVersion::from_id("2019"), None); } +/// The structure strict readers (Autodesk Fusion, #3085) need: the required sections and table +/// entries, handles that every reference resolves to, and LAYOUT objects with only the group codes +/// the DXF Reference defines for PLOTSETTINGS and LAYOUT (AutoCAD DXF Reference, OBJECTS section: +/// https://help.autodesk.com/view/OARX/2018/ENU/?guid=GUID-1113675E-AB07-4567-BD47-B7FBE7290D1C). +#[test] +fn r2000_and_later_files_have_the_structure_cad_apps_require() { + use std::collections::HashSet; + // Common object codes, then AcDbPlotSettings, then AcDbLayout (76 is the shade plot mode in + // the first and the UCS type in the second). + let layout_codes: HashSet<i32> = [0, 5, 102, 330, 360, 100] + .into_iter() + .chain([1, 2, 4, 6, 7, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 140, 141, 142, 143, 70, 72, 73, 74, 75, 76, 77, 78, 147, 148, 149, 333]) + .chain([71, 10, 20, 11, 21, 12, 22, 32, 14, 24, 34, 15, 25, 35, 146, 13, 23, 33, 16, 26, 36, 17, 27, 37, 331, 345, 346]) + .collect(); + let d = shapes_doc(); + for v in DxfVersion::ALL.into_iter().filter(|v| *v >= DxfVersion::R2000) { + let out = export(&d, &DxfOptions { version: v, ..opts(&d) }).unwrap(); + let p = pairs(&out.bytes); + for name in ["HEADER", "CLASSES", "TABLES", "BLOCKS", "ENTITIES", "OBJECTS"] { + assert!(p.windows(2).any(|w| w[0] == (0, "SECTION".into()) && w[1] == (2, name.into())), "{v:?}: {name} section"); + } + let tables = section(&p, "TABLES"); + let names = |k: &str| -> Vec<String> { tables.iter().filter(|o| kind(o) == k).filter_map(|o| get(o, 2).map(str::to_string)).collect() }; + for (k, want) in [ + ("LTYPE", "ByBlock"), + ("LTYPE", "ByLayer"), + ("LTYPE", "Continuous"), + ("LAYER", "0"), + ("STYLE", "Standard"), + ("APPID", "ACAD"), + ("DIMSTYLE", "Standard"), + ("BLOCK_RECORD", "*Model_Space"), + ("BLOCK_RECORD", "*Paper_Space"), + ] { + assert!(names(k).iter().any(|n| n == want), "{v:?}: {k} {want}"); + } + // Every object after the header has a handle below $HANDSEED, and every reference to + // another object (owner 330, soft/hard pointers 340/350/390) names one of them. + let body = &p[p.iter().position(|x| *x == (0, "ENDSEC".into())).unwrap()..]; + let handles: HashSet<u32> = body.iter().filter(|x| x.0 == 5 || x.0 == 105).map(|x| u32::from_str_radix(&x.1, 16).unwrap()).collect(); + let seed = u32::from_str_radix(&header(&p, "$HANDSEED").unwrap(), 16).unwrap(); + assert!(handles.iter().all(|h| *h < seed), "{v:?}: handles below the seed"); + for (code, value) in body.iter().filter(|x| matches!(x.0, 330 | 340 | 350 | 390)) { + let h = u32::from_str_radix(value, 16).unwrap(); + assert!(h == 0 || handles.contains(&h), "{v:?}: group {code} points at missing handle {value}"); + } + let objects = section(&p, "OBJECTS"); + let layouts: Vec<&Pairs> = objects.iter().filter(|o| kind(o) == "LAYOUT").collect(); + assert_eq!(layouts.len(), 2, "{v:?}: Model and Layout1"); + for l in &layouts { + let bad: Vec<i32> = l.iter().map(|x| x.0).filter(|c| !layout_codes.contains(c)).collect(); + assert!(bad.is_empty(), "{v:?}: LAYOUT has group codes the DXF Reference doesn't define: {bad:?}"); + // The paper image origin is 148 (x) and 149 (y). + assert!(get(l, 148).is_some() && get(l, 149).is_some(), "{v:?}: paper image origin"); + // Flag 1024 marks the model space layout, and only it. + let name = l.iter().skip_while(|x| x.1 != "AcDbLayout").find(|x| x.0 == 1).map(|x| x.1.as_str()); + let flags: i64 = get(l, 70).unwrap().parse().unwrap(); + assert_eq!(flags & 1024 != 0, name == Some("Model"), "{v:?}: model type flag of {name:?}"); + } + // The plot style placeholder carries only the common object codes. + let holder = objects.iter().find(|o| kind(o) == "ACDBPLACEHOLDER").expect("placeholder"); + assert!(holder.iter().all(|x| matches!(x.0, 0 | 5 | 102 | 330)), "{v:?}: placeholder {holder:?}"); + } +} + #[test] fn r12_viewport_has_no_duplicate_group_codes() { let d = shapes_doc(); diff --git a/crates/cad/src/writer.rs b/crates/cad/src/writer.rs index 665f8576f1..6ba7e5a35d 100644 --- a/crates/cad/src/writer.rs +++ b/crates/cad/src/writer.rs @@ -564,7 +564,10 @@ impl Drawing { c.handle(350, fixed::PLOT_NORMAL); c.raw(100, "AcDbDictionaryWithDefault"); c.handle(340, fixed::PLOT_NORMAL); - c.object("ACDBPLACEHOLDER", fixed::PLOT_NORMAL, fixed::PLOT_STYLES, "AcDbPlaceHolder"); + // A placeholder has no data and no subclass marker of its own. + c.raw(0, "ACDBPLACEHOLDER"); + c.handle(5, fixed::PLOT_NORMAL); + c.handle(330, fixed::PLOT_STYLES); self.layout(c, fixed::MODEL_LAYOUT, "Model", 0, fixed::MODEL_RECORD); self.layout(c, fixed::PAPER_LAYOUT, "Layout1", 1, fixed::PAPER_RECORD); } @@ -618,14 +621,23 @@ impl Drawing { c.num(141, 0.0); c.num(142, 1.0); c.num(143, 1.0); - c.int(70, 688); + // Plot flags; 1024 marks the model space layout. + c.int(70, if record == fixed::MODEL_RECORD { 688 | 1024 } else { 688 }); c.int(72, 1); c.int(73, 0); c.int(74, 5); c.raw(7, ""); c.int(75, 16); + if self.version.true_color() { + // Shade plot mode (as displayed), resolution level (normal) and custom DPI. + c.int(76, 0); + c.int(77, 2); + c.int(78, 300); + } c.num(147, 1.0); - c.xy(148, 0.0, 0.0); + // The paper image origin is 148 (x) and 149 (y), not a point at 148 and 158. + c.num(148, 0.0); + c.num(149, 0.0); c.raw(100, "AcDbLayout"); c.raw(1, name); c.int(70, 1); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 118fddd9e8..fac518fdde 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (an Illustrator envelope whose contents are being edited no longer draws its undistorted contents over its result) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (DXF export: LAYOUT objects write only DXF Reference group codes, for strict readers such as Autodesk Fusion, #3085) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -98,7 +98,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CID-keyed CJK type not read; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as `<title>`, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`) | -| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). CNC preset and VCarve QA remain open | +| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). CNC preset and VCarve QA remain open | | DWG | open, export | no | no | no open spec; DXF instead | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) | | PSD | open, place, export | yes (merged image, every mode and depth) | yes (layered, max editability) | placing as layers (Photoshop Import Options) missing; the embedded ICC profile's tags are 4-byte aligned (#1584) | @@ -132,6 +132,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | DXF export (2000–2018): the LAYOUT objects wrote the paper image origin as a point at group codes 148 and 158, but PLOTSETTINGS defines 148 and 149 and no 158, so strict readers could reject the file (Autodesk Fusion reported "DXF File failed to insert", #3085). They now write 148/149, the shade plot mode, resolution and DPI (76–78, 2004 and later) and flag 1024 on the Model layout; the plot style ACDBPLACEHOLDER no longer carries a subclass marker. Test `r2000_and_later_files_have_the_structure_cad_apps_require` (required sections and table entries, handles and references, LAYOUT group codes); exports pass ezdxf's recover and audit; not tested in Fusion itself; scores unchanged | | 2026-10-31 | minor | `.ai`/EPS editing data: an envelope whose contents are being edited is written the other way round from one that isn't: its contents, a group on `%_` lines, then its dictionary, which holds the mesh that shapes them. Those contents were read as art, so the undistorted art drew over the distorted art the page draws. The group on `%_` lines before an envelope's dictionary is now left out whatever it holds (text in it stays as hidden text, as the dictionary's own does), as the envelope's mesh already was (#2405). Test `import::ai::tests::an_envelope_s_contents_being_edited_are_not_read_as_art`; checked locally against a user's file: it opens from its layers, 0.0% from its page (it was 9.7%, over the 5% limit); scores unchanged | | 2026-10-31 | minor | `.ai`/EPS editing data: a transparency (`Xy`) set by art inside a dictionary, as an area text's frame (its `/ConfiningPath`) or a mask's art sets one, stays the current one after the dictionary: the writer goes on from it, so the objects after such a text have no `Xy` of their own. It was dropped when the dictionary closed, and a user's file drew its logo, calligraphy, footer and type after an area text with the Lighten of the glow before it, so they faded into the light background. Test `import::ai::tests::a_transparency_set_in_a_dictionary_s_art_stays_after_it`; checked locally against that file: 8.1% → 1.7% from its page, so it opens from its layers (5% is the limit); scores unchanged | | 2026-10-31 | minor | `.ai`/EPS editing data: area type made from the file's text document put its first baseline the font's ascent below the frame's top, where the file's own layout (and its page) can have it higher: Oswald's and Urbanist's headings came in a third and an eighth of their size lower than on the page, and each text over them was taken to differ. When the text document's first line is more than half a point from where it is laid out here, the first baseline is fixed (Area Type Options › First Baseline › Fixed) where the file has it; the type's own font metrics aren't changed. Test `import::ate::tests::area_type_s_first_line_goes_where_the_file_lays_it_out`; checked locally against users' files: two election posters come 5.4% → 1.1% and 8.6% → 4.3% from their pages, so they open from their layers, and another 1.7% → 0.3%; scores unchanged | From 7ae9f2c4e56d4928b2cba1bfbf26bc0d4f8980f7 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:52:03 +0100 Subject: [PATCH 071/260] Keep an empty text value in dataset CSV export and import Found while testing crates/engine/src/cmd/variablecmds/csv.rs:146 (csv_escape) and :158-163 (cell_to_value) Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- crates/engine/src/cmd/variablecmds/csv.rs | 30 ++++++++++++++--------- crates/engine/src/tests/variables.rs | 29 ++++++++++++++++++++++ 2 files changed, 48 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index 95d80ce28e..bf60c95085 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -29,8 +29,8 @@ fn datasets_csv_bytes(p: &Value, cmd: &str) -> Result<Vec<u8>> { Ok(bytes) } -/// A row of a datasets CSV: the file line it starts on, and its cells. -type CsvRow = (usize, Vec<String>); +/// A row of a datasets CSV: the file line it starts on, its cells, and for each cell whether it was quoted. +type CsvRow = (usize, Vec<String>, Vec<bool>); /// Whether a datasets CSV separates its cells with tabs: its header row (the first line that /// isn't blank), read with tabs between cells, has a tab outside quotes and no comma outside @@ -80,7 +80,7 @@ fn tab_separated(text: &str) -> bool { fn parse_datasets_csv(text: &str, cmd: &str) -> Result<Vec<CsvRow>> { let text = text.strip_prefix('\u{feff}').unwrap_or(text); let sep = if tab_separated(text) { '\t' } else { ',' }; - let (mut rows, mut row, mut cur) = (Vec::new(), Vec::<String>::new(), String::new()); + let (mut rows, mut row, mut quoted, mut cur) = (Vec::new(), Vec::<String>::new(), Vec::<bool>::new(), String::new()); // `closed`: where the closing quote of a quoted cell falls in `cur`. `start`: the line the // current row starts on. let (mut in_quotes, mut closed, mut line, mut start) = (false, None, 1usize, 1usize); @@ -98,18 +98,23 @@ fn parse_datasets_csv(text: &str, cmd: &str) -> Result<Vec<CsvRow>> { } } Some('"') if cur.is_empty() => in_quotes = true, - Some(ch) if ch == sep && !in_quotes => row.push(end_csv_cell(&mut cur, &mut closed)), + Some(ch) if ch == sep && !in_quotes => { + quoted.push(closed.is_some()); + row.push(end_csv_cell(&mut cur, &mut closed)); + } Some('\r') if !in_quotes => {} Some('\n') | None if !in_quotes => { + quoted.push(closed.is_some()); row.push(end_csv_cell(&mut cur, &mut closed)); if row.iter().any(|c| !c.trim().is_empty()) { - rows.push((start, std::mem::take(&mut row))); + rows.push((start, std::mem::take(&mut row), std::mem::take(&mut quoted))); // +1 for the header. if rows.len() > MAX_CSV_ROWS + 1 { return Err(bad(cmd, format!("more than {MAX_CSV_ROWS} data rows"))); } } row.clear(); + quoted.clear(); if c.is_none() { return Ok(rows); } @@ -143,7 +148,8 @@ fn end_csv_cell(cur: &mut String, closed: &mut Option<usize>) -> String { } fn csv_escape(s: &str) -> String { - if s.contains([',', '"', '\n', '\r']) || s != s.trim() { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() } + // An empty string is quoted so that it reads back as an empty value, not as a missing one. + if s.is_empty() || s.contains([',', '"', '\n', '\r']) || s != s.trim() { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() } } /// A visibility cell: true/false, 1/0, yes/no (ASCII, case-insensitive). @@ -155,12 +161,13 @@ fn parse_visible_cell(s: &str, var: &str, cmd: &str) -> Result<bool> { } } -fn cell_to_value(kind: VariableKind, cell: &str, var: &str, cmd: &str) -> Result<Option<DataValue>> { +/// The value of a cell. A quoted empty text cell is an empty text value; any other empty cell is no value. +fn cell_to_value(kind: VariableKind, cell: &str, quoted: bool, var: &str, cmd: &str) -> Result<Option<DataValue>> { // A text cell is not trimmed here (the parser trims unquoted cells); image, graph and // visibility cells are trimmed. let t = if kind == VariableKind::Text { cell } else { cell.trim() }; if t.is_empty() { - return Ok(None); + return Ok((quoted && kind == VariableKind::Text).then(|| DataValue::Text(String::new()))); } Ok(Some(match kind { VariableKind::Text => DataValue::Text(t.to_string()), @@ -250,7 +257,7 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> { let bytes = datasets_csv_bytes(p, C)?; let text = std::str::from_utf8(&bytes).map_err(|_| bad(C, "CSV is not UTF-8"))?; let rows = parse_datasets_csv(text, C)?; - let Some((_, header)) = rows.first() else { + let Some((_, header, _)) = rows.first() else { return Err(bad(C, "CSV is empty")); }; let name_column = header.first().is_some_and(|h| h.trim().eq_ignore_ascii_case("name")); @@ -280,7 +287,7 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> { let mut parsed: Vec<DataSet> = Vec::new(); // The names of the rows read so far, and the last number given to a row without a name. let (mut seen, mut number) = (BTreeSet::new(), 0usize); - for &(line, ref row) in rows.iter().skip(1) { + for &(line, ref row, ref quoted) in rows.iter().skip(1) { let raw_name = if name_column { row.first().map_or("", |c| c.trim()) } else { "" }; let name = if raw_name.is_empty() { // Same numbering as Capture Data Set when a row leaves the name blank or the file has @@ -302,7 +309,8 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> { let mut values = BTreeMap::new(); for &(col, ref var, kind) in &columns { let cell = row.get(col).map(String::as_str).unwrap_or(""); - match cell_to_value(kind, cell, var, C) { + let was_quoted = quoted.get(col).copied().unwrap_or(false); + match cell_to_value(kind, cell, was_quoted, var, C) { Ok(Some(v)) => { values.insert(var.clone(), v); } diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 281d575156..bdacd0e1bf 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -1103,6 +1103,35 @@ fn datasets_csv_keeps_line_breaks_in_quoted_cells() { assert!(s.execute("dataset.import", &json!({"csv": "name,Name\nX,\"open"})).is_err(), "unclosed quote"); } +/// An empty text value is not a missing value: it comes back from the exported CSV as an empty +/// text, so selecting the data set still clears the bound text. +#[test] +fn datasets_csv_keeps_an_empty_text_value() { + let mut s = session(); + let t = text(&mut s, "One"); + s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap(); + s.execute("dataset.new", &json!({"name": "A", "values": {"Name": ""}})).unwrap(); + let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); + s.execute("dataset.delete", &json!({"names": ["A"]})).unwrap(); + s.execute("dataset.import", &json!({"csv": csv})).unwrap(); + let value = s.doc().unwrap().doc.variables.dataset("A").and_then(|d| d.values.get("Name")).cloned(); + assert_eq!(value, Some(vectorcraft_doc::DataValue::Text(String::new()))); + s.execute("dataset.import", &json!({"csv": "name,Name\nB,\nC,\"\"\n"})).unwrap(); + let value = |name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("Name")).cloned(); + assert_eq!(value("C"), Some(vectorcraft_doc::DataValue::Text(String::new()))); + // Compatibility rule for files written before empty text was quoted: a bare empty cell stays "no value". + assert_eq!(value("B"), None); + // A data set with no value for the variable exports a bare cell and stays without a value. + s.execute("dataset.new", &json!({"name": "D", "values": {}})).unwrap(); + let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); + assert!(csv.contains("\nD,\n"), "{csv:?}"); + s.execute("dataset.delete", &json!({"names": ["D"]})).unwrap(); + s.execute("dataset.import", &json!({"csv": csv})).unwrap(); + let value = |name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("Name")).cloned(); + assert_eq!(value("D"), None); +} + /// A quoted text cell keeps its leading and trailing spaces, so a padded value comes back from /// the exported CSV as it went out; an unquoted cell, and spaces after a closing quote, are trimmed. #[test] From 1679318034a243c258763465a7a011520bb493b1 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:39:40 +0300 Subject: [PATCH 072/260] Type: lam-alef highlight follow-up: optional features, all marks, exact ligature test (#394) Highlight Alternate Glyphs no longer drops a lam-alef cluster's glyphs outright: the ligature is clear when required shaping, or shaping with liga left on (older fonts), gives it, so an optional feature such as salt that changes it is highlighted again. is_lam_alef takes any combining mark by Unicode general category (Arabic Extended-A/B/C included) instead of a partial list. The test font maps the fatha to a mark and skips marks in its ligature, so the mark-spanning test checks the exact ligature glyph and cluster; it gains a salt lookup and test. Also a one-line equivalent nonminimal_bool repair in pathops' pathtools that strict Clippy needs on main. --- Cargo.lock | 1 + crates/render/Cargo.toml | 2 + crates/render/src/tests/alternate.rs | 75 ++++++++++++++++++++++++---- crates/render/src/text_geom.rs | 47 +++++++++++------ crates/text/src/test_fonts.rs | 36 +++++++++---- docs/type-parity.md | 5 +- 6 files changed, 129 insertions(+), 37 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ff1d18be21..a1512c6d0d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6383,6 +6383,7 @@ dependencies = [ "psd", "serde_json", "tiff", + "unicode-general-category", "vectorcraft-brush", "vectorcraft-color", "vectorcraft-doc", diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 6d92638452..4bd499b9d4 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -27,6 +27,8 @@ weezl = "0.2" # PNG rows read one at a time (MIT OR Apache-2.0; already used by the image crate's PNG reader). png = "0.18" log = { workspace = true } +# Combining marks inside a lam-alef cluster (MIT OR Apache-2.0; already used by vectorcraft-text). +unicode-general-category = "1" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] vello_cpu = { workspace = true, features = ["multithreading"] } diff --git a/crates/render/src/tests/alternate.rs b/crates/render/src/tests/alternate.rs index 8ef6903301..201efc3299 100644 --- a/crates/render/src/tests/alternate.rs +++ b/crates/render/src/tests/alternate.rs @@ -136,17 +136,49 @@ fn lam_alef_is_not_an_alternate() { /// feature. Built in code, so it runs whatever fonts the machine has. #[test] fn lam_alef_in_liga_is_not_an_alternate() { - use vectorcraft_text::test_fonts::{lam_alef_family, lam_alef_font}; + use vectorcraft_text::test_fonts::{lam_alef_family, lam_alef_font, source_sans_gid}; let _adding = crate::tests_fontchange::adding_fonts(); let db = vectorcraft_text::FontDb::global(); + let gid = |c| u32::from(source_sans_gid(c).unwrap()); + // Text, the ligature glyph and its cluster (byte, length): lam + alef, lam + alef with hamza + // above, the pair after a beh, and the pair with a fatha on the lam (the ligature skips it). + let cases = [ + ("\u{0644}\u{0627}", 'H', (0, 4)), + ("\u{0644}\u{0623}", 'K', (0, 4)), + ("\u{0628}\u{0644}\u{0627}", 'H', (2, 4)), + ("\u{0644}\u{064E}\u{0627}", 'H', (0, 6)), + ]; for feature in [b"liga", b"rlig"] { db.add_font(lam_alef_font(feature).unwrap()); - let style = vectorcraft_doc::text::CharStyle { size: 36.0, font_family: lam_alef_family(feature).into(), ..Default::default() }; - for s in ["\u{0644}\u{0627}", "\u{0644}\u{0623}", "\u{0628}\u{0644}\u{0627}", "\u{0644}\u{064E}\u{0627}"] { + let family = lam_alef_family(feature); + let style = vectorcraft_doc::text::CharStyle { size: 36.0, font_family: family.into(), ..Default::default() }; + for (s, ligature, (byte, len)) in cases { let t = text(s, style.clone()); - // The font's ligature glyph stands for the pair. - assert!(glyphs(&t).iter().any(|g| g.1 > 2), "{}: {s} is shaped to one ligature glyph", lam_alef_family(feature)); - assert_eq!(alternates(&t), 0, "{}: {s}", lam_alef_family(feature)); + // The font's ligature glyph stands for the pair, its cluster lam to alef. + let shaped = glyphs(&t); + assert!(shaped.contains(&(byte, len, gid(ligature))), "{family}: {s} is shaped to {ligature} over {byte}..{}: {shaped:?}", byte + len); + assert_eq!(alternates(&t), 0, "{family}: {s}"); + } + } +} + +/// #394: an optional feature that changes the lam-alef ligature (here `salt`) is highlighted: +/// only the required ligature itself is left clear, whichever feature the font files it under. +#[test] +fn an_optional_feature_on_the_lam_alef_ligature_is_an_alternate() { + use vectorcraft_text::test_fonts::{LAM_ALEF_SALT, lam_alef_family, lam_alef_font, source_sans_gid}; + let _adding = crate::tests_fontchange::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + let salted = u32::from(source_sans_gid(LAM_ALEF_SALT).unwrap()); + for feature in [b"liga", b"rlig"] { + db.add_font(lam_alef_font(feature).unwrap()); + let family = lam_alef_family(feature); + let style = vectorcraft_doc::text::CharStyle { size: 36.0, font_family: family.into(), features: vec!["salt".into()], ..Default::default() }; + for (s, byte) in [("\u{0644}\u{0627}", 0), ("\u{0628}\u{0644}\u{0627}", 2)] { + let t = text(s, style.clone()); + let shaped = glyphs(&t); + assert!(shaped.contains(&(byte, 4, salted)), "{family}: salt turns the ligature into {LAM_ALEF_SALT}: {shaped:?}"); + assert_eq!(alternates(&t), 1, "{family}: {s}: the salted ligature, and nothing else"); } } } @@ -154,11 +186,36 @@ fn lam_alef_in_liga_is_not_an_alternate() { /// Only a lam followed by an alef (marks between or after allowed) is the required lam-alef. #[test] fn only_lam_alef_clusters_are_the_required_ligature() { - for s in ["\u{0644}\u{0627}", "\u{0644}\u{0622}", "\u{0644}\u{0623}", "\u{0644}\u{0625}", "\u{0644}\u{064E}\u{0627}", "\u{0644}\u{0627}\u{064B}"] - { + // Marks of the Arabic block, Arabic Extended-A (U+08E4, U+08F0), Extended-B (U+0898) and + // Extended-C (U+10EFD), and Quranic marks (U+0610, U+06ED). + for s in [ + "\u{0644}\u{0627}", + "\u{0644}\u{0622}", + "\u{0644}\u{0623}", + "\u{0644}\u{0625}", + "\u{0644}\u{064E}\u{0627}", + "\u{0644}\u{0627}\u{064B}", + "\u{0644}\u{08E4}\u{0627}", + "\u{0644}\u{08F0}\u{0627}", + "\u{0644}\u{0898}\u{0627}", + "\u{0644}\u{0627}\u{10EFD}", + "\u{0644}\u{0610}\u{06ED}\u{0627}", + ] { assert!(crate::text_geom::is_lam_alef(s), "{s:?}"); } - for s in ["", "\u{0644}", "\u{0627}\u{0644}", "\u{0644}\u{0628}", "\u{0628}\u{0644}\u{0627}", "\u{0644}\u{0627}\u{0627}", "fi", "\u{064E}"] { + // Not marks: tatweel (U+0640) and the number mark above (U+08E2, a format character). + for s in [ + "", + "\u{0644}", + "\u{0627}\u{0644}", + "\u{0644}\u{0628}", + "\u{0628}\u{0644}\u{0627}", + "\u{0644}\u{0627}\u{0627}", + "fi", + "\u{064E}", + "\u{0644}\u{0640}\u{0627}", + "\u{0644}\u{08E2}\u{0627}", + ] { assert!(!crate::text_geom::is_lam_alef(s), "{s:?}"); } } diff --git a/crates/render/src/text_geom.rs b/crates/render/src/text_geom.rs index bf058d75fc..0d65dfbffd 100644 --- a/crates/render/src/text_geom.rs +++ b/crates/render/src/text_geom.rs @@ -48,17 +48,28 @@ impl TextGeom { /// The boxes of the glyphs of `t` (the text this geometry is of) that optional OpenType features /// chose (Preferences › Highlight Alternate Glyphs): candidates the text's required shaping /// alone doesn't give ([`required_shaping`]). Arabic letters joining, Indic conjuncts and the - /// lam-alef ligature are what the script needs, not alternates (the lam-alef ligature also when - /// a font files it under `liga`: [`is_lam_alef`]). Measured once. + /// lam-alef ligature are what the script needs, not alternates. A font may file the lam-alef + /// ligature under `liga`, which required shaping turns off, so a lam-alef cluster + /// ([`is_lam_alef`]) is also compared with its shaping with `liga` left on: an optional feature + /// that changes its glyph beyond that (a stylistic alternate…) is still highlighted. Measured + /// once. pub(crate) fn alternate_glyphs(&self, t: &TextObject) -> &BezPath { self.alternate_glyphs.get_or_init(|| { let mut out = BezPath::new(); if self.alternate_candidates.is_empty() { return out; } - let required = required_shaping(t); + let required = required_shaping(t, &["-liga", "-calt"]); + let plain = t.plain_text(); + let in_lam_alef = |c: &AlternateCandidate| plain.get(c.byte..c.byte.saturating_add(c.len)).is_some_and(is_lam_alef); + // Laid out only when the text has a lam-alef candidate. + let with_liga = self.alternate_candidates.iter().any(in_lam_alef).then(|| required_shaping(t, &["-calt"])); + let gives = |map: &std::collections::HashMap<(usize, usize), Vec<(u32, u32)>>, c: &AlternateCandidate| { + map.get(&(c.byte, c.len)).is_some_and(|glyphs| glyphs.contains(&(c.font_id, c.gid))) + }; for c in &self.alternate_candidates { - if !required.get(&(c.byte, c.len)).is_some_and(|glyphs| glyphs.contains(&(c.font_id, c.gid))) { + let lam_alef_ligature = || in_lam_alef(c) && with_liga.as_ref().is_some_and(|m| gives(m, c)); + if !gives(&required, c) && !lam_alef_ligature() { out.extend(c.cell.iter()); } } @@ -86,12 +97,14 @@ pub(crate) fn is_opentype_alternate(nominal_gid: u32, shaped_gid: u32, cluster_c } /// Whether `cluster` is a lam followed by an alef (plain, with madda, or with hamza above or below), -/// with any Arabic marks between or after them: the lam-alef ligature, which the Unicode -/// Standard's Arabic chapter treats as obligatory, not a stylistic choice. Fonts made before -/// `rlig` was common put it in `liga`, which [`required_shaping`] turns off, so it is required -/// by its characters whatever feature the font files it under. +/// with any combining marks (Unicode general category M: the Arabic harakat, Quranic marks and +/// those of Arabic Extended-A, -B and -C) between or after them: the lam-alef ligature, which the +/// Unicode Standard's Arabic chapter treats as obligatory, not a stylistic choice. Fonts made +/// before `rlig` was common put it in `liga`, which [`required_shaping`] turns off, so +/// [`TextGeom::alternate_glyphs`] also accepts its glyph from shaping with `liga` on. pub(crate) fn is_lam_alef(cluster: &str) -> bool { - let is_mark = |c: &char| matches!(c, '\u{0610}'..='\u{061A}' | '\u{064B}'..='\u{065F}' | '\u{0670}' | '\u{06D6}'..='\u{06DC}' | '\u{06DF}'..='\u{06E4}' | '\u{06E7}' | '\u{06E8}' | '\u{06EA}'..='\u{06ED}'); + use unicode_general_category::{GeneralCategory as G, get_general_category}; + let is_mark = |c: &char| matches!(get_general_category(*c), G::NonspacingMark | G::SpacingMark | G::EnclosingMark); let mut letters = cluster.chars().filter(|c| !is_mark(c)); matches!((letters.next(), letters.next(), letters.next()), (Some('\u{0644}'), Some('\u{0622}' | '\u{0623}' | '\u{0625}' | '\u{0627}'), None)) } @@ -108,14 +121,16 @@ pub(crate) struct AlternateCandidate { } /// The glyphs `t` is shaped to by required shaping alone, by cluster (`byte`, `len`) → `(font, -/// glyph)`: laid out again with every optional feature off (standard and contextual ligatures and -/// alternates, and the features its characters turn on: stylistic sets, swashes, discretionary -/// ligatures, figure styles…). What is left is what the script needs: `ccmp`, `locl`, `rlig`, -/// Arabic's `init`, `medi`, `fina` and `isol`, the Indic and other complex scripts' required sets. -fn required_shaping(t: &TextObject) -> std::collections::HashMap<(usize, usize), Vec<(u32, u32)>> { +/// glyph)`: laid out again with every optional feature off (with `features` `-liga` and `-calt`: +/// standard and contextual ligatures and alternates, and the features its characters turn on: +/// stylistic sets, swashes, discretionary ligatures, figure styles…). What is left is what the +/// script needs: `ccmp`, `locl`, `rlig`, Arabic's `init`, `medi`, `fina` and `isol`, the Indic +/// and other complex scripts' required sets. With `features` `-calt` alone, standard ligatures +/// stay on (an older font's lam-alef). +fn required_shaping(t: &TextObject, features: &[&str]) -> std::collections::HashMap<(usize, usize), Vec<(u32, u32)>> { let mut plain = t.clone(); for run in &mut plain.runs { - run.style.features = vec!["-liga".into(), "-calt".into()]; + run.style.features = features.iter().map(|f| (*f).into()).collect(); } let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &plain); let mut glyphs: std::collections::HashMap<(usize, usize), Vec<(u32, u32)>> = std::collections::HashMap::new(); @@ -193,7 +208,7 @@ pub(crate) fn text_geom_snapped(t: &TextObject, snap: Option<Affine>) -> TextGeo let cluster_chars = cluster.chars().count(); let Some(first) = cluster.chars().next() else { continue }; let nominal = db.face_by_id(g.font_id).map(|f| f.glyph_for(first)).unwrap_or(0); - if is_opentype_alternate(nominal, g.gid, cluster_chars) && !is_lam_alef(cluster) { + if is_opentype_alternate(nominal, g.gid, cluster_chars) { alternate_candidates.push(AlternateCandidate { byte: g.byte, len: g.len, font_id: g.font_id, gid: g.gid, cell }); } } diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 449221f9f1..f3619679ff 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -352,21 +352,29 @@ pub fn lam_alef_family(feature: &[u8; 4]) -> &'static str { } } +/// The glyph [`lam_alef_font`]'s `salt` gives its lam + alef ligature (H): M. +pub const LAM_ALEF_SALT: char = 'M'; + /// A test-only Arabic cmap over bundled Source Sans 3: lam uses l, alef I, alef with hamza above -/// J and beh b. The `GSUB` table's `arab` script has one ligature lookup, under `feature`, that -/// joins lam + alef into H and lam + alef with hamza above into K. Older fonts put the mandatory -/// lam-alef ligature in `liga` rather than `rlig`; this builds either, without an OS font. `None` -/// when it can't be built. +/// J, beh b and fatha the combining acute (a mark in the font's `GDEF`). The `GSUB` table's `arab` +/// script has one ligature lookup, under `feature`, that skips marks and joins lam + alef into H +/// and lam + alef with hamza above into K, and a `salt` lookup that turns H into +/// [`LAM_ALEF_SALT`]. Older fonts put the mandatory lam-alef ligature in `liga` rather than +/// `rlig`; this builds either, without an OS font. `None` when it can't be built. pub fn lam_alef_font(feature: &[u8; 4]) -> Option<Vec<u8>> { use write_fonts::tables::cmap::Cmap; - use write_fonts::tables::gsub::{Gsub, Ligature, LigatureSet, LigatureSubstFormat1, SubstitutionLookup, SubstitutionLookupList}; - use write_fonts::tables::layout::{CoverageFormat1, Feature, FeatureList, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord}; + use write_fonts::tables::gsub::{ + Gsub, Ligature, LigatureSet, LigatureSubstFormat1, SingleSubstFormat2, SubstitutionLookup, SubstitutionLookupList, + }; + use write_fonts::tables::layout::{ + CoverageFormat1, Feature, FeatureList, FeatureRecord, LangSys, Lookup, LookupFlag, Script, ScriptList, ScriptRecord, + }; use write_fonts::types::GlyphId16; const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); let font = skrifa::FontRef::new(BASE).ok()?; let charmap = font.charmap(); - let mapping = [('\u{0644}', 'l'), ('\u{0627}', 'I'), ('\u{0623}', 'J'), ('\u{0628}', 'b')]; + let mapping = [('\u{0644}', 'l'), ('\u{0627}', 'I'), ('\u{0623}', 'J'), ('\u{0628}', 'b'), ('\u{064E}', '\u{0301}')]; let mappings = mapping.into_iter().map(|(c, source)| Some((c, write_fonts::types::GlyphId::new(charmap.map(source)?.to_u32())))); let cmap = Cmap::from_mappings(mappings.collect::<Option<Vec<_>>>()?).ok()?; let family = lam_alef_family(feature); @@ -380,9 +388,17 @@ pub fn lam_alef_font(feature: &[u8; 4]) -> Option<Vec<u8>> { let coverage = CoverageFormat1::new(vec![gid('l')?]); let ligatures = vec![Ligature::new(gid('H')?, vec![gid('I')?]), Ligature::new(gid('K')?, vec![gid('J')?])]; let subst = LigatureSubstFormat1::new(coverage.into(), vec![LigatureSet::new(ligatures)]); - let features = FeatureList::new(vec![FeatureRecord::new(Tag::new(feature), Feature::new(None, vec![0]))]); - let lookups = SubstitutionLookupList::new(vec![SubstitutionLookup::Ligature(Lookup::new(Default::default(), vec![subst]))]); - let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"arab"), Script::new(Some(LangSys::new(vec![0])), vec![]))]); + let salt = SingleSubstFormat2::new(CoverageFormat1::new(vec![gid('H')?]).into(), vec![gid(LAM_ALEF_SALT)?]); + // Features sorted by tag, as OpenType requires: `liga` / `rlig`, then `salt`. + let features = FeatureList::new(vec![ + FeatureRecord::new(Tag::new(feature), Feature::new(None, vec![0])), + FeatureRecord::new(Tag::new(b"salt"), Feature::new(None, vec![1])), + ]); + let lookups = SubstitutionLookupList::new(vec![ + SubstitutionLookup::Ligature(Lookup::new(LookupFlag::IGNORE_MARKS, vec![subst])), + SubstitutionLookup::Single(Lookup::new(Default::default(), vec![salt.into()])), + ]); + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"arab"), Script::new(Some(LangSys::new(vec![0, 1])), vec![]))]); builder.add_table(&Gsub::new(scripts, features, lookups)).ok()?; for r in font.table_directory.table_records() { let tag = Tag::new(&r.tag().to_be_bytes()); diff --git a/docs/type-parity.md b/docs/type-parity.md index c0220b1933..dbf195b8a8 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (Highlight Alternate Glyphs leaves the required lam-alef ligature unhighlighted also in older Arabic fonts (such as legacy Arial) that put it in `liga` rather than `rlig` (#394); scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Highlight Alternate Glyphs: an optional feature (such as `salt`) that changes a lam-alef ligature is highlighted again, only the required ligature staying clear, and a lam-alef with any combining mark (Arabic Extended-A/B/C included) counts as the ligature (#394); scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -28,7 +28,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Character and Paragraph panels, styles with overrides | done | Character-style Auto-leading resets, partial definitions, local leading overrides, override markers, Undo/Redo and native serialization have regression coverage; differing paragraph alignments leave the shared alignment buttons unselected (headless regressions, full integration CI and visual review pass); mixed-value display for other paragraph fields remains missing | | Character size and horizontal scale after object/group scaling | done | #1034: fields and setters compensate the stored affine; point size follows the transformed em-height axis, not the glyph ink bounds. Range edits, keyboard increments, leading and baseline shift use document points; rotation, reflection and shear remain editable. | | Preserve font sizes while scaling a group | missing | Separate enhancement; scaling still scales text with the other artwork. | -| OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607) | +| OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607) | | Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux) | | Missing glyphs set in an installed font made for their script (Thai, Lao, Khmer, Myanmar first; then any font that has them) | done | Thai: Leelawadee UI, Tahoma, Thonburi, Sukhumvit Set, Noto Sans Thai, TLWG | | Full font-name matching (OpenType name ID 4) | done | #1258: loaded/cataloged faces and Missing Fonts searches; localized names and variable default faces; Windows font-service QA pending | @@ -71,6 +71,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Highlight Alternate Glyphs: an optional feature (such as `salt`) that changes a lam-alef ligature is highlighted again, only the required ligature staying clear, and a lam-alef with any combining mark (Arabic Extended-A/B/C included) counts as the ligature (#394); scores unchanged | | 2026-10-30 | minor | Highlight Alternate Glyphs leaves the required lam-alef ligature unhighlighted also in older Arabic fonts (such as legacy Arial) that put it in `liga` rather than `rlig` (#394); scores unchanged | | 2026-10-30 | minor | Character panel menu › Show Snap to Glyph Options shows the Snap to Glyph section (Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides, Anchor Point; `view.snapToGlyph.options`) (#4232); scores unchanged | | 2026-10-29 | minor | Font fallback keeps a letter and its combining marks in one face; Vietnamese stacked diacritics (Ể, Ứ, Ự) attach in precomposed, decomposed and keyboard forms (#4491); scores and hours unchanged | From 2e7b2b7f96478842cacdd4272261c70b4b6f5b5e Mon Sep 17 00:00:00 2001 From: SusieeTheFemboy <96988330+SusieeTheLinuxUser@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:12:24 +0100 Subject: [PATCH 073/260] SVG import: an embedded SVG image gets the feConvolveMatrix order check too Files::svg parsed nested SVG images with usvg without the check the top-level import makes, so an overflowing order inside an <image> still reached usvg's multiply. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/svg/src/import/files.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/svg/src/import/files.rs b/crates/svg/src/import/files.rs index 722d043d44..b6d488c9ea 100644 --- a/crates/svg/src/import/files.rs +++ b/crates/svg/src/import/files.rs @@ -287,8 +287,10 @@ impl Files { if depth::xml_deeper_than(text, left) { return leave_out(&self.too_deep, true); } - let height = depth::height(&super::parse(text).ok()?, left); - let Some(height) = height else { return leave_out(&self.too_deep, true) }; + let xml = super::parse(text).ok()?; + let Some(height) = depth::height(&xml, left) else { return leave_out(&self.too_deep, true) }; + // usvg's parser would overflow on it, as on the SVG holding it (`import`). + super::convolve_matrices_ok(&xml).ok()?; self.note_text(text); self.depth.store(used + height, Ordering::Relaxed); let tree = usvg::Tree::from_data_nested(text.as_bytes(), opts); @@ -462,6 +464,22 @@ mod tests { assert_eq!(read(MAX_ELEMENT_DEPTH, 0), (false, 1)); } + /// An SVG image with a `feConvolveMatrix` order usvg's multiply overflows is left out before + /// usvg reads it, as the SVG holding it would be refused. + #[test] + fn svg_images_with_an_overflowing_convolve_order_are_left_out() { + let read = |order: &str| { + let svg = format!( + r#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4"><filter id="f"><feConvolveMatrix order="{order}" kernelMatrix="1"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"# + ); + let files = Files::default(); + let resolver = files.resolver(1); + matches!((resolver.resolve_data)("image/svg+xml", Arc::new(svg.into_bytes()), &usvg::Options::default()), Some(ImageKind::SVG(_))) + }; + assert!(!read("2147483647")); + assert!(read("1")); + } + #[test] fn the_placeholder_is_a_png() { let png = marker().unwrap(); From 9efe6dc76462fed745ed303a02cce1de345b916c Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 18:56:19 +0700 Subject: [PATCH 074/260] PDF import: a font name's family is looked for at no more than 16 of its hyphens The name comes from the file, and each lookup walks it, so a name made of thousands of hyphens took quadratic time. --- crates/pdf/src/import_text.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/pdf/src/import_text.rs b/crates/pdf/src/import_text.rs index 373437cfa4..8157759e7d 100644 --- a/crates/pdf/src/import_text.rs +++ b/crates/pdf/src/import_text.rs @@ -985,8 +985,9 @@ impl Families { } // The longest part of the name before a hyphen (or the comma of `Arial,Bold`, ISO 32000-1 // §9.6.3) that names an available family, the rest its style: a family can hold hyphens - // (`Noto-Sans-Bold` is Noto Sans, Bold). - let cuts = std::iter::once(name.len()).chain(name.rmatch_indices(['-', ',']).map(|(i, _)| i)); + // (`Noto-Sans-Bold` is Noto Sans, Bold). The name is the file's: a few cuts from its end are + // enough for any family, and each costs a pass over the name. + let cuts = std::iter::once(name.len()).chain(name.rmatch_indices(['-', ',']).map(|(i, _)| i).take(16)); for cut in cuts { let (fam, style) = (name.get(..cut).unwrap_or(name), name.get(cut + 1..).unwrap_or("")); if let Some(f) = [fam, strip_ps(fam)].iter().find_map(|f| self.0.get(&norm(f)).cloned()) { From 13bac047f35bcf46a8d5e645ad33188b79278cf9 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 18:56:43 +0700 Subject: [PATCH 075/260] EPS import: spend keeps its own doc comment --- crates/eps/src/import/interp.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index 68053f29bd..12232624f8 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -333,14 +333,14 @@ impl<'a> Interp<'a> { self.spend(1) } - /// Count `ops` operations' worth of work against [`MAX_OPS`]: what an operator that costs - /// far more than one operation (laying out type) does in a loop has to end too. /// Charge for work on `n` bytes or objects in one operator: one operation per 256, as `search` /// charges per 64 bytes, so a loop of big copies runs out of the budget. fn spend_bytes(&mut self, n: usize) -> Res { self.spend((n / 256) as u64) } + /// Count `ops` operations' worth of work against [`MAX_OPS`]: what an operator that costs + /// far more than one operation (laying out type) does in a loop has to end too. pub fn spend(&mut self, ops: u64) -> Res { self.ops = self.ops.saturating_add(ops); if self.ops > MAX_OPS { From 437280315f9ba7e9732faa0d79213e8e736d71b7 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 18:42:49 +0700 Subject: [PATCH 076/260] Fix #4803: Enter or Escape in a floating panel's field stays in the field --- crates/ui-egui/src/panel_docking.rs | 15 ++++++++- .../ui-egui/src/panel_docking/native_tests.rs | 31 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index d19b7be2c9..cdec00eaad 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1187,6 +1187,14 @@ fn forward_keys(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui: ctx.request_repaint(); } +/// A field of a floating panel's window that ends its editing on Enter or Escape lets go of the +/// keyboard in that frame, so craft-ui would forward the key to the main window's shortcuts: Enter +/// in the Transparency panel's Opacity field also opened the Move dialog (#4803). The key was the +/// field's, so it stays in the window. +fn keep_field_ending_keys(ui: &egui::Ui) { + ui.input_mut(|i| i.events.retain(|e| !matches!(e, egui::Event::Key { key: egui::Key::Enter | egui::Key::Escape, pressed: true, .. }))); +} + /// VectorCraft's look and wording of craft-ui's docking. fn dock_style(ui: &egui::Ui) -> craft_ui::docking::DockStyle { let t = crate::theme::Tokens::get(ui.ctx()); @@ -1244,9 +1252,11 @@ impl craft_ui::docking::DockContent<String> for PanelContent<'_> { self.app.canvas_area(ui); return; } - if ui.ctx().viewport_id() != egui::ViewportId::ROOT { + let floating = ui.ctx().viewport_id() != egui::ViewportId::ROOT; + if floating { crate::canvas::release_art_in_window(self.app, ui.ctx()); } + let field_had_keyboard = floating && ui.memory(|m| m.focused().is_some()); let t = crate::theme::Tokens::get(ui.ctx()); let back = ui.max_rect(); if back.is_positive() { @@ -1263,6 +1273,9 @@ impl craft_ui::docking::DockContent<String> for PanelContent<'_> { crate::dock::panel_body(self.app, ui, id, width, height) }); } + if field_had_keyboard { + keep_field_ending_keys(ui); + } } fn logical_label(&self, id: &String) -> String { diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index 41edab720a..ab47205743 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -240,6 +240,37 @@ fn keys_typed_in_a_native_window_run_the_main_windows_shortcuts() { assert!(h.app.session.active().unwrap().selection.objects.is_empty()); } +/// Enter that commits a field of a floating panel's window, and Escape that cancels one, are the +/// field's: with an object selected and the Selection tool, Enter didn't also open the Move dialog +/// (#4803). +#[test] +fn enter_and_escape_in_a_native_windows_field_stay_in_the_field() { + let mut h = Harness::new(); + h.app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + h.app.run("select.all", json!({})).unwrap(); + let viewport = h.float("transparency"); + // The window's first text field (Opacity), by the state its text box keeps. + let ctx = h.ctx.clone(); + let field = ctx + .viewport_for(viewport, |vp| vp.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).map(|w| (w.id, w.rect)).collect::<Vec<_>>()) + .into_iter() + .find(|(id, _)| egui::TextEdit::load_state(&ctx, *id).is_some()) + .map(|(_, rect)| rect.center()) + .expect("the panel has a text field"); + for key in [Key::Enter, Key::Escape] { + if let Some(window) = h.host.borrow_mut().windows.get_mut(&viewport) { + window.events.extend([button(field, true), button(field, false)]); + } + h.frames(2); + h.key_in(viewport, key); + assert!(h.app.ui.dialog.is_none(), "{key:?} in the field opens no dialog"); + assert_eq!(h.app.session.active().unwrap().selection.objects.len(), 1, "{key:?} in the field keeps the selection"); + } + // Keys typed with no field editing still reach the main window. + h.key_in(viewport, Key::Enter); + assert!(h.app.ui.dialog.is_some(), "Enter outside a field opens the Move dialog"); +} + #[test] fn a_modal_blocks_native_windows_and_takes_the_keyboard_from_them() { let mut h = Harness::new(); From 78a68bd8ecf0279b48ec76d16d8da781a2a3b3e7 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 19:01:14 +0700 Subject: [PATCH 077/260] Fix #4835: Artwork Cleanup's Duplicate Objects finds type set twice in the same place --- crates/engine/src/cmd/addons/cleanup.rs | 2 +- .../engine/src/cmd/addons/cleanup/checks.rs | 35 +++++++++++++++++-- crates/engine/src/cmd/addons/cleanup/tests.rs | 20 +++++++++++ docs/mcp.md | 2 +- 4 files changed, 54 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/addons/cleanup.rs b/crates/engine/src/cmd/addons/cleanup.rs index 4f96c26346..b65fc75ac3 100644 --- a/crates/engine/src/cmd/addons/cleanup.rs +++ b/crates/engine/src/cmd/addons/cleanup.rs @@ -46,7 +46,7 @@ pub fn specs() -> Vec<CommandSpec> { "Health Check", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{scope?: \"selection\"|\"document\" (default: the selection, or the document while nothing is selected), kinds?: [kind…] (default: all: emptyText, strayPoints (paths of one anchor), unpainted, zeroOpacity, duplicateObjects (a path stacked on an identical one), offArtboard, duplicateAnchors (neighbours within 0.01 pt), tinyHandles (under 0.01 pt), collinearAnchors (corners on a straight run, turning less than sine 0.005), nearPoints (anchors within 0.01 pt of other paths' anchors), nearlyClosed (ends within 0.01 pt), filledOpenPaths (filled, unstroked open paths), needlessClipGroups (an unpainted clip that clips nothing, hides everything, or is a rectangle round all its art), needlessCompounds (one path or none), needlessGroups (one member or none, nothing of their own), emptyArtboards (the document only))} find issues without changing anything; locked and hidden objects are left out → {scope, total, findings: [{kind, label, count, ids (the objects, at most 1000), artboards (indexes)}]} for the kinds found", + "{scope?: \"selection\"|\"document\" (default: the selection, or the document while nothing is selected), kinds?: [kind…] (default: all: emptyText, strayPoints (paths of one anchor), unpainted, zeroOpacity, duplicateObjects (a path stacked on an identical one, or type on the same type within 1 pt), offArtboard, duplicateAnchors (neighbours within 0.01 pt), tinyHandles (under 0.01 pt), collinearAnchors (corners on a straight run, turning less than sine 0.005), nearPoints (anchors within 0.01 pt of other paths' anchors), nearlyClosed (ends within 0.01 pt), filledOpenPaths (filled, unstroked open paths), needlessClipGroups (an unpainted clip that clips nothing, hides everything, or is a rectangle round all its art), needlessCompounds (one path or none), needlessGroups (one member or none, nothing of their own), emptyArtboards (the document only))} find issues without changing anything; locked and hidden objects are left out → {scope, total, findings: [{kind, label, count, ids (the objects, at most 1000), artboards (indexes)}]} for the kinds found", has_doc, check ), diff --git a/crates/engine/src/cmd/addons/cleanup/checks.rs b/crates/engine/src/cmd/addons/cleanup/checks.rs index 46c81293dd..c3abd029be 100644 --- a/crates/engine/src/cmd/addons/cleanup/checks.rs +++ b/crates/engine/src/cmd/addons/cleanup/checks.rs @@ -235,17 +235,46 @@ fn is_plain(n: &Node) -> bool { && *n.extras() == NodeExtras::default() } -/// Is `n` a plain path (full opacity, normal blending) identical to the object just below it? +/// Is `n` a plain path or type object (full opacity, normal blending) that doubles the object just +/// below it? fn duplicates_the_one_below(d: &Document, n: &Node) -> bool { - if !matches!(n.kind, NodeKind::Path { .. }) || n.opacity < 1.0 || n.blend != BlendMode::Normal { + if n.opacity < 1.0 || n.blend != BlendMode::Normal { return false; } let below = d.position(n.id).and_then(|(parent, i, _)| d.children(parent)?.get(i.checked_sub(1)?).cloned()); below.is_some_and(|b| { - b.visible && b.kind == n.kind && b.appearance == n.appearance && b.opacity == n.opacity && b.blend == n.blend && b.extras() == n.extras() + b.visible + && same_art(&b.kind, &n.kind) + && b.appearance == n.appearance + && b.opacity == n.opacity + && b.blend == n.blend + && b.extras() == n.extras() }) } +/// Distance (pt) within which doubled type counts as stacked: text set twice from a PDF or an old +/// file, or for a fake bold, is often a fraction of a point off. +const DOUBLED_TYPE: f64 = 1.0; + +/// The same path, or the same type (text, styles, size and turn) within [`DOUBLED_TYPE`] of it. +fn same_art(a: &NodeKind, b: &NodeKind) -> bool { + match (a, b) { + (NodeKind::Path { .. }, NodeKind::Path { .. }) => a == b, + (NodeKind::Text(a), NodeKind::Text(b)) => { + let ([a0, a1, a2, a3, ax, ay], [b0, b1, b2, b3, bx, by]) = (a.xf.as_coeffs(), b.xf.as_coeffs()); + [a0, a1, a2, a3] == [b0, b1, b2, b3] && (ax - bx).hypot(ay - by) <= DOUBLED_TYPE && { + // `b` placed on `a`, with `a`'s layout caches (they are in document space). + let mut moved = (**b).clone(); + moved.xf = a.xf; + moved.cached_bounds = a.cached_bounds; + moved.cached_baselines.clone_from(&a.cached_baselines); + **a == moved + } + } + _ => false, + } +} + fn inside(a: Rect, b: Rect) -> bool { a.x0 >= b.x0 && a.y0 >= b.y0 && a.x1 <= b.x1 && a.y1 <= b.y1 } diff --git a/crates/engine/src/cmd/addons/cleanup/tests.rs b/crates/engine/src/cmd/addons/cleanup/tests.rs index 3351dd7550..d02e1e4c09 100644 --- a/crates/engine/src/cmd/addons/cleanup/tests.rs +++ b/crates/engine/src/cmd/addons/cleanup/tests.rs @@ -226,6 +226,26 @@ fn each_check_finds_and_fixes_its_issue_and_leaves_clean_art_alone() { } } +/// Type set twice in the same place (from a PDF, or for a fake bold) is a duplicate within a point: +/// Show selects the upper copy and Fix removes it. Other text, or the same text further off, stays. +#[test] +fn doubled_type_within_a_point_is_a_duplicate() { + let mut s = session(); + let text = |s: &mut Session, x: f64, text: &str| id_of(&s.execute("text.create", &json!({"x": x, "y": 100, "text": text})).unwrap()); + let base = text(&mut s, 20.0, "Total"); + let doubled = text(&mut s, 20.4, "Total"); + let other = text(&mut s, 20.0, "Subtotal"); + let far = text(&mut s, 23.0, "Subtotal"); + assert_eq!(found(&mut s, "duplicateObjects", "document"), 1); + let shown = s.execute("addon.cleanup.show", &json!({"kind": "duplicateObjects", "scope": "document"})).unwrap(); + assert_eq!(shown["ids"], json!([doubled.0])); + s.execute("addon.cleanup.fix", &json!({"kinds": ["duplicateObjects"], "scope": "document"})).unwrap(); + assert!(node(&s, doubled).is_none()); + for id in [base, other, far] { + assert!(node(&s, id).is_some(), "{id:?} stays"); + } +} + #[test] fn fix_all_is_one_undo_step() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 90ce4f6c3a..71ae5c02d0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5726,7 +5726,7 @@ envelopes, graphs, symbols), are left out. | `strayPoints` | Paths of one anchor (not clipping paths) | Removes them | | `unpainted` | Paths and compound paths with no fill and no stroke | Removes them | | `zeroOpacity` | Objects at 0 % opacity | Removes them | -| `duplicateObjects` | A path stacked directly on an identical one (geometry, paint, opacity) | Removes the upper one | +| `duplicateObjects` | A path stacked directly on an identical one (geometry, paint, opacity), or type stacked directly on the same type (text, styles, paint) within 1 pt of it | Removes the upper one | | `offArtboard` | Top-level objects that touch no artboard | Removes them | | `duplicateAnchors` | Neighbouring anchors within 0.01 pt | Merges them | | `tinyHandles` | Handles shorter than 0.01 pt | Retracts them | From 672a5342a617c1ffb6193b3a8a1dac5adf93764e Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 19:19:55 +0700 Subject: [PATCH 078/260] Fix #4817: Properties' Quick Actions has Blend Options for a selected blend with any tool --- crates/ui-egui/src/panels/properties.rs | 8 +++++--- crates/ui-egui/src/panels/properties/tests.rs | 10 +++++----- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 5 +++-- 4 files changed, 14 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 49716e0489..a10f5c1334 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -111,10 +111,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { section_header(ui, tl!("Quick Actions")); let is_group = matches!(first.as_ref().map(|n| &n.kind), Some(NodeKind::Group { .. })); let is_live = matches!(first.as_ref().map(|n| &n.kind), Some(NodeKind::Path { live: Some(l), .. }) if !matches!(**l, LiveShape::Path { .. })); - // Blend Options for one blend while the Blend tool is in use, Merge Live Paint for a Live - // Paint group selected with more to merge into it, as the Properties panel overview lists them + // Blend Options for one selected blend, Merge Live Paint for a Live Paint group selected with + // more to merge into it, as the Properties panel overview lists them // (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html>). - let blend_options = n_sel == 1 && app.session.tool_id() == "blend" && matches!(first.as_ref().map(|n| &n.kind), Some(NodeKind::Blend { .. })); + // The overview names the Blend tool; the blending page has the button for a blend selected with + // any tool (<https://helpx.adobe.com/illustrator/using/blending-objects.html>, #4817). + let blend_options = n_sel == 1 && matches!(first.as_ref().map(|n| &n.kind), Some(NodeKind::Blend { .. })); let merge_live_paint = n_sel > 1 && can_merge_live_paint(app); let mut actions: Vec<(&str, &str)> = vec![]; if n_sel > 1 { diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 7bf2e6d151..0bd879a318 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1254,18 +1254,18 @@ fn rect(app: &mut VectorcraftApp, x: f64, y: f64, w: f64, h: f64) -> serde_json: app.run("shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].clone() } -/// One blend selected with the Blend tool has Blend Options in Quick Actions, which opens the -/// Blend Options dialog on it; OK is one undo step. Not with another tool, nor for a blend -/// selected with another object. +/// One selected blend has Blend Options in Quick Actions, with the Selection tool (#4817) as with +/// the Blend tool, which opens the Blend Options dialog on it; OK is one undo step. Not for a +/// blend selected with another object. #[test] -fn blend_options_is_a_quick_action_for_one_blend_with_the_blend_tool() { +fn blend_options_is_a_quick_action_for_one_blend() { let mut app = new_app(); let (a, b) = (rect(&mut app, 20.0, 20.0, 40.0, 40.0), rect(&mut app, 200.0, 20.0, 40.0, 40.0)); app.run("select.set", json!({"ids": [a, b]})).unwrap(); let blend = app.run("object.blend.make", json!({})).unwrap()["id"].clone(); app.run("select.set", json!({"ids": [blend]})).unwrap(); let ctx = egui::Context::default(); - assert!(!shows(&tall(&mut app, &ctx, vec![]), "Blend Options"), "not with the Selection tool"); + assert!(shows(&tall(&mut app, &ctx, vec![]), "Blend Options"), "with the Selection tool"); app.select_tool("blend"); app.run("select.set", json!({"ids": [blend]})).unwrap(); let texts = tall(&mut app, &ctx, vec![]); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 58e42441c6..8712f26f5f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -519,7 +519,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Names of new and renamed artboards, brushes and patterns:** `artboard.new` and `artboard.setProps` trim the white space around the name they are given, as the Artboards panel's rename does, and a blank name gives the artboard its default name, Artboard N for the Nth artboard. `brush.new`, `brush.duplicate`, `brush.options`, `object.pattern.make`, `object.pattern.saveCopy` and `pattern.options` trim the name as the Brush Options dialog and the Pattern Options panel do, and compare the trimmed name with the names there are; a blank name gives the name each command gives when there is none, and Brush Options and Pattern Options keep the name. Tests in `tests/panelcmds.rs`, `tests/brushsym.rs` and `tests/pattern.rs` cover each command. Public references: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html), [Brushes](https://web.archive.org/web/20251018101754/https://helpx.adobe.com/illustrator/using/brushes.html) and [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copies). - **Pattern names and swatch names:** `pattern.options` refuses a new name that another pattern, a swatch or a color group has. It takes a name that only the pattern's own swatches have. The reference page does not say what happens when the new name is taken; the refusal follows VectorCraft's rule that swatches and color groups share one namespace (`Document::swatch_name_taken`), which `swatch.new` and `swatch.edit` also follow. A rename gives the new name only to the pattern's swatches that had the old one; any other swatch with the old name keeps it, and art linked to that swatch stays linked. `object.pattern.make` and `object.pattern.saveCopy` number a color group's name as they number a swatch's. Tests in `tests/pattern.rs` cover each command. Public reference: [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copy). - **A clip group in Properties:** with one clip group selected, the panel has Edit Clipping Path and Edit Contents at its top, under the Clip Group heading, which select the clipping path or the clipped art for the selection tools to transform alone, as Object › Clipping Mask does (<https://www.adobe.com/learn/illustrator/web/crop-using-masks>: with a clip group selected, the tutorial uses Edit Clipping Path at the top of the Properties panel to select the mask for editing, and uses Edit Contents to select the masked art). Edit Contents shows only when the group clips something. Not checked against the reference app: whether Properties keeps the buttons while the clipping path or the contents is selected; the Control bar has no clip-group buttons here. Evidence: `panels::properties::tests::one_clip_group_has_edit_clipping_path_and_edit_contents_at_the_top`. -- **Contextual controls in Properties:** the [Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html) lists controls that appear for particular selections and tools; Properties has them, each running the existing command. Quick Actions has Blend Options for one selected blend while the Blend tool is in use (the Blend Options dialog, OK one undo step) and Merge Live Paint when a Live Paint group is selected with more paths and nothing Live Paint refuses (`livePaint.merge`). Appearance has the stroke's Variable Width Profile list, the Control bar's, with the Width tool or when the stroke has a variable width (`stroke.set {profile}`), and beside fx the Delete icon: with one effect on the one selected object (its own or a fill's or stroke's) its name and an icon that removes it (`effect.remove`), with several an icon that opens the Appearance panel, as the overview describes. With Direct Selection and corners of one path selected, Corner and Corner Radius set the kind and radius of those corners (`object.setLiveShape`); a live rectangle's and polygon's own rows already do. Each edit is one undo step. The overview's Variable Font icon was already in Character. Not checked against the reference app: whether Merge needs two Live Paint groups (the overview speaks of several selected groups; `livePaint.merge` takes a group and paths), and where exactly each control sits in its section. Evidence: `panels::properties::tests::{blend_options_is_a_quick_action_for_one_blend_with_the_blend_tool, merge_live_paint_is_a_quick_action_for_a_live_paint_group_and_more, the_width_profile_shows_for_a_variable_width_or_the_width_tool, direct_selected_corners_show_their_kind_and_radius, one_effect_has_a_delete_icon_in_appearance}`. +- **Contextual controls in Properties:** the [Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html) lists controls that appear for particular selections and tools; Properties has them, each running the existing command. Quick Actions has Blend Options for one selected blend, with the Blend tool or any other, as the [blending page](https://helpx.adobe.com/illustrator/using/blending-objects.html) describes (#4817) (the Blend Options dialog, OK one undo step) and Merge Live Paint when a Live Paint group is selected with more paths and nothing Live Paint refuses (`livePaint.merge`). Appearance has the stroke's Variable Width Profile list, the Control bar's, with the Width tool or when the stroke has a variable width (`stroke.set {profile}`), and beside fx the Delete icon: with one effect on the one selected object (its own or a fill's or stroke's) its name and an icon that removes it (`effect.remove`), with several an icon that opens the Appearance panel, as the overview describes. With Direct Selection and corners of one path selected, Corner and Corner Radius set the kind and radius of those corners (`object.setLiveShape`); a live rectangle's and polygon's own rows already do. Each edit is one undo step. The overview's Variable Font icon was already in Character. Not checked against the reference app: whether Merge needs two Live Paint groups (the overview speaks of several selected groups; `livePaint.merge` takes a group and paths), and where exactly each control sits in its section. Evidence: `panels::properties::tests::{blend_options_is_a_quick_action_for_one_blend_with_the_blend_tool, merge_live_paint_is_a_quick_action_for_a_live_paint_group_and_more, the_width_profile_shows_for_a_variable_width_or_the_width_tool, direct_selected_corners_show_their_kind_and_radius, one_effect_has_a_delete_icon_in_appearance}`. - **Edit Artboards in Properties:** the active artboard's name is a field. Typing a new name and pressing Enter or clicking elsewhere renames that artboard in one undo step, as the Artboards panel's rename does (`artboard.setProps {index, name}`); pressing Escape or leaving the field empty keeps the old name. A click on the Artboard Options icon beside the field opens Artboard Options for the active artboard, as double-clicking the Artboard tool's button does (`tool.options {tool: "artboard"}`). Pointer and key tests in `panels/properties.rs` cover both. Public references: [Resize artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/resize-artboards.html) and [Create and add new artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/add-new-artboards.html). - **Artboard background colors:** each artboard can have a background color (`artboard.setProps {index, color}`, `color: null` removes it). With the Artboard tool, Properties has a Fill row: its list sets None, White or Black, and its chip and its Color Picker… item open the Color Picker for the artboard. Artboard Options has a Background Color row with a list that sets None, White or Black, and a color button. The canvas draws the artboard's paper in the color, multiplied with the paper color while Simulate Colored Paper is on, and the transparency grid still covers it. The native format saves the color, and a document without colors saves as before. Exports and print do not draw the color. Engine, canvas, Properties, Color Picker and Artboard Options tests cover it. Public reference: [Apply colors to artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/add-background-color-to-artboards.html). - **Resizing several artboards:** with several artboards selected with the Artboard tool, a new W or H in Properties, the Transform panel or the Control bar, a preset or an orientation in Properties or the Control bar, and a new Width or Height in Artboard Options resize every selected artboard in one undo step (`artboard.setProps {artboards}`); with Scale Artwork with Artboard on, Properties, the Transform panel and the Control bar scale each object once, with the artboard it was inside before the change. The Transform panel, the Control bar and Artboard Options resize each one about its own reference point, a preset sizes each one in its own orientation, and X and Y still move the active artboard alone. Pointer and key tests in `panels/properties.rs`, dialog tests in `dialogs/tests.rs` and an engine test in `tests/xform.rs` cover them. Public references: [Artboard Enhancements In Illustrator CC](https://blog.adobe.com/en/publish/2017/11/10/artboard-enhancements-in-illustrator-cc) (a height and a width entered once resize every selected artboard) and [Using multiple artboards](https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (2019). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 73e52f87a7..f32db08429 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Direct Selection snaps a dragged line end square to straight paths and grazing curves; Path Precision Tools add-on: Shared Edge Merge Tool; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Properties: Blend Options in Quick Actions for one selected blend with any tool, #4817; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -293,7 +293,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Toolbar without group labels by default, one or two columns; All Tools drawer by flyout group with shortcuts, its menu (Reset, Basic, Advanced) and Show section | done | #1751; a preference brings the labels back; `toolbar.show` sets the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls | | Actions panel: a clicked action stays selected for Play Current Selection and Delete Selection | partial | #1853 (part of #1629); editing actions and action shortcuts remain | | Actions panel: Create New Set (bottom bar, ≡ › New Set…) names a new set and Set Options… renames the current one; a click on a set's name makes it current and a recording goes into the current set ([helpx: Automation with actions](https://helpx.adobe.com/illustrator/using/automation-actions.html)) | partial | #3712; the New Action dialog (name, set menu, shortcut, colour), dragging actions between sets and deleting a set remain | -| Properties panel per context (every selection type's Quick Actions) | partial | one clip group: Edit Clipping Path and Edit Contents, at the top of the panel rather than in Quick Actions (G1); the overview's additional controls ([Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html)): Blend Options (one blend, Blend tool) and Merge Live Paint (a Live Paint group with more) in Quick Actions, the Width Profile list (Width tool or a variable-width stroke) and an applied effect's Delete icon in Appearance, Corner and Corner Radius for corners selected with Direct Selection; Variable Font was already there | +| Properties panel per context (every selection type's Quick Actions) | partial | one clip group: Edit Clipping Path and Edit Contents, at the top of the panel rather than in Quick Actions (G1); the overview's additional controls ([Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html)): Blend Options (one blend selected, with any tool, #4817) and Merge Live Paint (a Live Paint group with more) in Quick Actions, the Width Profile list (Width tool or a variable-width stroke) and an applied effect's Delete icon in Appearance, Corner and Corner Radius for corners selected with Direct Selection; Variable Font was already there | | Select › Start Global Edit / Stop Global Edit; Properties › Quick Actions with the Global Edit Options popover (Match: Appearance, Size; On Artboards: All Artboards or a range, Include Objects On Canvas; Result(s)); Escape stops it; the matched objects are highlighted in their layer colour while it runs | partial | #3521, `select.globalEdit` / `select.globalEditOptions`, `crates/engine/src/tests/globaledit.rs`; paths, compound paths and symbol instances; the Control panel's copy of the options, Shift-click to leave a match out, highlighting matches before the start and similar groups remain ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)) | | Contextual task bar | done | | | Control bar with Transform and Stroke popovers | done | | @@ -376,6 +376,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Properties: Quick Actions has Blend Options for one selected blend with any tool, not only the Blend tool, as the blending page describes (#4817); scores unchanged | | 2026-10-31 | minor | Smart guides and snapping: Snap to Perpendicular and Snap to Tangent for an existing line's end dragged with Direct Selection (#2530), so the tangent and perpendicular row is done; scores and estimates unchanged | | 2026-10-31 | minor | Grid Repeat Options has a Preview checkbox (#2651); scores and estimates unchanged | | 2026-10-31 | minor | Path Precision Tools add-on: the Shared Edge Merge Tool and Keep Shared Points Together; scores and estimates unchanged | From b0f6174c37aaf1262bbb90bd5c94cac08801a044 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 04:35:41 -0700 Subject: [PATCH 079/260] i18n: Dutch names a brush 'penseel' everywhere, with neuter agreement --- crates/ui-egui/src/i18n/nl.tsv | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 6078c314c9..d7a608c311 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2836,32 +2836,32 @@ theme Appearance Vormgeving Remove Asset Asset verwijderen Rename Asset Asset hernoemen Fill Rule Vulregel - Apply Brush Kwast toepassen + Apply Brush Penseel toepassen Break Link to Symbol Koppeling met symbool verbreken - Brush Definition Kwastdefinitie - Brush Options… Kwastopties… - Current Brush Huidige kwast - Current Symbol Huidige symbool - Delete Brush Kwast verwijderen + Brush Definition Penseeldefinitie + Brush Options… Penseelopties… + Current Brush Huidig penseel + Current Symbol Huidig symbool + Delete Brush Penseel verwijderen Delete Symbol Symbool verwijderen - Duplicate Brush Kwast dupliceren + Duplicate Brush Penseel dupliceren Duplicate Symbol Symbool dupliceren Edit Symbol Symbool bewerken - Expand Brush Strokes Kwaststreken omzetten - New Brush… Nieuwe kwast… - New Brush Nieuwe kwast + Expand Brush Strokes Penseelstreken omzetten + New Brush… Nieuw penseel… + New Brush Nieuw penseel Calligraphic Brush Kalligrafisch penseel Scatter Brush Verspreidingspenseel Art Brush Artpenseel Bristle Brush Borstelpenseel Pattern Brush Patroonpenseel Select art to make a scatter, art or pattern brush. Selecteer illustratie om een verspreidings-, art- of patroonpenseel te maken. - Brush Art Kwastillustratie + Brush Art Penseelillustratie New Symbol Nieuw symbool New Symbol… Nieuw symbool… Place Symbol Instance Symboolexemplaar plaatsen Redefine Symbol Symbool opnieuw definiëren - Remove Brush Stroke Kwaststreek verwijderen + Remove Brush Stroke Penseelstreek verwijderen Replace Symbol Symbool vervangen Select All Instances Alle exemplaren selecteren Symbol Sprayer Symboolspuit @@ -2937,7 +2937,7 @@ theme Appearance Vormgeving Saved Selections Opgeslagen selecties Select Guides Hulplijnen selecteren Move Guide to Layer Hulplijn naar laag verplaatsen - Blob Brush BLOB-kwast + Blob Brush Blob-penseel Convert Anchor Point Ankerpunt omzetten Curvature Kromming Delete Anchor Point Ankerpunt verwijderen @@ -3420,7 +3420,7 @@ theme Appearance Vormgeving Delete Swatch Kleurstaal verwijderen Duplicate Swatch Kleurstaal dupliceren Merge Swatches Kleurstalen samenvoegen - Move Brush Kwast verplaatsen + Move Brush Penseel verplaatsen Move Swatch Kleurstaal verplaatsen New Color Group Nieuwe kleurgroep New Swatch Nieuw kleurstaal From c0872ff9c6c02a32a5dcdee62ee8814f5de3bef5 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 11:40:51 +0000 Subject: [PATCH 080/260] Fix enhanced_preset Shapes for decorated High Fidelity Photo names Found while testing crates/trace/src/params.rs:248-251 (enhanced_preset) Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- crates/trace/src/params.rs | 2 +- crates/trace/tests/enhanced_preset_name.rs | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 crates/trace/tests/enhanced_preset_name.rs diff --git a/crates/trace/src/params.rs b/crates/trace/src/params.rs index 6ce6ce2415..dd5bc99298 100644 --- a/crates/trace/src/params.rs +++ b/crates/trace/src/params.rs @@ -247,5 +247,5 @@ pub fn presets() -> Vec<(&'static str, TraceParams)> { /// Gradients stay an option to turn on. Flat Logo, a preset of our own, has none. pub fn enhanced_preset(name: &str) -> Option<TraceParams> { let p = preset(name).filter(|p| p.mode != Mode::Logo)?; - Some(TraceParams { auto_grouping: true, shapes: !name.eq_ignore_ascii_case("High Fidelity Photo"), ..p }) + Some(TraceParams { auto_grouping: true, shapes: p != preset("High Fidelity Photo")?, ..p }) } diff --git a/crates/trace/tests/enhanced_preset_name.rs b/crates/trace/tests/enhanced_preset_name.rs new file mode 100644 index 0000000000..b84bb6e6a6 --- /dev/null +++ b/crates/trace/tests/enhanced_preset_name.rs @@ -0,0 +1,13 @@ +//! `enhanced_preset` resolves a name the way `preset` does (trimmed, brackets stripped, any case), +//! so Shapes is off for High Fidelity Photo however its name is written. + +use vectorcraft_trace::enhanced_preset; + +#[test] +fn enhanced_high_fidelity_photo_ignores_name_decoration() { + let plain = enhanced_preset("High Fidelity Photo").unwrap(); + assert!(!plain.shapes); + for name in ["[High Fidelity Photo]", " High Fidelity Photo ", " high fidelity photo "] { + assert_eq!(enhanced_preset(name), Some(plain.clone()), "{name:?}"); + } +} From 6664e366e7a62851e66f436b7d346f66a00c4f90 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 13:03:57 +0100 Subject: [PATCH 081/260] Reject repeated '#' in perspective grid colour parser Found while testing crates/tools/src/distort/perspective/define.rs:84-86 (Rgb::parse) Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- crates/tools/src/distort/perspective/define.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/tools/src/distort/perspective/define.rs b/crates/tools/src/distort/perspective/define.rs index a2dd6f4249..19600bac41 100644 --- a/crates/tools/src/distort/perspective/define.rs +++ b/crates/tools/src/distort/perspective/define.rs @@ -82,7 +82,8 @@ pub struct Rgb(pub [u8; 3]); impl Rgb { /// `#rrggbb` or `rrggbb`. pub fn parse(s: &str) -> Option<Self> { - let h = s.trim().trim_start_matches('#'); + let h = s.trim(); + let h = h.strip_prefix('#').unwrap_or(h); if h.len() != 6 || !h.chars().all(|c| c.is_ascii_hexdigit()) { return None; } @@ -397,6 +398,15 @@ mod tests { const AB: Rect = Rect::new(0.0, 0.0, 800.0, 600.0); + #[test] + fn rgb_rejects_repeated_hash() { + assert!(Rgb::parse("##ff0000").is_none()); + assert!(Rgb::parse("####00ff00").is_none()); + assert!(Rgb::try_from(String::from("##ff0000")).is_err()); + assert_eq!(Rgb::parse("#ff0000"), Some(Rgb([255, 0, 0]))); + assert_eq!(Rgb::parse("ff0000"), Some(Rgb([255, 0, 0]))); + } + #[test] fn the_station_point_places_the_vanishing_points() { let mut g = PerspectiveGrid::normal(2, AB); From aaeb1b2b35c43d10c92cbb99a604f97821e57854 Mon Sep 17 00:00:00 2001 From: Shunsuke Yoshizawa <63687325+yssy1982@users.noreply.github.com> Date: Sat, 31 Oct 2026 19:37:32 +0900 Subject: [PATCH 082/260] Respect SVG image-rendering pixelated attribute --- crates/svg/src/import/importer.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 2215458e8c..c2220f9d8f 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -652,10 +652,16 @@ impl Importer { if link.is_some() && !missing { blob.with_proxy() } else { blob } }); let xf = acc * Affine::scale_non_uniform(size.width() as f64 / pw as f64, size.height() as f64 / ph as f64); - self.named( + let mut node = self.named( i.id(), NodeKind::Image(Box::new(ImageObject { key, width: pw, height: ph, xf, link, placement: Default::default(), pixels: None })), - ) + )?; + + if i.rendering_mode() == usvg::ImageRendering::Pixelated { + node.extras_mut().pixelated = true; + } + + Some(node) } /// An SVG shown as an image (a data URL or a linked file) → its art, `acc` mapping its size. From 40dd6db6e1420830ea4fe23b6c44b7c23053747e Mon Sep 17 00:00:00 2001 From: marshiyar <57055687+marshiyar@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:04:01 -0700 Subject: [PATCH 083/260] contributors: add names for marshiyar --- contributors/people.toml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 0134ded6cb..55b5b38609 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -180,3 +180,8 @@ real_name = "Ashok Ram" [people.dylanmtaylor] sync_github_name = true + +[people.marshiyar] +display_name = "Arshiya" +real_name = "Arshiya Rahgozar" +sync_github_name = false From 54b0c7266c022dbec07a1b428d8755302111a3f3 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 20:28:52 +0700 Subject: [PATCH 084/260] Fix #4826: Artwork Cleanup's Join Point Text stacks one-line type into one object --- crates/engine/src/cmd/addons/cleanup/text.rs | 90 ++++++++++++++++++- .../src/cmd/addons/cleanup/text/tests.rs | 34 +++++++ crates/engine/tests/command_sweep.rs | 2 + crates/ui-egui/src/addons/cleanup.rs | 4 +- crates/ui-egui/src/addons/cleanup/tests.rs | 1 + crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + docs/mcp.md | 5 ++ docs/target-app-parity.md | 6 +- 32 files changed, 188 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/addons/cleanup/text.rs b/crates/engine/src/cmd/addons/cleanup/text.rs index 26a37efbf1..dd7cb67888 100644 --- a/crates/engine/src/cmd/addons/cleanup/text.rs +++ b/crates/engine/src/cmd/addons/cleanup/text.rs @@ -1,5 +1,5 @@ //! Artwork Cleanup's text tools: Break Text into Lines / Paragraphs / Words / Glyphs, Combine Point -//! Text, Split Text at Cursor, Remove Line / Paragraph Breaks, Set Alignment, Keep Position, Reset +//! Text, Join Point Text, Split Text at Cursor, Remove Line / Paragraph Breaks, Set Alignment, Keep Position, Reset //! Text Transform and Replace Missing Fonts. Each is one undo step. Pieces keep their characters' //! styles and stay where the layout drew them: each is moved so the glyph of its first character //! lands where it was. @@ -57,6 +57,15 @@ pub fn specs() -> Vec<CommandSpec> { has_selection, combine_text ), + cmd!( + "addon.cleanup.joinText", + "Join Point Text", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{ids?: [id…] (default: the selection)} join one-line horizontal point type into one point type object, as one undo step: pieces turned and sheared like the top-left one are read as lines (baselines within 0.4 em of each other), top to bottom, each line's pieces left to right with a space between them; each line becomes a paragraph, left aligned, and keeps the distance between baselines as its leading. The text keeps its character styles; the object takes the top-left piece's place and paint, and the other pieces go → {id (selected), joined (pieces merged into it), lines}", + has_selection, + join_text + ), cmd!( "addon.cleanup.removeBreaks", "Remove Breaks", @@ -641,6 +650,85 @@ fn combine_text(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "ids": ids, "combined": combined })) } +fn join_text(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "addon.cleanup.joinText"; + let d = &s.doc()?.doc; + let pieces: Vec<Piece> = + texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().filter_map(|id| Piece::of(d, id).map(|p| p.0)).collect(); + // The piece top-left on the page sets the turn; the others turned like it are read in that frame. + let on_page = |p: &Piece| Affine::new([p.turn[0], p.turn[1], p.turn[2], p.turn[3], 0.0, 0.0]) * p.at; + let first = pieces.iter().min_by(|x, y| { + let (a, b) = (on_page(x), on_page(y)); + a.y.total_cmp(&b.y).then(a.x.total_cmp(&b.x)) + }); + let mut kept: Vec<&Piece> = first.map(|f| pieces.iter().filter(|p| p.turned_like(f)).collect()).unwrap_or_default(); + kept.sort_by(|x, y| x.at.y.total_cmp(&y.at.y).then(x.at.x.total_cmp(&y.at.x))); + // Lines, top to bottom, by baseline; each line's pieces left to right. + let mut lines: Vec<Vec<&Piece>> = vec![]; + for piece in kept { + match lines.last_mut().filter(|l| l.first().is_some_and(|f| (f.at.y - piece.at.y).abs() <= SAME_LINE * f.size.min(piece.size))) { + Some(l) => l.push(piece), + None => lines.push(vec![piece]), + } + } + for line in &mut lines { + line.sort_by(|x, y| x.at.x.total_cmp(&y.at.x)); + } + let joined: usize = lines.iter().map(Vec::len).sum(); + let (Some(top), true) = (lines.first().and_then(|l| l.first()).copied(), joined >= 2) else { + return Err(EngineError::Other("Select two or more one-line point type objects to join".into())); + }; + let mut runs: Vec<vectorcraft_doc::TextRun> = vec![]; + let mut prev_y = None; + for line in &lines { + let y = line.first().map_or(top.at.y, |p| p.at.y); + // The line keeps the distance from the baseline above as its leading. + let leading = prev_y.map(|above| y - above).filter(|l: &f64| l.is_finite() && *l > 0.0); + prev_y = Some(y); + let last = |runs: &[vectorcraft_doc::TextRun]| runs.iter().rev().find(|r| !r.text.is_empty()).map(|r| r.style.clone()).unwrap_or_default(); + if !runs.is_empty() { + runs.push(vectorcraft_doc::TextRun::new("\n", last(&runs))); + } + let start = runs.len(); + for (k, piece) in line.iter().enumerate() { + let blank = runs.last().is_some_and(|r| r.text.ends_with(char::is_whitespace)) || piece.t.plain_text().starts_with(char::is_whitespace); + if k > 0 && !blank { + runs.push(vectorcraft_doc::TextRun::new(" ", last(&runs))); + } + runs.extend(piece.t.runs.iter().cloned()); + } + if let Some(l) = leading { + for r in runs.iter_mut().skip(start) { + r.style.leading = Some(l); + } + } + } + let mut m = top.t.clone(); + m.set_all_paras(ParaStyle { justify: Justify::Left, ..top.t.para.clone() }); + m.runs = runs; + edit::normalize(&mut m.runs); + m.ruby.clear(); + // The top-left piece's first glyph stays where it was. + let [a, b, c, dd] = top.turn; + let base = Affine::new([a, b, c, dd, 0.0, 0.0]) * Affine::translate(top.at.to_vec2()); + m.xf = base; + let x0 = glyph_starting(&layout(&m), 0).map_or(0.0, |g| g.x); + m.xf = base * Affine::translate((-x0, 0.0)); + refresh_bounds(&mut m); + let id = top.id; + let gone: Vec<NodeId> = lines.iter().flatten().map(|p| p.id).filter(|g| *g != id).collect(); + let count = lines.len(); + s.edit("Join Point Text", |d, sel| { + if let Some(n) = d.node_mut(id) { + n.kind = NodeKind::Text(Box::new(m)); + } + d.remove_many(&gone)?; + sel.set([id]); + Ok(()) + })?; + Ok(json!({ "id": id.0, "joined": joined, "lines": count })) +} + /// Remove the breaks `brk` in bytes `a..b` of `t`: one between two words becomes a space → how many /// went. fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize { diff --git a/crates/engine/src/cmd/addons/cleanup/text/tests.rs b/crates/engine/src/cmd/addons/cleanup/text/tests.rs index a2fa3225f0..2286288662 100644 --- a/crates/engine/src/cmd/addons/cleanup/text/tests.rs +++ b/crates/engine/src/cmd/addons/cleanup/text/tests.rs @@ -176,6 +176,40 @@ fn combine_joins_only_pieces_on_one_line_turned_alike() { assert!(other(s.execute("addon.cleanup.combineText", &json!({}))).contains("combine")); } +/// Join Point Text makes one object of stacked one-line pieces: lines top to bottom as paragraphs, +/// pieces on a line left to right, each line's baseline where it was (its leading is the distance +/// from the line above), in one undo step. A piece turned unlike the top-left one stays. +#[test] +fn join_stacks_lines_into_one_object_with_their_spacing() { + let mut s = session(); + let a = text(&mut s, json!({"x": 50, "y": 100, "text": "First", "size": 20})); + let b = text(&mut s, json!({"x": 120, "y": 101, "text": "line", "size": 20})); + let c = text(&mut s, json!({"x": 50, "y": 130, "text": "Second", "size": 20})); + let d = text(&mut s, json!({"x": 50, "y": 166, "text": "Third", "size": 20})); + let turned = text(&mut s, json!({"x": 300, "y": 300, "text": "Turned", "size": 20, "rotation": 45})); + let was = glyphs(&s, &[a, c, d]); + select(&mut s, &[d, b, turned, c, a]); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.joinText", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!((r["id"].as_u64(), r["joined"].as_u64(), r["lines"].as_u64()), (Some(a.0), Some(4), Some(3))); + let t = obj(&s, a); + assert_eq!(t.plain_text(), "First line\nSecond\nThird"); + assert_eq!(t.runs.iter().filter(|r| r.text.contains("Third")).map(|r| r.style.leading).collect::<Vec<_>>(), [Some(36.0)]); + // Each line's first glyph is where it was. + let now = glyphs(&s, &[a]); + for ch in ['F', 'S', 'T'] { + let (p, q) = (was.iter().find(|g| g.0 == ch).unwrap().1, now.iter().find(|g| g.0 == ch).unwrap().1); + assert!((p - q).hypot() < 0.05, "{ch}: {p:?} moved to {q:?}"); + } + let doc = &s.doc().unwrap().doc; + assert!(doc.node(b).is_none() && doc.node(c).is_none() && doc.node(d).is_none() && doc.node(turned).is_some()); + select(&mut s, &[turned]); + assert!(other(s.execute("addon.cleanup.joinText", &json!({}))).contains("join")); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(c).is_some(), "undo brings the pieces back"); +} + #[test] fn remove_line_and_paragraph_breaks() { let mut s = session(); diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 27c6088318..e80e93ce8a 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -601,6 +601,8 @@ fn structured_junk() { ("addon.cleanup.breakText", json!({"by": "words", "ids": "all"})), ("addon.cleanup.combineText", json!({"ids": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})), ("addon.cleanup.combineText", json!({"ids": [-1, 1e308]})), + ("addon.cleanup.joinText", json!({"ids": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})), + ("addon.cleanup.joinText", json!({"ids": [-1, 1e308, "x"]})), ("addon.cleanup.removeBreaks", json!({"kind": "paragraph", "ids": [1, 2, 3, 4, 5, 6, 7, 8, u64::MAX]})), ("addon.cleanup.removeBreaks", json!({"kind": 3})), ("addon.cleanup.removeBreaks", json!({"kind": "line", "ids": null})), diff --git a/crates/ui-egui/src/addons/cleanup.rs b/crates/ui-egui/src/addons/cleanup.rs index d44fe7b393..cf5dbbfd8a 100644 --- a/crates/ui-egui/src/addons/cleanup.rs +++ b/crates/ui-egui/src/addons/cleanup.rs @@ -38,7 +38,7 @@ fn replace_fonts() -> Value { /// modifier click does, command, params). type TextRow = (Option<&'static str>, Vec<(&'static str, Option<&'static str>, &'static str, Value)>); -fn text_rows() -> [TextRow; 4] { +fn text_rows() -> [TextRow; 5] { let align = |a: &str| json!({ "align": a }); let by = |b: &str| json!({ "by": b }); [ @@ -66,6 +66,7 @@ fn text_rows() -> [TextRow; 4] { ], ), (None, vec![("Combine Point Text", None, "addon.cleanup.combineText", json!({}))]), + (None, vec![("Join Point Text", None, "addon.cleanup.joinText", json!({}))]), ] } @@ -98,6 +99,7 @@ pub fn menu() -> Vec<Item> { let align = |a: &str| json!({ "align": a }); items.extend([ Item::Cmd("Combine Point Text", "addon.cleanup.combineText", json!({})), + Item::Cmd("Join Point Text", "addon.cleanup.joinText", json!({})), Item::Cmd("Break Text into Lines", "addon.cleanup.breakText", by("lines")), Item::Cmd("Break Text into Paragraphs", "addon.cleanup.breakText", by("paragraphs")), Item::Cmd("Break Text into Words", "addon.cleanup.breakText", by("words")), diff --git a/crates/ui-egui/src/addons/cleanup/tests.rs b/crates/ui-egui/src/addons/cleanup/tests.rs index edf7159241..f6b3f820ef 100644 --- a/crates/ui-egui/src/addons/cleanup/tests.rs +++ b/crates/ui-egui/src/addons/cleanup/tests.rs @@ -95,6 +95,7 @@ fn the_plugins_submenu_runs_the_text_tools() { let cleanup = ["Object", "Plug-ins", "Artwork Cleanup"]; for (label, id) in [ ("Combine Point Text", "addon.cleanup.combineText"), + ("Join Point Text", "addon.cleanup.joinText"), ("Break Text into Lines", "addon.cleanup.breakText"), ("Break Text into Paragraphs", "addon.cleanup.breakText"), ("Break Text into Glyphs", "addon.cleanup.breakText"), diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 706c4a5f65..2cf931a8aa 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5800,6 +5800,7 @@ anchor Points: Точки: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Разделяне на текст Combine Point Text Обединяване на точков текст + Join Point Text Съединяване на точков текст Remove Breaks Премахване на прекъсвания Split Text at Cursor Разделяне на текст при курсора Set Alignment, Keep Position Задаване на подравняване със запазване на позицията @@ -5828,6 +5829,7 @@ breakText Glyphs Глифи @msg Select horizontal point or area type whose text fits Изберете хоризонтален точков текст или текст в зона, чийто текст се побира @msg Nothing to split at the cursor При курсора няма какво да се раздели @msg Select two or more one-line point type objects on one baseline to combine Изберете два или повече едноредови обекта с точков текст на една базова линия, за да ги обедините +@msg Select two or more one-line point type objects to join Изберете два или повече едноредови обекта с точков текст, за да ги съедините @msg No line breaks to remove Няма прекъсвания на редове за премахване @msg No paragraph breaks to remove Няма прекъсвания на абзаци за премахване @msg Too many breaks to remove at once Твърде много прекъсвания за премахване наведнъж diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 597eb81828..a9adf22ae1 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5901,6 +5901,7 @@ anchor Points: Punts: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Divideix el text Combine Point Text Combina el text de punt + Join Point Text Uneix el text de punt Remove Breaks Elimina els salts Split Text at Cursor Divideix el text al cursor Set Alignment, Keep Position Defineix l’alineació i manté la posició @@ -5929,6 +5930,7 @@ breakText Glyphs Glifs @msg Select horizontal point or area type whose text fits Seleccioneu text de punt o d’àrea horitzontal el text del qual hi càpiga @msg Nothing to split at the cursor No hi ha res a dividir al cursor @msg Select two or more one-line point type objects on one baseline to combine Seleccioneu dos o més objectes de text de punt d’una línia sobre una mateixa línia de base per combinar-los +@msg Select two or more one-line point type objects to join Seleccioneu dos o més objectes de text de punt d’una línia per unir-los @msg No line breaks to remove No hi ha salts de línia per eliminar @msg No paragraph breaks to remove No hi ha salts de paràgraf per eliminar @msg Too many breaks to remove at once Massa salts per eliminar-los alhora diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b1539f4d85..41d9b25f8f 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5910,6 +5910,7 @@ anchor Points: Body: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Rozdělit text Combine Point Text Sloučit bodový text + Join Point Text Spojit bodový text Remove Breaks Odstranit zalomení Split Text at Cursor Rozdělit text u kurzoru Set Alignment, Keep Position Nastavit zarovnání, zachovat polohu @@ -5938,6 +5939,7 @@ breakText Glyphs Glyfy @msg Select horizontal point or area type whose text fits Vyberte vodorovný bodový text nebo text v oblasti, jehož text se vejde @msg Nothing to split at the cursor U kurzoru není co rozdělit @msg Select two or more one-line point type objects on one baseline to combine Vyberte dva nebo více jednořádkových objektů bodového textu na jednom účaří, abyste je sloučili +@msg Select two or more one-line point type objects to join Vyberte dva nebo více jednořádkových objektů bodového textu, abyste je spojili @msg No line breaks to remove Žádná zalomení řádků k odstranění @msg No paragraph breaks to remove Žádná zalomení odstavců k odstranění @msg Too many breaks to remove at once Příliš mnoho zalomení k odstranění najednou diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index e1f760e1f0..1b6277fd59 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5815,6 +5815,7 @@ anchor Points: Punkter: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Opdel tekst Combine Point Text Kombiner punkttekst + Join Point Text Sammenføj punkttekst Remove Breaks Fjern skift Split Text at Cursor Opdel tekst ved markøren Set Alignment, Keep Position Angiv justering, bevar placering @@ -5843,6 +5844,7 @@ breakText Glyphs Glyffer @msg Select horizontal point or area type whose text fits Vælg vandret punkt- eller områdetekst, hvis tekst kan være der @msg Nothing to split at the cursor Intet at opdele ved markøren @msg Select two or more one-line point type objects on one baseline to combine Vælg to eller flere punkttekstobjekter på én linje på samme grundlinje for at kombinere dem +@msg Select two or more one-line point type objects to join Vælg to eller flere punkttekstobjekter på én linje for at sammenføje dem @msg No line breaks to remove Ingen linjeskift at fjerne @msg No paragraph breaks to remove Ingen afsnitsskift at fjerne @msg Too many breaks to remove at once For mange skift til at fjerne på én gang diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index bcfc78c073..405462042d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5495,6 +5495,7 @@ anchor Points: Punkte: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Text aufteilen Combine Point Text Punkttext zusammenfügen + Join Point Text Punkttext verbinden Remove Breaks Umbrüche entfernen Split Text at Cursor Text an der Einfügemarke teilen Set Alignment, Keep Position Ausrichtung festlegen, Position beibehalten @@ -5523,6 +5524,7 @@ breakText Glyphs Glyphen @msg Select horizontal point or area type whose text fits Wählen Sie horizontalen Punkt- oder Flächentext aus, dessen Text hineinpasst @msg Nothing to split at the cursor An der Einfügemarke gibt es nichts zu teilen @msg Select two or more one-line point type objects on one baseline to combine Wählen Sie zwei oder mehr einzeilige Punkttextobjekte auf einer Grundlinie aus, um sie zusammenzufügen +@msg Select two or more one-line point type objects to join Wählen Sie zwei oder mehr einzeilige Punkttextobjekte aus, um sie zu verbinden @msg No line breaks to remove Keine Zeilenumbrüche zu entfernen @msg No paragraph breaks to remove Keine Absatzumbrüche zu entfernen @msg Too many breaks to remove at once Zu viele Umbrüche, um sie auf einmal zu entfernen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 8305782fa4..5147b4fd94 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5862,6 +5862,7 @@ anchor Points: Σημεία: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Διαίρεση κειμένου Combine Point Text Συνδυασμός κειμένου σημείου + Join Point Text Ένωση κειμένου σημείου Remove Breaks Αφαίρεση αλλαγών Split Text at Cursor Διαίρεση κειμένου στον δρομέα Set Alignment, Keep Position Ορισμός στοίχισης με διατήρηση θέσης @@ -5890,6 +5891,7 @@ breakText Glyphs Γλύφοι @msg Select horizontal point or area type whose text fits Επιλέξτε οριζόντιο κείμενο σημείου ή περιοχής του οποίου το κείμενο χωράει @msg Nothing to split at the cursor Δεν υπάρχει τίποτα για διαίρεση στον δρομέα @msg Select two or more one-line point type objects on one baseline to combine Επιλέξτε δύο ή περισσότερα μονογραμμικά αντικείμενα κειμένου σημείου στην ίδια γραμμή βάσης για να τα συνδυάσετε +@msg Select two or more one-line point type objects to join Επιλέξτε δύο ή περισσότερα μονογραμμικά αντικείμενα κειμένου σημείου για να τα ενώσετε @msg No line breaks to remove Δεν υπάρχουν αλλαγές γραμμής για αφαίρεση @msg No paragraph breaks to remove Δεν υπάρχουν αλλαγές παραγράφου για αφαίρεση @msg Too many breaks to remove at once Πάρα πολλές αλλαγές για αφαίρεση ταυτόχρονα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index cd071b0ae1..bbd74c412b 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5853,6 +5853,7 @@ anchor Points: Puntos: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Dividir texto Combine Point Text Combinar texto de punto + Join Point Text Unir texto de punto Remove Breaks Quitar saltos Split Text at Cursor Dividir texto en el cursor Set Alignment, Keep Position Definir alineación manteniendo la posición @@ -5881,6 +5882,7 @@ breakText Glyphs Glifos @msg Select horizontal point or area type whose text fits Seleccione texto de punto o de área horizontal cuyo texto quepa @msg Nothing to split at the cursor No hay nada que dividir en el cursor @msg Select two or more one-line point type objects on one baseline to combine Seleccione dos o más objetos de texto de punto de una línea sobre la misma línea base para combinarlos +@msg Select two or more one-line point type objects to join Seleccione dos o más objetos de texto de punto de una línea para unirlos @msg No line breaks to remove No hay saltos de línea que quitar @msg No paragraph breaks to remove No hay saltos de párrafo que quitar @msg Too many breaks to remove at once Demasiados saltos para quitarlos a la vez diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1d34418d98..27c96b5301 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5941,6 +5941,7 @@ anchor Points: Pisteet: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Jaa teksti Combine Point Text Yhdistä pisteteksti + Join Point Text Liitä pisteteksti Remove Breaks Poista vaihdot Split Text at Cursor Jaa teksti kohdistimen kohdalta Set Alignment, Keep Position Aseta tasaus, säilytä sijainti @@ -5969,6 +5970,7 @@ breakText Glyphs Merkit @msg Select horizontal point or area type whose text fits Valitse vaakasuora piste- tai alueteksti, jonka teksti mahtuu @msg Nothing to split at the cursor Kohdistimen kohdalla ei ole jaettavaa @msg Select two or more one-line point type objects on one baseline to combine Valitse kaksi tai useampia yksirivisiä pistetekstiobjekteja samalla perusviivalla yhdistääksesi ne +@msg Select two or more one-line point type objects to join Valitse kaksi tai useampia yksirivisiä pistetekstiobjekteja liittääksesi ne @msg No line breaks to remove Ei poistettavia rivinvaihtoja @msg No paragraph breaks to remove Ei poistettavia kappaleenvaihtoja @msg Too many breaks to remove at once Liian monta vaihtoa poistettavaksi kerralla diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 5e1c40015e..bbcab564e8 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5909,6 +5909,7 @@ anchor Points: Points : # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Diviser le texte Combine Point Text Combiner le texte de point + Join Point Text Joindre le texte de point Remove Breaks Supprimer les sauts Split Text at Cursor Diviser le texte au curseur Set Alignment, Keep Position Définir l’alignement en conservant la position @@ -5937,6 +5938,7 @@ breakText Glyphs Glyphes @msg Select horizontal point or area type whose text fits Sélectionnez du texte de point ou captif horizontal dont le texte tient dans son cadre @msg Nothing to split at the cursor Rien à diviser au curseur @msg Select two or more one-line point type objects on one baseline to combine Sélectionnez au moins deux objets texte de point d’une ligne sur une même ligne de base pour les combiner +@msg Select two or more one-line point type objects to join Sélectionnez au moins deux objets texte de point d’une ligne pour les joindre @msg No line breaks to remove Aucun saut de ligne à supprimer @msg No paragraph breaks to remove Aucun saut de paragraphe à supprimer @msg Too many breaks to remove at once Trop de sauts à supprimer en une fois diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index cc72129c0a..a17b4724fb 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5897,6 +5897,7 @@ anchor Points: Pontok: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Szöveg felosztása Combine Point Text Pontszöveg egyesítése + Join Point Text Pontszöveg összekapcsolása Remove Breaks Törések eltávolítása Split Text at Cursor Szöveg felosztása a kurzornál Set Alignment, Keep Position Igazítás beállítása, helyzet megtartása @@ -5925,6 +5926,7 @@ breakText Glyphs Glifák @msg Select horizontal point or area type whose text fits Jelöljön ki vízszintes pont- vagy területszöveget, amelynek szövege elfér @msg Nothing to split at the cursor A kurzornál nincs mit felosztani @msg Select two or more one-line point type objects on one baseline to combine Az egyesítéshez jelöljön ki legalább két egysoros pontszöveg-objektumot egy alapvonalon +@msg Select two or more one-line point type objects to join Az összekapcsoláshoz jelöljön ki legalább két egysoros pontszöveg-objektumot @msg No line breaks to remove Nincs eltávolítandó sortörés @msg No paragraph breaks to remove Nincs eltávolítandó bekezdéstörés @msg Too many breaks to remove at once Túl sok törés az egyszerre történő eltávolításhoz diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 34ca64d532..85f09a6a6d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5815,6 +5815,7 @@ anchor Points: Titik: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Pisahkan teks Combine Point Text Gabungkan teks titik + Join Point Text Satukan teks titik Remove Breaks Hapus pemisah Split Text at Cursor Pisahkan teks di kursor Set Alignment, Keep Position Atur perataan, pertahankan posisi @@ -5843,6 +5844,7 @@ breakText Glyphs Glif @msg Select horizontal point or area type whose text fits Pilih teks titik atau teks area horizontal yang teksnya muat @msg Nothing to split at the cursor Tidak ada yang dapat dipisahkan di kursor @msg Select two or more one-line point type objects on one baseline to combine Pilih dua atau lebih objek teks titik satu baris pada satu garis dasar untuk menggabungkannya +@msg Select two or more one-line point type objects to join Pilih dua atau lebih objek teks titik satu baris untuk menyatukannya @msg No line breaks to remove Tidak ada putus baris untuk dihapus @msg No paragraph breaks to remove Tidak ada putus paragraf untuk dihapus @msg Too many breaks to remove at once Terlalu banyak pemisah untuk dihapus sekaligus diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 7eabb61750..8be70bb1ff 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5529,6 +5529,7 @@ anchor Points: Punti: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Dividi testo Combine Point Text Combina testo con punto + Join Point Text Unisci testo con punto Remove Breaks Rimuovi interruzioni Split Text at Cursor Dividi testo al cursore Set Alignment, Keep Position Imposta allineamento mantenendo la posizione @@ -5557,6 +5558,7 @@ breakText Glyphs Glifi @msg Select horizontal point or area type whose text fits Seleziona testo con punto o in area orizzontale il cui testo ci sta @msg Nothing to split at the cursor Niente da dividere al cursore @msg Select two or more one-line point type objects on one baseline to combine Seleziona due o più oggetti di testo con punto su una riga sulla stessa linea di base per combinarli +@msg Select two or more one-line point type objects to join Seleziona due o più oggetti di testo con punto su una riga per unirli @msg No line breaks to remove Nessuna interruzione di riga da rimuovere @msg No paragraph breaks to remove Nessuna interruzione di paragrafo da rimuovere @msg Too many breaks to remove at once Troppe interruzioni da rimuovere in una volta diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index b08889efda..c7acb2adf3 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5595,6 +5595,7 @@ anchor Points: ポイント: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text テキストを分割 Combine Point Text ポイント文字を結合 + Join Point Text ポイント文字を連結 Remove Breaks 改行を削除 Split Text at Cursor カーソル位置でテキストを分割 Set Alignment, Keep Position 位置を保って行揃えを設定 @@ -5623,6 +5624,7 @@ breakText Glyphs 字形 @msg Select horizontal point or area type whose text fits テキストが収まっている横組みのポイント文字またはエリア内文字を選択してください @msg Nothing to split at the cursor カーソル位置で分割するものがありません @msg Select two or more one-line point type objects on one baseline to combine 結合するには、同じベースライン上にある 1 行のポイント文字オブジェクトを 2 つ以上選択してください +@msg Select two or more one-line point type objects to join 連結するには、1 行のポイント文字オブジェクトを 2 つ以上選択してください @msg No line breaks to remove 削除する強制改行がありません @msg No paragraph breaks to remove 削除する段落の区切りがありません @msg Too many breaks to remove at once 一度に削除する改行が多すぎます diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 208ff506be..903d741c74 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5900,6 +5900,7 @@ anchor Points: წერტილები: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text ტექსტის დაყოფა Combine Point Text წერტილის ტექსტის გაერთიანება + Join Point Text წერტილის ტექსტის შეერთება Remove Breaks წყვეტების წაშლა Split Text at Cursor ტექსტის დაყოფა კურსორთან Set Alignment, Keep Position სწორების დაყენება მდებარეობის შენარჩუნებით @@ -5928,6 +5929,7 @@ breakText Glyphs გლიფები @msg Select horizontal point or area type whose text fits აირჩიეთ ჰორიზონტალური წერტილის ან არის ტექსტი, რომლის ტექსტიც ეტევა @msg Nothing to split at the cursor კურსორთან დასაყოფი არაფერია @msg Select two or more one-line point type objects on one baseline to combine გასაერთიანებლად აირჩიეთ ერთ საბაზისო ხაზზე მდებარე ორი ან მეტი ერთსტრიქონიანი წერტილის ტექსტის ობიექტი +@msg Select two or more one-line point type objects to join შესაერთებლად აირჩიეთ ორი ან მეტი ერთსტრიქონიანი წერტილის ტექსტის ობიექტი @msg No line breaks to remove წასაშლელი სტრიქონის წყვეტები არ არის @msg No paragraph breaks to remove წასაშლელი აბზაცის წყვეტები არ არის @msg Too many breaks to remove at once ერთდროულად წასაშლელად ძალიან ბევრი წყვეტაა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 6be4d08703..732af24f62 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5492,6 +5492,7 @@ anchor Points: 포인트: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text 텍스트 나누기 Combine Point Text 포인트 문자 결합 + Join Point Text 포인트 문자 연결 Remove Breaks 나누기 제거 Split Text at Cursor 커서 위치에서 텍스트 나누기 Set Alignment, Keep Position 위치를 유지하며 정렬 설정 @@ -5520,6 +5521,7 @@ breakText Glyphs 글리프 @msg Select horizontal point or area type whose text fits 텍스트가 모두 들어가는 가로 포인트 문자 또는 영역 문자를 선택하십시오 @msg Nothing to split at the cursor 커서 위치에서 나눌 내용이 없습니다 @msg Select two or more one-line point type objects on one baseline to combine 결합하려면 같은 기준선에 있는 한 줄짜리 포인트 문자 오브젝트를 두 개 이상 선택하십시오 +@msg Select two or more one-line point type objects to join 연결하려면 한 줄짜리 포인트 문자 오브젝트를 두 개 이상 선택하십시오 @msg No line breaks to remove 제거할 강제 줄 바꿈이 없습니다 @msg No paragraph breaks to remove 제거할 단락 나누기가 없습니다 @msg Too many breaks to remove at once 한 번에 제거할 나누기가 너무 많습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d7a608c311..effdca022d 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5859,6 +5859,7 @@ anchor Points: Punten: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Tekst splitsen Combine Point Text Punttekst combineren + Join Point Text Punttekst samenvoegen Remove Breaks Einden verwijderen Split Text at Cursor Tekst splitsen bij cursor Set Alignment, Keep Position Uitlijning instellen, positie behouden @@ -5887,6 +5888,7 @@ breakText Glyphs Glyphs @msg Select horizontal point or area type whose text fits Selecteer horizontale punt- of vlaktekst waarvan de tekst past @msg Nothing to split at the cursor Niets te splitsen bij de cursor @msg Select two or more one-line point type objects on one baseline to combine Selecteer twee of meer punttekstobjecten van één regel op één basislijn om ze te combineren +@msg Select two or more one-line point type objects to join Selecteer twee of meer punttekstobjecten van één regel om ze samen te voegen @msg No line breaks to remove Geen regeleinden om te verwijderen @msg No paragraph breaks to remove Geen alinea-einden om te verwijderen @msg Too many breaks to remove at once Te veel einden om in één keer te verwijderen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 63dd77d7d6..6be694f622 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5765,6 +5765,7 @@ anchor Points: Punkty: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Podziel tekst Combine Point Text Połącz tekst punktowy + Join Point Text Złącz tekst punktowy Remove Breaks Usuń podziały Split Text at Cursor Podziel tekst w miejscu kursora Set Alignment, Keep Position Ustaw wyrównanie, zachowaj położenie @@ -5793,6 +5794,7 @@ breakText Glyphs Glify @msg Select horizontal point or area type whose text fits Zaznacz poziomy tekst punktowy lub akapitowy, którego tekst się mieści @msg Nothing to split at the cursor Nie ma nic do podzielenia w miejscu kursora @msg Select two or more one-line point type objects on one baseline to combine Zaznacz co najmniej dwa jednowierszowe obiekty tekstu punktowego na jednej linii bazowej, aby je połączyć +@msg Select two or more one-line point type objects to join Zaznacz co najmniej dwa jednowierszowe obiekty tekstu punktowego, aby je złączyć @msg No line breaks to remove Brak podziałów wiersza do usunięcia @msg No paragraph breaks to remove Brak podziałów akapitu do usunięcia @msg Too many breaks to remove at once Zbyt wiele podziałów do usunięcia naraz diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 94508e9659..5fe9922eda 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5828,6 +5828,7 @@ anchor Points: Pontos: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Dividir Texto Combine Point Text Combinar Texto de Ponto + Join Point Text Unir Texto de Ponto Remove Breaks Remover Quebras Split Text at Cursor Dividir Texto no Cursor Set Alignment, Keep Position Definir Alinhamento, Manter Posição @@ -5856,6 +5857,7 @@ breakText Glyphs Glifos @msg Select horizontal point or area type whose text fits Selecione texto de ponto ou de área horizontal cujo texto caiba @msg Nothing to split at the cursor Nada a dividir no cursor @msg Select two or more one-line point type objects on one baseline to combine Selecione dois ou mais objetos de texto de ponto de uma linha na mesma linha de base para combiná-los +@msg Select two or more one-line point type objects to join Selecione dois ou mais objetos de texto de ponto de uma linha para uni-los @msg No line breaks to remove Nenhuma quebra de linha a remover @msg No paragraph breaks to remove Nenhuma quebra de parágrafo a remover @msg Too many breaks to remove at once Quebras demais para remover de uma vez diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 37e6eb061e..bd4faa713d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5888,6 +5888,7 @@ anchor Points: Точки: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Разбить текст Combine Point Text Объединить текст из точки + Join Point Text Соединить текст из точки Remove Breaks Удалить разрывы Split Text at Cursor Разбить текст у курсора Set Alignment, Keep Position Задать выравнивание, сохранив положение @@ -5916,6 +5917,7 @@ breakText Glyphs Глифы @msg Select horizontal point or area type whose text fits Выделите горизонтальный текст из точки или в области, текст которого помещается @msg Nothing to split at the cursor У курсора нечего разбивать @msg Select two or more one-line point type objects on one baseline to combine Выделите два или более однострочных объекта текста из точки на одной базовой линии, чтобы объединить их +@msg Select two or more one-line point type objects to join Выделите два или более однострочных объекта текста из точки, чтобы соединить их @msg No line breaks to remove Нет разрывов строк для удаления @msg No paragraph breaks to remove Нет разрывов абзацев для удаления @msg Too many breaks to remove at once Слишком много разрывов для удаления за один раз diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index fbed797583..273720935b 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5963,6 +5963,7 @@ shape Open Öppen # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Dela upp text Combine Point Text Kombinera punkttext + Join Point Text Sammanfoga punkttext Remove Breaks Ta bort brytningar Split Text at Cursor Dela text vid markören Set Alignment, Keep Position Ställ in justering, behåll position @@ -5991,6 +5992,7 @@ breakText Glyphs Glyfer @msg Select horizontal point or area type whose text fits Markera vågrät punkt- eller områdestext vars text får plats @msg Nothing to split at the cursor Inget att dela vid markören @msg Select two or more one-line point type objects on one baseline to combine Markera två eller fler enradiga punkttextobjekt på samma baslinje för att kombinera dem +@msg Select two or more one-line point type objects to join Markera två eller fler enradiga punkttextobjekt för att sammanfoga dem @msg No line breaks to remove Inga radbrytningar att ta bort @msg No paragraph breaks to remove Inga styckebrytningar att ta bort @msg Too many breaks to remove at once För många brytningar att ta bort på en gång diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index aabe5c6452..180f3448da 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5868,6 +5868,7 @@ anchor Points: Noktalar: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Metni Böl Combine Point Text Nokta Metnini Birleştir + Join Point Text Nokta Metnini Bağla Remove Breaks Kesmeleri Kaldır Split Text at Cursor Metni İmleçte Böl Set Alignment, Keep Position Hizalamayı Ayarla, Konumu Koru @@ -5896,6 +5897,7 @@ breakText Glyphs Glifler @msg Select horizontal point or area type whose text fits Metni sığan yatay nokta veya alan metni seçin @msg Nothing to split at the cursor İmleçte bölünecek bir şey yok @msg Select two or more one-line point type objects on one baseline to combine Birleştirmek için aynı taban çizgisinde iki veya daha fazla tek satırlı nokta metni nesnesi seçin +@msg Select two or more one-line point type objects to join Bağlamak için iki veya daha fazla tek satırlı nokta metni nesnesi seçin @msg No line breaks to remove Kaldırılacak satır sonu yok @msg No paragraph breaks to remove Kaldırılacak paragraf sonu yok @msg Too many breaks to remove at once Bir kerede kaldırılacak çok fazla kesme var diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index b3553b0445..4d267593f6 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5509,6 +5509,7 @@ anchor Points: Точки: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Розбити текст Combine Point Text Об’єднати текст із точки + Join Point Text З’єднати текст із точки Remove Breaks Видалити розриви Split Text at Cursor Розбити текст біля курсора Set Alignment, Keep Position Задати вирівнювання, зберігши положення @@ -5537,6 +5538,7 @@ breakText Glyphs Гліфи @msg Select horizontal point or area type whose text fits Виділіть горизонтальний текст із точки або в області, текст якого вміщується @msg Nothing to split at the cursor Біля курсора нічого розбивати @msg Select two or more one-line point type objects on one baseline to combine Виділіть два або більше однорядкових об’єктів тексту з точки на одній базовій лінії, щоб об’єднати їх +@msg Select two or more one-line point type objects to join Виділіть два або більше однорядкових об’єктів тексту з точки, щоб з’єднати їх @msg No line breaks to remove Немає розривів рядків для видалення @msg No paragraph breaks to remove Немає розривів абзаців для видалення @msg Too many breaks to remove at once Забагато розривів, щоб видалити їх за раз diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4bb1fd1226..67169df4de 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5511,6 +5511,7 @@ anchor Points: Điểm: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text Tách văn bản Combine Point Text Kết hợp chữ điểm + Join Point Text Nối chữ điểm Remove Breaks Xóa ngắt Split Text at Cursor Tách văn bản tại con trỏ Set Alignment, Keep Position Đặt căn lề, giữ vị trí @@ -5539,6 +5540,7 @@ breakText Glyphs Glyph @msg Select horizontal point or area type whose text fits Chọn chữ điểm hoặc chữ vùng nằm ngang có văn bản vừa khung @msg Nothing to split at the cursor Không có gì để tách tại con trỏ @msg Select two or more one-line point type objects on one baseline to combine Chọn hai đối tượng chữ điểm một dòng trở lên trên cùng một đường cơ sở để kết hợp +@msg Select two or more one-line point type objects to join Chọn hai đối tượng chữ điểm một dòng trở lên để nối @msg No line breaks to remove Không có xuống dòng nào để xóa @msg No paragraph breaks to remove Không có ngắt đoạn nào để xóa @msg Too many breaks to remove at once Quá nhiều ngắt để xóa cùng lúc diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index bd495d05d6..6da63132e7 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5752,6 +5752,7 @@ anchor Points: 点: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text 拆分文本 Combine Point Text 合并点文字 + Join Point Text 连接点文字 Remove Breaks 删除换行 Split Text at Cursor 在光标处拆分文本 Set Alignment, Keep Position 设置对齐并保持位置 @@ -5780,6 +5781,7 @@ breakText Glyphs 字形 @msg Select horizontal point or area type whose text fits 请选择文本能完全容纳的横排点文字或区域文字 @msg Nothing to split at the cursor 光标处没有可拆分的内容 @msg Select two or more one-line point type objects on one baseline to combine 请选择同一基线上两个或更多单行点文字对象以合并 +@msg Select two or more one-line point type objects to join 请选择两个或更多单行点文字对象以连接 @msg No line breaks to remove 没有要删除的强制换行 @msg No paragraph breaks to remove 没有要删除的段落换行 @msg Too many breaks to remove at once 一次要删除的换行过多 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index f69992edd9..7e21abda50 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5548,6 +5548,7 @@ anchor Points: 點: # Artwork Cleanup add-on: its text tools (Object › Plug-ins › Artwork Cleanup and the panel's Text row) and their messages. Break Text 分割文字 Combine Point Text 合併點文字 + Join Point Text 連接點文字 Remove Breaks 移除換行 Split Text at Cursor 在游標處分割文字 Set Alignment, Keep Position 設定對齊並保持位置 @@ -5576,6 +5577,7 @@ breakText Glyphs 字符 @msg Select horizontal point or area type whose text fits 請選取文字能完整容納的橫排點文字或區域文字 @msg Nothing to split at the cursor 游標處沒有可分割的內容 @msg Select two or more one-line point type objects on one baseline to combine 請選取同一基線上兩個或更多單行點文字物件以合併 +@msg Select two or more one-line point type objects to join 請選取兩個或更多單行點文字物件以連接 @msg No line breaks to remove 沒有要移除的強制換行 @msg No paragraph breaks to remove 沒有要移除的段落換行 @msg Too many breaks to remove at once 一次要移除的換行過多 diff --git a/docs/mcp.md b/docs/mcp.md index 71ae5c02d0..a4756b6768 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5773,6 +5773,11 @@ glyph of its first character lands where it was drawn. more than 1 em, another look (paint, opacity, effects) or a piece that can't keep its place once joined (a ligature forming across the join) starts another object. Each object made takes the place and paint of its leftmost piece. The main use is type from a PDF that arrives one glyph per object. +- `addon.cleanup.joinText {ids?}` (Join Point Text) joins one-line horizontal point type into one point type object, + for text that arrives one line or fragment per object. Pieces turned and sheared like the top-left one are read as + lines (baselines within 0.4 em), top to bottom; a line's pieces join left to right with a space between them. Each + line becomes a left-aligned paragraph whose leading is the distance from the baseline above, so the lines stay where + they were. Character styles stay; the object takes the top-left piece's place and paint. Returns `{id, joined, lines}`. - `addon.cleanup.removeBreaks {kind, ids?}` removes the forced line breaks (`kind: "line"`) or paragraph returns (`"paragraph"`) in the characters selected with a Type tool, else in all the text of the selected type. A break between two words becomes a space; merged paragraphs take the first one's paragraph style. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8712f26f5f..8d930ef07e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G13: Direct Selection snaps a dragged line end square to straight paths and grazing curves; Path Precision Tools add-on: Shared Edge Merge Tool; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Artwork Cleanup add-on: Join Point Text, #4826; scores unchanged; previously: G13: Direct Selection snaps a dragged line end square to straight paths and grazing curves; Path Precision Tools add-on: Shared Edge Merge Tool; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -19,6 +19,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Artwork Cleanup add-on: Join Point Text (`addon.cleanup.joinText`) joins stacked one-line point type into one object, a paragraph per line keeping its baseline (#4826); scores unchanged. | | 2026-10-31 | minor | Width tool: a stroke with a width profile keeps its shape while the view zooms out; the minimum visible width goes to its widest point instead of scaling the whole profile (#995); scores unchanged. | | 2026-10-31 | minor | Patterns: Grid Repeat Options has a Preview checkbox, as the public grid options page lists (#2651); scores unchanged. | | 2026-10-31 | minor | Hardening: a gradient mesh read from a file is budgeted at about a million quads, so a huge one no longer exhausts memory when drawn or exported (#3592); scores unchanged. | @@ -1244,7 +1245,8 @@ alone; Fix All as one step; scopes; rejoin within the gap only) and `addons::cle The add-on's text tools (2026-10-31) work on the shared text layout: Break Text into lines, paragraphs, words or glyphs and Split Text at Cursor make point type pieces placed by the glyph of their first character, Combine Point Text merges -one-line point type back with every glyph where it was (tracking and spaces, checked against the layout), and Remove +one-line point type back with every glyph where it was (tracking and spaces, checked against the layout), Join Point +Text stacks one-line pieces into one object of paragraphs that keep their baselines (#4826), and Remove Line / Paragraph Breaks, Set Alignment, Keep Position, Reset Text Transform and Replace Missing Fonts. Tests: `cmd::addons::cleanup::text::tests` in `vectorcraft-engine` (glyphs kept in place, styles kept, one undo step, refusals), `addons::cleanup::tests` in `vectorcraft-ui-egui` (the submenu and the panel's Text row run them) and From b8e5f7088f06d2c131655adff59eded8c0736d18 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 21:08:59 +0700 Subject: [PATCH 085/260] Export for Screens: Export PDFs As Single file writes the artboards as one PDF's pages --- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/screens.rs | 35 +++++++++++++++++-- crates/engine/src/cmd/fileio/tests_screens.rs | 22 ++++++++++++ docs/mcp.md | 5 +-- 4 files changed, 58 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 0c38079dff..abd6857adc 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export for Screens", ["File", "Export"], None, - "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)", + "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)", has_doc, screens::export_for_screens ), diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index db934aeab7..c6ff1e8d6a 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -309,6 +309,9 @@ struct ScreenParams { /// Where files go: `none` (all in the folder), `rows` (the rows' sub-folders, as /// `subfolders`), `format` (a folder per extension), `item`, or `itemFormat`. folders: Option<String>, + /// Export PDFs As: `single` (the artboards a PDF row writes are the pages of one file) or + /// `multiple` (a file per artboard, the default). + pdfs: Option<String>, } /// How exported files are sorted into folders. @@ -389,6 +392,8 @@ struct Naming { /// The counter counts files rather than items. per_file: bool, folders: Folders, + /// Export PDFs As › Single file. + single_pdf: bool, } impl Naming { @@ -406,9 +411,14 @@ impl Naming { Some("file") => true, Some(c) => return Err(bad(C, format!("counterPer `{c}`: item or file"))), }; + let single_pdf = match o.pdfs.as_deref() { + None | Some("multiple") => false, + Some("single") => true, + Some(m) => return Err(bad(C, format!("pdfs `{m}`: single or multiple"))), + }; let filename = safe_name(&super::file_stem(title)).unwrap_or_else(|| "Untitled".into()); let pattern = o.name.clone().filter(|n| !n.trim().is_empty()); - Ok(Self { pattern, prefix, filename, when, counter_start: o.counter_start.unwrap_or(1), per_file, folders }) + Ok(Self { pattern, prefix, filename, when, counter_start: o.counter_start.unwrap_or(1), per_file, folders, single_pdf }) } /// The sub-folder (`None` for the export folder itself) and the file name of the file row `r` @@ -781,15 +791,34 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> // One step per item and row, the files a name collision skips included. let steps = (items.len() * rows.len()) as u64; let mut step = 0u64; + // Export PDFs As › Single file: with several artboards, a PDF row writes them all as the pages + // of one file, named as the document, with the first of them. + let artboards: Option<Vec<usize>> = items.iter().map(|i| i.artboard).collect::<Option<Vec<_>>>().filter(|a| naming.single_pdf && a.len() > 1); for (index, item) in items.iter().enumerate() { for r in &rows { vectorcraft_doc::cancel::check()?; vectorcraft_doc::cancel::progress(step, steps, &format!("Exporting file {} of {steps}", step + 1)); step += 1; - let (sub, file) = naming.file(item, index, files, r); + let single = artboards.as_ref().filter(|_| r.format.id == "pdf"); + if single.is_some() && index > 0 { + continue; + } + let document = single.map(|_| Item { + name: naming.filename.clone(), + stem: naming.filename.clone(), + doc: item.doc.clone(), + artboard: None, + region: item.region, + every_artboard: None, + }); + let (sub, file) = naming.file(document.as_ref().unwrap_or(item), index, files, r); let name = sub.map_or_else(|| file.clone(), |d| format!("{d}/{file}")); let Some(name) = out.claim(&name, &format!("{}|{}", item.stem, r.key), o.name.is_some()) else { continue }; - let bytes = if let (Some(all), "pdf") = (&item.every_artboard, r.format.id) { + let bytes = if let Some(boards) = single { + let mut options = r.options.clone(); + options["range"] = json!(boards.iter().map(|b| (b + 1).to_string()).collect::<Vec<_>>().join(", ")); + write(&item.doc, "pdf", &options)? + } else if let (Some(all), "pdf") = (&item.every_artboard, r.format.id) { // One page per artboard. let mut options = r.options.clone(); options["range"] = json!("all"); diff --git a/crates/engine/src/cmd/fileio/tests_screens.rs b/crates/engine/src/cmd/fileio/tests_screens.rs index 5da4bdf5e4..bb4e356259 100644 --- a/crates/engine/src/cmd/fileio/tests_screens.rs +++ b/crates/engine/src/cmd/fileio/tests_screens.rs @@ -811,3 +811,25 @@ fn the_document_remembers_its_export_settings() { assert!(!plain.contains("export_settings") && !plain.contains("exportSettings"), "not written when empty"); assert!(vectorcraft_format::load(plain.as_bytes()).unwrap().export_settings.is_empty()); } + +/// Export PDFs As › Single file: with several artboards, a PDF row writes them as the pages of one +/// file named after the document (raster rows still write a file per artboard); with one artboard +/// the PDF is that artboard's, as Multiple files writes it. +#[test] +fn single_file_pdfs_hold_every_chosen_artboard() { + let mut s = session(3); + let title = s.doc().unwrap().doc.title.clone(); + let rows = json!([{"format": "png", "scale": "1x"}, {"format": "pdf"}]); + let r = export(&mut s, json!({"range": "1-2", "pdfs": "single", "formats": rows})); + let got = files(&r); + let pdf: Vec<&(String, Vec<u8>)> = got.iter().filter(|(n, _)| n.ends_with(".pdf")).collect(); + assert_eq!(pdf.len(), 1, "{:?}", names(&r)); + assert_eq!(pdf[0].0, format!("{title}.pdf")); + assert_eq!(vectorcraft_pdf::import(&pdf[0].1).unwrap().artboards.len(), 2, "one page per artboard"); + assert_eq!(got.iter().filter(|(n, _)| n.ends_with(".png")).count(), 2); + let r = export(&mut s, json!({"range": "2", "pdfs": "single", "formats": [{"format": "pdf"}]})); + assert_eq!(names(&r), ["Artboard-2.pdf"]); + let r = export(&mut s, json!({"range": "1-2", "pdfs": "multiple", "formats": [{"format": "pdf"}]})); + assert_eq!(names(&r), ["Artboard-1.pdf", "Artboard-2.pdf"]); + assert!(s.execute("document.exportForScreens", &json!({"pdfs": "both", "formats": [{"format": "pdf"}]})).is_err()); +} diff --git a/docs/mcp.md b/docs/mcp.md index a4756b6768..c1568ae63c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3987,8 +3987,9 @@ each file deflated, or stored when deflating does not make it smaller. A row is `{format, scale?}` where `scale` is a factor (`2`, `"2x"`), a pixel width (`"100w"` or `width: 100`), a height (`"100h"`) or a resolution (`"72ppi"`); raster rows name their files `@2x`, `@100w`… unless `suffix` says otherwise. `fullDocument` writes one file per row instead (a PDF of every artboard, other formats the bounds of all -art), `includeBleed` grows each artboard by the document's bleed, `subfolders` puts each row's files in a sub-folder -(its size or format, or its own `folder`), `preset: "mobile"` or `"density"` (Android-style ldpi…xxxhdpi +art), `includeBleed` grows each artboard by the document's bleed, `pdfs: "single"` (Export PDFs As › Single file) +writes the artboards a PDF row exports as the pages of one PDF named after the document, `subfolders` puts each +row's files in a sub-folder (its size or format, or its own `folder`; `folders: "format"` sorts by format instead), `preset: "mobile"` or `"density"` (Android-style ldpi…xxxhdpi sub-folders) replaces the rows, and `settings: {png: {…}, jpg: {…}, svg: {…}, pdf: {preset}}` gives every row of a format its options. On every platform, `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters from a prefix, a suffix, a name pattern or an item's name become `-` in file and folder names, a folder name ends without From 7a2acbc178602956b48d2799473900ac6d623be1 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 21:16:28 +0700 Subject: [PATCH 086/260] Export for Screens: the dialog is laid out as Illustrator's --- .../ui-egui/src/dialogs/export_for_screens.rs | 740 +++++++++--------- .../src/dialogs/tests_accessibility.rs | 6 +- .../src/dialogs/tests_screen_assets.rs | 11 +- crates/ui-egui/src/dialogs/tests_screens.rs | 257 +++--- crates/ui-egui/src/i18n/bg.tsv | 8 + crates/ui-egui/src/i18n/bs.tsv | 8 + crates/ui-egui/src/i18n/ca.tsv | 8 + crates/ui-egui/src/i18n/cs.tsv | 8 + crates/ui-egui/src/i18n/da.tsv | 8 + crates/ui-egui/src/i18n/de.tsv | 8 + crates/ui-egui/src/i18n/el.tsv | 8 + crates/ui-egui/src/i18n/es.tsv | 8 + crates/ui-egui/src/i18n/fi.tsv | 8 + crates/ui-egui/src/i18n/fr.tsv | 8 + crates/ui-egui/src/i18n/hu.tsv | 8 + crates/ui-egui/src/i18n/id.tsv | 8 + crates/ui-egui/src/i18n/it.tsv | 8 + crates/ui-egui/src/i18n/ja.tsv | 8 + crates/ui-egui/src/i18n/ka.tsv | 8 + crates/ui-egui/src/i18n/ko.tsv | 8 + crates/ui-egui/src/i18n/nl.tsv | 8 + crates/ui-egui/src/i18n/pl.tsv | 8 + crates/ui-egui/src/i18n/pt-br.tsv | 8 + crates/ui-egui/src/i18n/ru.tsv | 8 + crates/ui-egui/src/i18n/sv.tsv | 8 + crates/ui-egui/src/i18n/tr.tsv | 8 + crates/ui-egui/src/i18n/uk.tsv | 8 + crates/ui-egui/src/i18n/vi.tsv | 8 + crates/ui-egui/src/i18n/zh-hans.tsv | 8 + crates/ui-egui/src/i18n/zh-hant.tsv | 8 + crates/ui-egui/src/io/export.rs | 2 + crates/ui-egui/src/panels/asset_export.rs | 2 +- .../ui-egui/src/panels/tests_asset_export.rs | 2 +- 33 files changed, 673 insertions(+), 555 deletions(-) diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 7bc4ca8b7a..fdb48a7536 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -1,34 +1,31 @@ -//! File → Export → Export for Screens: the Artboards tab (All, a range or Full Document, Include -//! Bleed, thumbnails with checkboxes) and the Assets tab (the Asset Export panel's assets, with -//! checkboxes), the destination (folder picker, Open Location after Export, Create Sub-folders; -//! the web downloads instead), the format rows (scale as `2x`, `100w`, `100h` or `72ppi`, suffix, -//! format), the presets, Format Settings (the gear) and the prefix. It opens on the settings the -//! document last exported with, except that while the Artboard tool is in use the artboards it has -//! selected are the ones chosen; the format rows are the Asset Export panel's too ([`formats`]). +//! File → Export → Export for Screens, laid out as Illustrator's: on the left the Artboards and +//! Assets tabs (thumbnails with checkboxes, in a grid or a list), Clear Selection and the prefix; +//! on the right Select (All, a range or Full Document, Include Bleed), the destination (folder +//! picker, Open Location after Export, Create Sub-folders by scale or by format; the web downloads +//! instead), Export PDFs As (one file of every artboard or a file each), and the format rows (scale +//! as `2x`, `100w`, `100h` or `72ppi`, suffix, format) with the iOS and Android rows, the format +//! presets (the ☰ menu) and Format Settings (the gear); below, how many items are selected and +//! how many files the export writes. It opens on the settings the document last exported with, +//! except that while the Artboard tool is in use the artboards it has selected are the ones chosen; +//! the format rows are the Asset Export panel's too ([`formats`]). On the desktop with Background +//! Export on, the files are encoded and written on the background thread +//! ([`crate::background`]) after the dialog closes. //! -//! The Layers tab exports each checked layer's art alone, and the Selection tab the selected art as -//! one file or a file per object. A file name pattern (`name`: `<filename>`, `<name>`, `####`, -//! `YYYYMMDD`…, see `document.exportForScreens`) names every file alike, with a live example, and -//! the files go into one folder, or a folder per row, format, item, or item and format -//! (`folders`). Export presets (built-in and saved) set the formats, naming and folders at once. -//! On the desktop with Background Export on, the files are encoded and written on the background -//! thread ([`crate::background`]) after the dialog closes. +//! `document.exportForScreens` does more than the dialog shows (layers, the selection, file name +//! patterns, a folder per item): those are for scripts and MCP. //! -//! Fields (`ui.dialog.set`): `tab` (artboards|assets|layers|selection), `select` (all|range|full), `range`, +//! Fields (`ui.dialog.set`): `tab` (artboards|assets), `select` (all|range|full), `range`, //! `boards` ([bool] per artboard), `assets` ([asset id] checked on the Assets tab), `includeBleed`, -//! `folder`, `openLocation`, `subfolders`, `prefix`, `preset` (""|mobile|density: where the rows -//! came from), `formats` (rows of `document.exportForScreens`, `scale` as text), `settings` -//! ({png|png8|jpg|webp|gif|tiff|svg|pdf: {…}}), `layers` ([layer id] checked on the Layers tab), -//! `selectionMode` (one|each), `name` (the pattern), `counterStart`, `folders` -//! (none|rows|format|item|itemFormat), `exportPreset` (the preset applied last, "" for none); +//! `folder`, `openLocation`, `subfolders`, `subfolderBy` (scale|format), `pdfs` (single|multiple), +//! `prefix`, `preset` (""|mobile|density: where the rows came from), `formats` (rows of +//! `document.exportForScreens`, `scale` as text), `settings` ({png|png8|jpg|webp|gif|tiff|svg|pdf: +//! {…}}), `view` (grid|list), `exportPreset` (the format preset applied last, "" for none); //! `__settings` names the format whose Format Settings show ("" when closed), `__savePreset` is the //! name being typed to save a preset (absent when not saving). use serde::Deserialize; use serde_json::{Map, Value, json}; -use vectorcraft_engine::cmd::fileio::{self, ArtboardPick, SCREEN_PRESETS, ScreenSize, pdf}; - -use vectorcraft_doc::{ExportAsset, NodeId}; +use vectorcraft_engine::cmd::fileio::{self, ArtboardPick, ScreenSize, pdf}; use super::{DialogSpec, form, png_options, svg_options}; use crate::state::Dialog; @@ -43,11 +40,9 @@ pub(super) const SPEC: DialogSpec = DialogSpec { ok_label: Some(|app| match (io::is_web(app), app.ui.dialog.as_ref().map(|d| d.str("tab")).as_deref()) { (true, _) => "Download", (false, Some("assets")) => "Export Asset", - (false, Some("layers")) => "Export Layer", - (false, Some("selection")) => "Export Selection", (false, _) => "Export Artboard", }), - min_width: 660.0, + min_width: 720.0, ..DialogSpec::FORM }; @@ -80,32 +75,13 @@ fn print_marks() -> Value { json!({"trim": true, "registration": true, "colorBars": true, "pageInfo": true}) } -/// Where the files go: (`folders` value, label). -const FOLDERS: [(&str, &str); 5] = [ - ("none", "All in One Folder"), - ("rows", "By Size or Row"), - ("format", "By Format"), - ("item", "By Artboard or Item"), - ("itemFormat", "By Item, Then Format"), -]; -const FOLDER_LABELS: [&str; 5] = ["All in One Folder", "By Size or Row", "By Format", "By Artboard or Item", "By Item, Then Format"]; - -/// The tokens Insert adds to the file name pattern: (label, token). -const TOKENS: [(&str, &str); 8] = [ - ("Document Name", "<filename>"), - ("Artboard or Item Name", "<name>"), - ("Number (####)", "####"), - ("Date (YYYYMMDD)", "YYYYMMDD"), - ("Date (YYYY-MM-DD)", "YYYY-MM-DD"), - ("Time (hhmmss)", "<time>"), - ("Format", "<format>"), - ("Scale", "<scale>"), -]; -const TOKEN_LABELS: [&str; 8] = - ["Document Name", "Artboard or Item Name", "Number (####)", "Date (YYYYMMDD)", "Date (YYYY-MM-DD)", "Time (hhmmss)", "Format", "Scale"]; - /// The tabs: (`tab` value, label). -const TABS: [&str; 4] = ["artboards", "assets", "layers", "selection"]; +const TABS: [&str; 2] = ["artboards", "assets"]; + +/// The left pane's width and the height of its thumbnails' area; the right pane's width. +const LEFT_W: f32 = 300.0; +const PANE_H: f32 = 360.0; +const RIGHT_W: f32 = 370.0; /// The formats Format Settings has options for: (format, label). const SETTINGS: [(&str, &str); 8] = @@ -144,8 +120,9 @@ pub(crate) fn open_assets(app: &mut VectorcraftApp, checked: Option<&[u64]>) { } /// Open the dialog on the settings the active document last exported with (else one PNG row at -/// 1x, into the Desktop), every asset checked. While the Artboard tool is in use, the artboards it -/// has selected (the rows the Artboards panel highlights) are the ones chosen instead. +/// 1x, into the Desktop, with Create Sub-folders on), every asset checked. While the Artboard tool +/// is in use, the artboards it has selected (the rows the Artboards panel highlights) are the ones +/// chosen instead. pub fn open(app: &mut VectorcraftApp) { let (n, saved, assets) = app .session @@ -172,12 +149,14 @@ pub fn open(app: &mut VectorcraftApp) { settings.insert(id.into(), Value::Object(saved_options(app, &saved, id))); } let folder = get("folder").and_then(Value::as_str).filter(|f| !f.is_empty()).map(str::to_string).or_else(fileio::export_folder); - // Where files go: the saved choice, else a folder per row as Create Sub-folders did. - let folders = get("folders") - .and_then(Value::as_str) - .filter(|f| FOLDERS.iter().any(|(id, _)| id == f)) - .map_or_else(|| if flag("subfolders", preset.is_some()) { "rows" } else { "none" }.to_string(), str::to_string); - let layers: Vec<u64> = app.session.active().map(|st| st.doc.layers.iter().map(|l| l.id.0).collect()).unwrap_or_default(); + // Create Sub-folders is on until an export turns it off; a folder per format is the saved + // `folders: "format"`, any other sorting a folder per scale. + let folders = get("folders").and_then(Value::as_str); + let subfolders = match folders { + Some("none") => false, + Some(_) => true, + None => flag("subfolders", saved.is_empty() || preset.is_some()), + }; let fields = json!({ "tab": "artboards", "select": select, @@ -187,18 +166,16 @@ pub fn open(app: &mut VectorcraftApp) { "includeBleed": flag("includeBleed", false), "folder": folder.unwrap_or_default(), "openLocation": flag("openLocation", true), - "subfolders": flag("subfolders", preset.is_some()), + "subfolders": subfolders, + "subfolderBy": if folders == Some("format") { "format" } else { "scale" }, + "pdfs": if get("pdfs").and_then(Value::as_str) == Some("single") { "single" } else { "multiple" }, "prefix": get("prefix").and_then(Value::as_str).unwrap_or_default(), "preset": preset.unwrap_or_default(), "formats": rows, "settings": settings, + "view": "grid", "__settings": "", "__presets": pdf::presets(&app.session), - "layers": layers, - "selectionMode": get("selection").and_then(Value::as_str).filter(|m| *m == "each").unwrap_or("one"), - "name": get("name").and_then(Value::as_str).unwrap_or_default(), - "counterStart": get("counterStart").and_then(Value::as_u64).unwrap_or(1), - "folders": folders, "exportPreset": "", "__exportPresets": export_presets(app), }); @@ -281,24 +258,6 @@ pub(super) fn export_presets(app: &mut VectorcraftApp) -> Value { app.run("document.exportPresets.list", json!({})).ok().and_then(|r| r.get("presets").cloned()).unwrap_or_else(|| json!([])) } -/// The art of layer `id` (sublayers unfolded), back to front: what its file holds. -fn layer_art(doc: &vectorcraft_doc::Document, id: NodeId, out: &mut Vec<NodeId>) { - let Some(n) = doc.node(id) else { return }; - if n.is_layer() { - for c in n.children().into_iter().flatten() { - layer_art(doc, c.id, out); - } - } else { - out.push(id); - } -} - -/// The checked layers that are still in the document, in stacking order. -fn checked_layers(app: &VectorcraftApp, d: &Dialog) -> Vec<u64> { - let on: Vec<u64> = d.fields.get("layers").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default(); - app.session.active().map(|st| st.doc.layers.iter().map(|l| l.id.0).filter(|id| on.contains(id)).collect()).unwrap_or_default() -} - /// The `document.exportForScreens` params the dialog describes (the web: no folder, one ZIP for /// several files). fn params(app: &VectorcraftApp, d: &Dialog) -> Result<Value, String> { @@ -316,24 +275,24 @@ fn params(app: &VectorcraftApp, d: &Dialog) -> Result<Value, String> { Ok(Value::Object(p)) } -/// The counter's first value: the Start at field (a number, or text typed through `ui.dialog.set`). -fn counter_start(d: &Dialog) -> u64 { - d.fields.get("counterStart").and_then(|v| v.as_u64().or_else(|| v.as_str().and_then(|t| t.trim().parse().ok()))).unwrap_or(1) -} - /// The params of [`params`] without the destination (what is exported, at which sizes, and how the /// files are named and sorted), and how many files that is. fn settings_params(app: &VectorcraftApp, d: &Dialog) -> Result<(Map<String, Value>, usize), String> { + let (p, files, _) = selection_params(app, d)?; + Ok((p, files)) +} + +/// [`settings_params`] and how many artboards or assets are chosen. +fn selection_params(app: &VectorcraftApp, d: &Dialog) -> Result<(Map<String, Value>, usize, usize), String> { let n = app.session.active().map_or(0, |st| st.doc.artboards.len()); let rows = d.fields.get("formats").and_then(Value::as_array).cloned().unwrap_or_default(); if rows.is_empty() { return Err("add a format to export".into()); } let mut p = Map::new(); - // What each row writes a file of: the checked assets, layers, the selection, else the - // artboards. - let tab = d.str("tab"); - let pieces = if tab == "assets" { + // What each row writes a file of: the checked assets, else the artboards. + let artboards = d.str("tab") != "assets"; + let pieces = if !artboards { let checked = checked_assets(app, d); if checked.is_empty() { return Err("check an asset to export".into()); @@ -341,22 +300,6 @@ fn settings_params(app: &VectorcraftApp, d: &Dialog) -> Result<(Map<String, Valu let count = checked.len(); p.insert("assets".into(), json!(checked)); count - } else if tab == "layers" { - let checked = checked_layers(app, d); - if checked.is_empty() { - return Err("check a layer to export".into()); - } - let count = checked.len(); - p.insert("layers".into(), json!(checked)); - count - } else if tab == "selection" { - let selected = app.session.active().map_or(0, |st| st.selection.objects.len()); - if selected == 0 { - return Err("select the art to export first".into()); - } - let each = d.str("selectionMode") == "each"; - p.insert("selection".into(), json!(if each { "each" } else { "one" })); - if each { selected } else { 1 } } else { match d.str("select").as_str() { "full" => { @@ -367,34 +310,33 @@ fn settings_params(app: &VectorcraftApp, d: &Dialog) -> Result<(Map<String, Valu let range = d.str("range"); // A bad range keeps the dialog open. let chosen = ArtboardPick { range: Some(range.clone()), ..Default::default() }.resolve(n)?.unwrap_or_default(); + if chosen.is_empty() { + return Err("check an artboard to export".into()); + } p.insert("range".into(), json!(range)); chosen.len() } _ => n, } }; - let files = pieces * rows.len(); + // Export PDFs As › Single file: every chosen artboard in one PDF per PDF row. + let single = artboards && pieces > 1 && d.str("select") != "full" && d.str("pdfs") == "single"; + let pdf_rows = rows.iter().filter(|r| r["format"].as_str().and_then(fileio::format).is_some_and(|f| f.id == "pdf")).count(); + let files = if single { (rows.len() - pdf_rows) * pieces + pdf_rows } else { rows.len() * pieces }; p.insert("includeBleed".into(), json!(d.bool("includeBleed"))); - let folders = d.str("folders"); - let folders = match (FOLDERS.iter().any(|(id, _)| *id == folders), d.bool("subfolders")) { - // Create Sub-folders (as the Asset Export panel and older scripts set it) is a folder per - // row while Folders is still All in One Folder. - (true, true) if folders == "none" => "rows".to_string(), - (true, _) => folders, - (false, sub) => if sub { "rows" } else { "none" }.to_string(), + let folders = match (d.bool("subfolders"), d.str("subfolderBy").as_str()) { + (false, _) => "none", + (true, "format") => "format", + (true, _) => "rows", }; - // Create Sub-folders, as the Asset Export panel (which shares these settings) still names it. + // Create Sub-folders, as the Asset Export panel (which shares these settings) names it. p.insert("subfolders".into(), json!(folders == "rows")); p.insert("folders".into(), json!(folders)); + p.insert("pdfs".into(), json!(if single { "single" } else { "multiple" })); p.insert("prefix".into(), json!(d.str("prefix"))); - let name = d.str("name"); - if !name.trim().is_empty() { - p.insert("name".into(), json!(name.trim())); - } - p.insert("counterStart".into(), json!(counter_start(d))); p.insert("formats".into(), Value::Array(rows)); p.insert("settings".into(), d.fields.get("settings").cloned().unwrap_or(json!({}))); - Ok((p, files)) + Ok((p, files, pieces)) } /// Export; the dialog stays open when the export fails. @@ -410,130 +352,218 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let t = Tokens::get(ui.ctx()); let tab = TABS.iter().position(|k| *k == d.str("tab")).unwrap_or(0); - if let Some(i) = widgets::tab_bar(ui, &[tl!("Artboards"), tl!("Assets"), tl!("Layers"), tl!("Selection")], tab) { - d.fields.insert("tab".into(), json!(TABS.get(i).copied().unwrap_or("artboards"))); - } - ui.add_space(8.0); ui.horizontal_top(|ui| { ui.vertical(|ui| { - ui.set_width(270.0); - match tab { - 1 => assets(app, ui, d), - 2 => layers(app, ui, d), - 3 => selection(app, ui, d), - _ => artboards(app, ui, d), + ui.set_width(LEFT_W); + if let Some(i) = widgets::tab_bar(ui, &[tl!("Artboards"), tl!("Assets")], tab) { + d.fields.insert("tab".into(), json!(TABS.get(i).copied().unwrap_or("artboards"))); } + ui.add_space(6.0); + let list = d.str("view") == "list"; + let (pane, _) = ui.allocate_exact_size(egui::vec2(LEFT_W, PANE_H), egui::Sense::hover()); + ui.painter().rect_filled(pane, 2.0, t.panel_darker); + ui.painter().rect_stroke(pane, 2.0, egui::Stroke::new(1.0, t.divider), egui::StrokeKind::Inside); + let mut inner = ui.new_child(egui::UiBuilder::new().max_rect(pane.shrink(8.0)).layout(egui::Layout::top_down(egui::Align::Min))); + match tab { + 1 => assets(app, &mut inner, d, list), + _ => artboard_tiles(app, &mut inner, d, list), + } + ui.add_space(6.0); + ui.horizontal(|ui| { + for (view, icon, tip) in [("grid", "layout-grid", tl!("Grid View")), ("list", "dc-list-view", tl!("List View"))] { + if widgets::icon_button(ui, icon, tip, d.str("view") == view || (view == "grid" && !list && d.str("view") != "list"), 22.0) + .clicked() + { + d.fields.insert("view".into(), json!(view)); + } + } + ui.add_space(6.0); + if ui.small_button(tl!("Clear Selection")).clicked() { + clear_selection(app, d, tab); + } + widgets::dim_label(ui, tl!("Prefix:")); + form::text(ui, d, "prefix", (ui.available_width() - 4.0).max(60.0)); + }); }); - let (sep, _) = ui.allocate_exact_size(egui::vec2(17.0, 380.0), egui::Sense::hover()); + let (sep, _) = ui.allocate_exact_size(egui::vec2(17.0, PANE_H + 60.0), egui::Sense::hover()); ui.painter().line_segment([sep.center_top(), sep.center_bottom()], egui::Stroke::new(1.0, t.divider)); ui.vertical(|ui| { - ui.set_width(350.0); + ui.set_width(RIGHT_W); let shown = d.str("__settings"); if SETTINGS.iter().any(|(id, _)| *id == shown) { format_settings(ui, d, &shown); } else { - presets(app, ui, d); - ui.add_space(8.0); + if tab == 0 { + select_options(app, ui, d); + ui.add_space(8.0); + } destination(app, ui, d); + ui.add_space(6.0); + pdf_mode(ui, d, tab == 0); ui.add_space(10.0); - formats(ui, d); - ui.add_space(8.0); - naming(app, ui, d); + formats(ui, d, Some(&mut |ui: &mut egui::Ui, d: &mut Dialog| preset_menu(app, ui, d))); + save_preset_row(app, ui, d); } }); }); + ui.add_space(8.0); + let (picked, files) = counts(app, d); + let status = + crate::i18n::fmt(tl!("Selected: {n}, Total number of files to export: {m}"), &[("n", &picked.to_string()), ("m", &files.to_string())]); + widgets::dim_label(ui, &status); false } +/// How many artboards or assets are chosen and how many files the export writes (0 while the +/// settings choose nothing to export). +fn counts(app: &VectorcraftApp, d: &Dialog) -> (usize, usize) { + match selection_params(app, d) { + Ok((_, files, pieces)) => (pieces, files), + Err(_) => (if d.str("tab") == "assets" { checked_assets(app, d).len() } else { 0 }, 0), + } +} + +/// Clear Selection: no artboard (or, on the Assets tab, no asset) is checked. +fn clear_selection(app: &VectorcraftApp, d: &mut Dialog, tab: usize) { + if tab == 1 { + d.fields.insert("assets".into(), json!([])); + } else { + let n = app.session.active().map_or(0, |st| st.doc.artboards.len()); + d.fields.insert("boards".into(), json!(vec![false; n])); + set_select(d, "range"); + d.fields.insert("range".into(), json!("")); + } +} + fn set_select(d: &mut Dialog, select: &str) { d.fields.insert("select".into(), json!(select)); } -/// Select (All, Range, Full Document), Include Bleed, and the artboards' thumbnails and checkboxes. -fn artboards(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { +/// The checked artboards, one per artboard (all checked when the field is short). +fn boards(app: &VectorcraftApp, d: &Dialog) -> Vec<bool> { let n = app.session.active().map_or(0, |st| st.doc.artboards.len()); let mut boards: Vec<bool> = d.fields.get("boards").and_then(Value::as_array).map(|a| a.iter().map(|b| b.as_bool().unwrap_or(false)).collect()).unwrap_or_default(); boards.resize(n, true); - let before = boards.clone(); + boards +} + +/// Select: All or a Range (which checks the artboards it names), Include Bleed and Full Document. +fn select_options(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { + let n = app.session.active().map_or(0, |st| st.doc.artboards.len()); let select = d.str("select"); widgets::dim_label(ui, tl!("Select:")); ui.horizontal(|ui| { if widgets::radio(ui, tl!("All"), select == "all", true) { set_select(d, "all"); - boards.iter_mut().for_each(|b| *b = true); + d.fields.insert("boards".into(), json!(vec![true; n])); + d.fields.insert("range".into(), json!(range_text(&vec![true; n]))); } if widgets::radio(ui, tl!("Range:"), select == "range", true) { set_select(d, "range"); } ui.add_enabled_ui(select == "range", |ui| { - if form::text_named(ui, d, "range", tl!("Range:"), 90.0) + if form::text_named(ui, d, "range", tl!("Range:"), 150.0) && let Ok(Some(chosen)) = (ArtboardPick { range: Some(d.str("range")), ..Default::default() }).resolve(n) { - boards = (0..n).map(|i| chosen.contains(&i)).collect(); + d.fields.insert("boards".into(), json!((0..n).map(|i| chosen.contains(&i)).collect::<Vec<_>>())); } }); }); - if widgets::radio(ui, tl!("Full Document"), select == "full", true) { + form::check(ui, d, "includeBleed", tl!("Include Bleed")); + if widgets::radio(ui, tl!("Full Document"), d.str("select") == "full", true) { set_select(d, "full"); } - ui.add_space(4.0); - form::check(ui, d, "includeBleed", tl!("Include Bleed")); - ui.add_space(6.0); - let typed = boards != before; - let checked = boards.clone(); +} + +/// The artboards' thumbnails, each with its checkbox, number and name, in a grid or a list; +/// checking them picks them as the range (all of them: All). Dimmed with Full Document. +fn artboard_tiles(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, list: bool) { + let mut boards = boards(app, d); + let before = boards.clone(); + let names: Vec<String> = app.session.active().map(|s| s.doc.artboards.iter().map(|a| a.name.clone()).collect()).unwrap_or_default(); ui.add_enabled_ui(d.str("select") != "full", |ui| { - ui.horizontal(|ui| { - if ui.small_button(tl!("Select All")).clicked() { - boards.iter_mut().for_each(|b| *b = true); + tiles(ui, "efs-artboards", names.len(), list, |ui, i, r| { + match artboard_thumb(app, ui.ctx(), i) { + Some(tex) => { + let sz = tex.size_vec2(); + let s = (r.width() / sz.x).min(r.height() / sz.y).min(1.0); + let uv = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); + ui.painter().image(tex.id(), egui::Rect::from_center_size(r.center(), sz * s), uv, egui::Color32::WHITE); + } + None => { + ui.painter().rect_filled(r, 2.0, egui::Color32::WHITE); + } } - if ui.small_button(tl!("Clear")).clicked() { - boards.iter_mut().for_each(|b| *b = false); - } - }); - let names: Vec<String> = app.session.active().map(|s| s.doc.artboards.iter().map(|a| a.name.clone()).collect()).unwrap_or_default(); - egui::ScrollArea::vertical().max_height(250.0).show(ui, |ui| { - for (i, name) in names.iter().enumerate() { - ui.horizontal(|ui| { - let (r, _) = ui.allocate_exact_size(egui::vec2(46.0, 46.0), egui::Sense::hover()); - match artboard_thumb(app, ui.ctx(), i) { - Some(tex) => { - let sz = tex.size_vec2(); - let s = (46.0 / sz.x.max(sz.y)).min(1.0); - let uv = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); - ui.painter().image(tex.id(), egui::Rect::from_center_size(r.center(), sz * s), uv, egui::Color32::WHITE); - } - None => { - ui.painter().rect_filled(r, 2.0, egui::Color32::WHITE); - } - } - if let Some(b) = boards.get_mut(i) - && crate::widgets::check_name(ui, name, *b) - { - *b ^= true; - } - }); + let name = names.get(i).cloned().unwrap_or_default(); + (format!("{} {name}", i + 1), name, boards.get(i).copied().unwrap_or(false)) + }) + .into_iter() + .for_each(|i| { + if let Some(b) = boards.get_mut(i) { + *b ^= true; } }); }); - // Checking artboards picks them as the range (all of them: All); a typed range keeps its text. - if boards != checked { + if boards != before { set_select(d, if boards.iter().all(|b| *b) { "all" } else { "range" }); d.fields.insert("range".into(), json!(range_text(&boards))); - } - if typed || boards != checked { d.fields.insert("boards".into(), json!(boards)); } } +/// `count` thumbnails in a grid (or, with `list`, a list) that scrolls: `paint` draws thumbnail `i` +/// into its rect and gives its caption, its checkbox's name and whether it is checked → the +/// thumbnails whose checkbox (or picture) was clicked. +fn tiles( + ui: &mut egui::Ui, + id: &str, + count: usize, + list: bool, + mut paint: impl FnMut(&mut egui::Ui, usize, egui::Rect) -> (String, String, bool), +) -> Vec<usize> { + let t = Tokens::get(ui.ctx()); + let mut toggled = vec![]; + let side = if list { 40.0 } else { 84.0 }; + let width = ui.available_width(); + let columns = if list { 1 } else { ((width + 10.0) / (side + 10.0)).floor().max(1.0) as usize }; + egui::ScrollArea::vertical().id_salt(id).auto_shrink([false, false]).show(ui, |ui| { + for start in (0..count).step_by(columns) { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 10.0; + for i in start..(start + columns).min(count) { + let cell = if list { egui::vec2(width - 16.0, side) } else { egui::vec2(side, side + 18.0) }; + let (r, resp) = ui.allocate_exact_size(cell, egui::Sense::click()); + let pic = egui::Rect::from_min_size(r.min, egui::vec2(side, side)); + let (caption, name, checked) = paint(ui, i, pic.shrink(3.0)); + let stroke = if checked { egui::Stroke::new(2.0, t.accent) } else { egui::Stroke::new(1.0, t.divider) }; + ui.painter().rect_stroke(pic, 2.0, stroke, egui::StrokeKind::Inside); + let label_at = if list { egui::pos2(pic.right() + 8.0, pic.center().y) } else { egui::pos2(pic.left(), pic.bottom() + 9.0) }; + let galley = + ui.painter().layout(caption, egui::FontId::proportional(11.0), t.text, if list { cell.x - side - 12.0 } else { side }); + ui.painter().galley(egui::pos2(label_at.x, label_at.y - galley.size().y / 2.0), galley, t.text); + // The checkbox sits on the thumbnail's lower left corner, as Illustrator's. + let bx = egui::Rect::from_min_size(egui::pos2(pic.left() + 4.0, pic.bottom() - 18.0), egui::vec2(14.0, 14.0)); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(bx)); + if widgets::check_box(&mut child, &name, checked, true) || resp.clicked() { + toggled.push(i); + } + } + }); + ui.add_space(6.0); + } + }); + toggled +} + /// The checked assets that are still in the document, in panel order. fn checked_assets(app: &VectorcraftApp, d: &Dialog) -> Vec<u64> { let on: Vec<u64> = d.fields.get("assets").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default(); app.session.active().map(|st| st.doc.assets.iter().map(|a| a.id).filter(|id| on.contains(id)).collect()).unwrap_or_default() } -/// The Assets tab: each asset's thumbnail and checkbox, Select All and Clear. -fn assets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { +/// The Assets tab: each asset's thumbnail with its checkbox and name, in a grid or a list. +fn assets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, list: bool) { let Some(st) = app.session.active() else { return }; if st.doc.assets.is_empty() { ui.add_space(24.0); @@ -542,39 +572,30 @@ fn assets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { } let mut on = checked_assets(app, d); let before = on.clone(); - ui.horizontal(|ui| { - if ui.small_button(tl!("Select All")).clicked() { - on = st.doc.assets.iter().map(|a| a.id).collect(); - } - if ui.small_button(tl!("Clear")).clicked() { - on.clear(); - } - }); - // Asked for until the row is in view: the dialog's first frame only measures it. + // Asked for until its row is in view: the dialog's first frame only measures it. let scroll_to = d.fields.get("__scrollTo").and_then(Value::as_u64).filter(|id| st.doc.assets.iter().any(|a| a.id == *id)); let mut in_view = scroll_to.is_none(); - egui::ScrollArea::vertical().max_height(330.0).show(ui, |ui| { - for a in &st.doc.assets { - let row = ui.horizontal(|ui| { - let (r, _) = ui.allocate_exact_size(egui::vec2(46.0, 46.0), egui::Sense::hover()); - crate::panels::asset_export::paint_thumb(ui, st, a, r); - let checked = on.contains(&a.id); - if crate::widgets::check_name(ui, &a.name, checked) { - on.retain(|id| *id != a.id); - if !checked { - on.push(a.id); - } - } - }); - if scroll_to == Some(a.id) { - if ui.clip_rect().contains_rect(row.response.rect) { - in_view = true; - } else { - row.response.scroll_to_me(Some(egui::Align::Center)); - } + let clicked = tiles(ui, "efs-assets", st.doc.assets.len(), list, |ui, i, r| { + let Some(a) = st.doc.assets.get(i) else { return (String::new(), String::new(), false) }; + crate::panels::asset_export::paint_thumb(ui, st, a, r); + if scroll_to == Some(a.id) { + if ui.clip_rect().contains_rect(r) { + in_view = true; + } else { + ui.scroll_to_rect(r, Some(egui::Align::Center)); } } + (a.name.clone(), a.name.clone(), on.contains(&a.id)) }); + for i in clicked { + if let Some(a) = st.doc.assets.get(i) { + if on.contains(&a.id) { + on.retain(|id| *id != a.id); + } else { + on.push(a.id); + } + } + } if in_view { d.fields.remove("__scrollTo"); } @@ -583,8 +604,8 @@ fn assets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { } } -/// Export to: the folder (typed or picked), Open Location after Export and Create Sub-folders; the -/// web downloads instead. +/// Export to: the folder (typed or picked), Open Location after Export, and Create Sub-folders, +/// a folder per scale or per format; the web downloads instead. fn destination(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { widgets::dim_label(ui, tl!("Export to:")); if io::is_web(app) { @@ -592,78 +613,111 @@ fn destination(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { } else { let pick = app.services.pick_folder.is_some(); ui.horizontal(|ui| { - form::text(ui, d, "folder", if pick { 300.0 } else { 334.0 }); + form::text(ui, d, "folder", if pick { RIGHT_W - 40.0 } else { RIGHT_W - 6.0 }); if pick && widgets::icon_button(ui, "folder-open", tl!("Choose a folder"), false, 26.0).clicked() { crate::picks::folder_field(app, d, "folder"); } }); form::check(ui, d, "openLocation", tl!("Open Location after Export")); } + form::check(ui, d, "subfolders", tl!("Create Sub-folders")); ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("Folders:")); - let current = d.str("folders"); - let at = FOLDERS.iter().position(|(id, _)| *id == current).unwrap_or(0); - if let Some((id, _)) = widgets::dropdown(ui, "efs-folders", FOLDER_LABELS[at], &FOLDER_LABELS, 190.0).and_then(|i| FOLDERS.get(i)) { - d.fields.insert("folders".into(), json!(id)); - d.fields.insert("subfolders".into(), json!(*id == "rows")); + ui.add_space(22.0); + let on = d.bool("subfolders"); + let by = d.str("subfolderBy"); + if widgets::radio(ui, tl!("Scale"), by != "format", on) { + d.fields.insert("subfolderBy".into(), json!("scale")); + } + if widgets::radio(ui, tl!("Format"), by == "format", on) { + d.fields.insert("subfolderBy".into(), json!("format")); } }); } -/// Export Preset: apply a built-in or saved preset (its formats, settings, naming and folders), -/// save the dialog's settings as one (Save…, then a name), or delete a saved one. -fn presets(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { +/// Export PDFs As: one file of every chosen artboard, or a file each; only for artboards (not +/// Full Document) with a PDF row. +fn pdf_mode(ui: &mut egui::Ui, d: &mut Dialog, artboards: bool) { + let pdf = d + .fields + .get("formats") + .and_then(Value::as_array) + .is_some_and(|rows| rows.iter().any(|r| r["format"].as_str().and_then(fileio::format).is_some_and(|f| f.id == "pdf"))); + let on = artboards && pdf && d.str("select") != "full"; + ui.horizontal(|ui| { + ui.add_enabled_ui(on, |ui| widgets::dim_label(ui, tl!("Export PDFs As:"))); + let single = d.str("pdfs") == "single"; + if widgets::radio(ui, tl!("Single File"), single, on) { + d.fields.insert("pdfs".into(), json!("single")); + } + if widgets::radio(ui, tl!("Multiple Files"), !single, on) { + d.fields.insert("pdfs".into(), json!("multiple")); + } + }); +} + +/// The format presets (the ☰ by iOS and Android): apply a built-in or saved one (its rows, their +/// settings, the prefix and the sub-folders), save the dialog's rows as one, or delete the saved +/// one applied last. +fn preset_menu(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let list: Vec<Value> = d.fields.get("__exportPresets").and_then(Value::as_array).cloned().unwrap_or_default(); - let names: Vec<&str> = list.iter().filter_map(|p| p["name"].as_str()).collect(); let current = d.str("exportPreset"); let saved = list.iter().any(|p| p["name"] == current && p["builtIn"] == false); - ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("Export Preset:")); - let labels: Vec<&str> = std::iter::once("Custom").chain(names.iter().copied()).collect(); - let at = names.iter().position(|n| *n == current).map_or(0, |i| i + 1); - if let Some(i) = widgets::dropdown(ui, "efs-export-preset", labels[at], &labels, 150.0) - && let Some(preset) = i.checked_sub(1).and_then(|i| list.get(i)) - { - apply_preset(d, preset); - } - if widgets::icon_button(ui, "save", tl!("Save Preset…"), false, 24.0).clicked() { - let name = if saved { current.clone() } else { String::new() }; - d.fields.insert("__savePreset".into(), json!(name)); - } - ui.add_enabled_ui(saved, |ui| { - if widgets::icon_button(ui, "trash-2", tl!("Delete Preset"), false, 24.0).clicked() - && app.run("document.exportPresets.delete", json!({"name": current})).is_ok() - { - d.fields.insert("exportPreset".into(), json!("")); - d.fields.insert("__exportPresets".into(), export_presets(app)); + let resp = widgets::icon_button(ui, "menu", tl!("Format Presets"), false, 24.0); + let clicked = resp.clicked(); + let _ = widgets::popover(&resp, clicked, |ui| { + for p in &list { + let name = p["name"].as_str().unwrap_or_default(); + if widgets::menu_item_name(ui, name, true, name == current) { + apply_preset(d, p); + ui.close(); } - }); + } + ui.separator(); + if widgets::menu_item(ui, tl!("Save Preset…"), true, false) { + d.fields.insert("__savePreset".into(), json!(if saved { current.clone() } else { String::new() })); + ui.close(); + } + if widgets::menu_item(ui, tl!("Delete Preset"), saved, false) && app.run("document.exportPresets.delete", json!({"name": current})).is_ok() { + d.fields.insert("exportPreset".into(), json!("")); + d.fields.insert("__exportPresets".into(), export_presets(app)); + ui.close(); + } }); - if d.fields.contains_key("__savePreset") { - ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("Name:")); - form::text(ui, d, "__savePreset", 150.0); - let name = d.str("__savePreset").trim().to_string(); - if ui.add_enabled(!name.is_empty(), egui::Button::new(tl!("Save"))).clicked() { - let settings = params(app, d).unwrap_or_else(|_| json!({"formats": d.fields.get("formats").cloned().unwrap_or(json!([]))})); - match app.run("document.exportPresets.save", json!({"name": name, "settings": settings})) { - Ok(_) => { - d.fields.remove("__savePreset"); - d.fields.insert("exportPreset".into(), json!(name)); - d.fields.insert("__exportPresets".into(), export_presets(app)); - } - Err(e) => app.ui.status = e, - } - } - if ui.small_button(tl!("Cancel")).clicked() { - d.fields.remove("__savePreset"); - } - }); - } } -/// Set the dialog to preset `preset` (`{name, settings}`): its formats, settings, naming and -/// folders; what it doesn't name keeps the dialog's value. +/// The row that names a format preset being saved (Save Preset… in the ☰ menu). +fn save_preset_row(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { + if !d.fields.contains_key("__savePreset") { + return; + } + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Name:")); + form::text(ui, d, "__savePreset", 150.0); + let name = d.str("__savePreset").trim().to_string(); + if ui.add_enabled(!name.is_empty(), egui::Button::new(tl!("Save"))).clicked() { + let settings = json!({ + "formats": d.fields.get("formats").cloned().unwrap_or(json!([])), + "settings": d.fields.get("settings").cloned().unwrap_or(json!({})), + "prefix": d.str("prefix"), + "folders": if !d.bool("subfolders") { "none" } else if d.str("subfolderBy") == "format" { "format" } else { "rows" }, + }); + match app.run("document.exportPresets.save", json!({"name": name, "settings": settings})) { + Ok(_) => { + d.fields.remove("__savePreset"); + d.fields.insert("exportPreset".into(), json!(name)); + d.fields.insert("__exportPresets".into(), export_presets(app)); + } + Err(e) => app.ui.status = e, + } + } + if ui.small_button(tl!("Cancel")).clicked() { + d.fields.remove("__savePreset"); + } + }); +} + +/// Set the dialog to format preset `preset` (`{name, settings}`): its rows, their settings, the +/// prefix and the sub-folders; what it doesn't name keeps the dialog's value. pub(super) fn apply_preset(d: &mut Dialog, preset: &Value) { let st = &preset["settings"]; if let Some(rows) = st["formats"].as_array() { @@ -680,127 +734,29 @@ pub(super) fn apply_preset(d: &mut Dialog, preset: &Value) { } let folders = st["folders"].as_str().or_else(|| st["subfolders"].as_bool().map(|b| if b { "rows" } else { "none" })); if let Some(f) = folders { - d.fields.insert("folders".into(), json!(f)); - d.fields.insert("subfolders".into(), json!(f == "rows")); + d.fields.insert("subfolders".into(), json!(f != "none")); + d.fields.insert("subfolderBy".into(), json!(if f == "format" { "format" } else { "scale" })); } - for k in ["name", "prefix"] { - d.fields.insert(k.into(), json!(st[k].as_str().unwrap_or_default())); + if let Some(prefix) = st["prefix"].as_str() { + d.fields.insert("prefix".into(), json!(prefix)); } - d.fields.insert("counterStart".into(), json!(st["counterStart"].as_u64().unwrap_or(1))); if let Some(b) = st["includeBleed"].as_bool() { d.fields.insert("includeBleed".into(), json!(b)); } - if let Some(f) = st["folder"].as_str().filter(|f| !f.is_empty()) { - d.fields.insert("folder".into(), json!(f)); - } d.fields.insert("exportPreset".into(), json!(preset["name"])); } -/// File Name: the pattern (with Insert for its tokens), the counter's start, the prefix and an -/// example of the first file's name. -fn naming(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { - ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("File Name:")); - // A pattern typed by hand is no longer the preset's. - if form::text(ui, d, "name", 170.0) { - d.fields.insert("exportPreset".into(), json!("")); - } - if let Some((_, token)) = - widgets::dropdown_named(ui, "efs-name-token", Some(tl!("Insert")), tl!("Insert"), &TOKEN_LABELS, 90.0).and_then(|i| TOKENS.get(i)) - { - let name = d.str("name"); - d.fields.insert("name".into(), json!(format!("{name}{token}"))); - } - }); - ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("Prefix:")); - form::text(ui, d, "prefix", 110.0); - widgets::dim_label(ui, tl!("Start at:")); - if let Some(v) = widgets::range_field(ui, "efs-counter-start", counter_start(d) as f64, 0.0..=999_999.0, "", 0, 64.0) { - d.fields.insert("counterStart".into(), json!(v.round().max(0.0) as u64)); - } - }); - let example = example_name(app, d); - if !example.is_empty() { - widgets::dim_label(ui, &crate::i18n::fmt(tl!("Example: {name}"), &[("name", &example)])); - } -} +/// What the dialog adds by the iOS and Android buttons: its format presets. +pub(crate) type FormatMenu<'a> = &'a mut dyn FnMut(&mut egui::Ui, &mut Dialog); -/// The first file the export writes, relative to the export folder, as `document.exportForScreens` -/// names it ([`fileio::screen_first_file`]); empty while the dialog's settings choose nothing to -/// export (no format, nothing checked or selected, a bad range). -pub(super) fn example_name(app: &VectorcraftApp, d: &Dialog) -> String { - settings_params(app, d).ok().and_then(|(p, _)| fileio::screen_first_file(&app.session, &Value::Object(p)).ok()).unwrap_or_default() -} +/// The iOS and Android rows (the engine's `mobile` and `density` presets) and their labels. +const PLATFORMS: [(&str, &str); 2] = [("mobile", "iOS"), ("density", "Android")]; -/// The Layers tab: each top-level layer's thumbnail and checkbox (a file of its art alone), -/// Select All and Clear. -fn layers(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { - let Some(st) = app.session.active() else { return }; - let mut on = checked_layers(app, d); - let before = on.clone(); - ui.horizontal(|ui| { - if ui.small_button(tl!("Select All")).clicked() { - on = st.doc.layers.iter().map(|l| l.id.0).collect(); - } - if ui.small_button(tl!("Clear")).clicked() { - on.clear(); - } - }); - egui::ScrollArea::vertical().max_height(330.0).show(ui, |ui| { - for l in &st.doc.layers { - ui.horizontal(|ui| { - let (r, _) = ui.allocate_exact_size(egui::vec2(46.0, 46.0), egui::Sense::hover()); - let mut art = vec![]; - layer_art(&st.doc, l.id, &mut art); - // An id of its own for the thumbnail cache, away from the assets' ids. - let a = ExportAsset { id: u64::MAX - l.id.0, name: l.display_name(), nodes: art }; - crate::panels::asset_export::paint_thumb(ui, st, &a, r); - let checked = on.contains(&l.id.0); - if crate::widgets::check_name(ui, &l.display_name(), checked) { - on.retain(|id| *id != l.id.0); - if !checked { - on.push(l.id.0); - } - } - }); - } - }); - if on != before { - d.fields.insert("layers".into(), json!(on)); - } -} - -/// The Selection tab: what is selected (a thumbnail and the count), as one file or a file per -/// object. -fn selection(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { - let Some(st) = app.session.active() else { return }; - let ids = st.selection.objects.clone(); - if ids.is_empty() { - ui.add_space(24.0); - widgets::dim_label(ui, tl!("Nothing is selected. Select the art to export, then open this tab again.")); - return; - } - let (r, _) = ui.allocate_exact_size(egui::vec2(120.0, 120.0), egui::Sense::hover()); - // The selection changes without a new revision: its ids name its thumbnail. - let key = ids.iter().fold(0x005e_1ec7_u64, |h, id| h.rotate_left(7) ^ id.0); - let a = ExportAsset { id: u64::MAX / 2 + (key % (u64::MAX / 4)), name: "Selection".into(), nodes: ids.clone() }; - crate::panels::asset_export::paint_thumb(ui, st, &a, r); - let count = ids.len().to_string(); - widgets::dim_label(ui, &crate::i18n::fmt(tl!("{n} objects selected"), &[("n", &count)])); - ui.add_space(6.0); - let mode = d.str("selectionMode"); - if widgets::radio(ui, tl!("One File of the Selection"), mode != "each", true) { - d.fields.insert("selectionMode".into(), json!("one")); - } - if widgets::radio(ui, tl!("A File per Object"), mode == "each", true) { - d.fields.insert("selectionMode".into(), json!("each")); - } -} - -/// The preset, the Format Settings gear (which sets `__settings`), the format rows (scale, suffix, -/// format) and Add Scale, as wide as `ui` allows: the dialog's and the Asset Export panel's rows. -pub(crate) fn formats(ui: &mut egui::Ui, d: &mut Dialog) { +/// Formats: the iOS and Android buttons (each sets the rows that platform uses), `menu` (the +/// dialog's format presets), the Format Settings gear (which sets `__settings`), the format rows +/// (scale, suffix, format) and Add Scale, as wide as `ui` allows: the dialog's and the Asset +/// Export panel's rows. +pub(crate) fn formats(ui: &mut egui::Ui, d: &mut Dialog, mut menu: Option<FormatMenu<'_>>) { let mut rows: Vec<Value> = d.fields.get("formats").and_then(Value::as_array).cloned().unwrap_or_default(); let mut edited = false; ui.horizontal(|ui| { @@ -816,19 +772,21 @@ pub(crate) fn formats(ui: &mut egui::Ui, d: &mut Dialog) { .filter(|f| SETTINGS.iter().any(|(id, _)| id == f)); d.fields.insert("__settings".into(), json!(first.unwrap_or("png"))); } - let preset = d.str("preset"); - let labels: Vec<&str> = std::iter::once("Custom").chain(SCREEN_PRESETS.iter().map(|(_, l)| *l)).collect(); - let at = SCREEN_PRESETS.iter().position(|(id, _)| *id == preset).map_or(0, |i| i + 1); - if let Some(i) = - widgets::dropdown_named(ui, "efs-preset", Some(tl!("Preset:")), labels[at], &labels, (ui.available_width() - 8.0).clamp(90.0, 180.0)) - { - let id = i.checked_sub(1).and_then(|i| SCREEN_PRESETS.get(i)).map_or("", |(id, _)| *id); - if let Some(preset_rows) = fileio::screen_preset_rows(id) { + if let Some(menu) = menu.as_mut() { + menu(ui, d); + } + // Right to left: Android, then iOS before it. + for (id, label) in PLATFORMS.iter().rev() { + let on = d.str("preset") == *id; + if ui.add(egui::Button::new(egui::RichText::new(tl!(label)).size(12.0)).selected(on).frame(on)).clicked() + && let Some(preset_rows) = fileio::screen_preset_rows(id) + { rows = preset_rows; d.fields.insert("subfolders".into(), json!(true)); + d.fields.insert("subfolderBy".into(), json!("scale")); d.fields.insert("formats".into(), json!(rows)); + d.fields.insert("preset".into(), json!(id)); } - d.fields.insert("preset".into(), json!(id)); } }); }); diff --git a/crates/ui-egui/src/dialogs/tests_accessibility.rs b/crates/ui-egui/src/dialogs/tests_accessibility.rs index 42ee3256b4..ac469f6b72 100644 --- a/crates/ui-egui/src/dialogs/tests_accessibility.rs +++ b/crates/ui-egui/src/dialogs/tests_accessibility.rs @@ -39,16 +39,16 @@ fn strict(app: VectorcraftApp) -> Harness { h } -/// Export for Screens names its three text fields and exposes no raw widget ids. +/// Export for Screens names its range and prefix fields and exposes no raw widget ids. #[test] fn export_for_screens_names_the_form_text_fields() { let mut app = app(); app.run("file.exportForScreens", json!({})).unwrap(); let h = strict(app); - for name in ["File Name:", "Prefix:", "Start at:"] { + for name in ["Range:", "Prefix:"] { let _ = h.get_by_role_and_label(Role::TextInput, name); } - assert!(h.query_by_role_and_label(Role::TextInput, "name").is_none(), "no internal widget id"); + assert!(h.query_by_role_and_label(Role::TextInput, "range").is_none(), "no internal widget id"); assert!(h.query_by_role_and_label(Role::TextInput, "prefix").is_none(), "no internal widget id"); } diff --git a/crates/ui-egui/src/dialogs/tests_screen_assets.rs b/crates/ui-egui/src/dialogs/tests_screen_assets.rs index 9bfd4f5078..32f585e812 100644 --- a/crates/ui-egui/src/dialogs/tests_screen_assets.rs +++ b/crates/ui-egui/src/dialogs/tests_screen_assets.rs @@ -65,10 +65,10 @@ fn export_selection_collects_the_selection_and_opens_the_assets_tab() { assert_eq!(assets(&mut app).len(), 2); assert_eq!(field(&app, "assets"), json!(ids)); let text = painted_text(&mut app, |app, ui| super::show(app, ui.ctx())); - assert!(text.contains("Asset 1") && text.contains("Asset 2") && text.contains("Select All"), "{text}"); - // The web downloads both as one zip. + assert!(text.contains("Asset 1") && text.contains("Asset 2") && text.contains("Clear Selection"), "{text}"); + // The web downloads both as one zip, in the 1x sub-folder Create Sub-folders makes by default. let r = confirm(&mut app).unwrap(); - assert_eq!(r["files"], json!(["Asset-1.png", "Asset-2.png"])); + assert_eq!(r["files"], json!(["1x/Asset-1.png", "1x/Asset-2.png"])); assert_eq!(log.borrow().len(), 1); assert!(app.ui.dialog.is_none()); // Nothing selected: Export Selection is off; document.exportSelection still exports in one go. @@ -112,8 +112,9 @@ fn the_assets_tab_exports_the_checked_assets_into_the_folder() { set(&mut app, "assets", json!([ids[1], 999])); set(&mut app, "formats", json!([{"format": "png", "scale": "2x", "suffix": "@2x"}])); let r = confirm(&mut app).unwrap(); - assert_eq!(r["files"], json!([format!("{folder}/Asset-2@2x.png")])); - let png = image::load_from_memory(&std::fs::read(dir.join("Asset-2@2x.png")).unwrap()).unwrap(); + // Create Sub-folders is on by default: a folder per scale. + assert_eq!(r["files"], json!([format!("{folder}/2x/Asset-2@2x.png")])); + let png = image::load_from_memory(&std::fs::read(dir.join("2x").join("Asset-2@2x.png")).unwrap()).unwrap(); assert_eq!((png.width(), png.height()), (60, 40), "the asset's art at 2x"); assert_eq!(log.borrow().len(), 1, "Open Location shows the file"); // The rows are remembered for the dialog and the Asset Export panel alike. diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index 38f469e30b..2a54850ca4 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -63,7 +63,8 @@ fn opens_on_defaults_and_draws_every_view() { assert_eq!((field(&app, "select"), field(&app, "range"), field(&app, "boards")), (json!("all"), json!("1-3"), json!([true, true, true]))); assert_eq!(field(&app, "formats"), json!([{"format": "png", "scale": "1x", "suffix": ""}])); assert_eq!(field(&app, "folder"), json!(fileio::export_folder().unwrap_or_default()), "the Desktop, else home"); - assert_eq!((field(&app, "openLocation"), field(&app, "subfolders"), field(&app, "preset")), (json!(true), json!(false), json!(""))); + assert_eq!((field(&app, "openLocation"), field(&app, "subfolders"), field(&app, "preset")), (json!(true), json!(true), json!(""))); + assert_eq!((field(&app, "subfolderBy"), field(&app, "pdfs"), field(&app, "view")), (json!("scale"), json!("multiple"), json!("grid"))); let settings = field(&app, "settings"); for f in ["png", "png8", "jpg", "webp", "gif", "tiff", "svg", "pdf"] { assert!(settings[f].is_object(), "{f} has settings"); @@ -128,7 +129,8 @@ fn opens_with_the_artboards_the_artboard_tool_selected_and_exports_only_them() { frame(&mut app); assert_eq!(field(&app, "boards"), json!([false, true, true, false]), "drawing the dialog keeps them"); let r = confirm(&mut app).unwrap(); - assert_eq!(r["files"], json!(["Artboard-2.png", "Artboard-3.png"])); + // Create Sub-folders is on by default, a folder per scale. + assert_eq!(r["files"], json!(["1x/Artboard-2.png", "1x/Artboard-3.png"])); assert_eq!(log.borrow().len(), 1, "one zip"); // With every artboard selected it opens on All. click(&mut app, 0, true); @@ -433,7 +435,7 @@ fn the_web_downloads_one_zip_or_the_file() { assert_eq!(name, "Untitled-1.zip"); assert_eq!(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(), zip); } - assert_eq!(r["files"], json!(["Artboard-1.png", "Artboard-1@2x.jpg", "Artboard-2.png", "Artboard-2@2x.jpg"])); + assert_eq!(r["files"], json!(["1x/Artboard-1.png", "2x/Artboard-1@2x.jpg", "1x/Artboard-2.png", "2x/Artboard-2@2x.jpg"])); // One file downloads as itself, with the format's settings. log.borrow_mut().clear(); open(&mut app); @@ -602,7 +604,7 @@ fn screen_format_gear(out: &egui::FullOutput, width: f32) -> egui::Pos2 { } } let label = out.shapes.iter().find_map(|s| label(&s.shape)).expect("painted Formats row"); - // The existing 24 pt gear is right-aligned in the 350 pt dialog or 236 pt panel. + // The existing 24 pt gear is right-aligned in the dialog's 370 pt column or the 236 pt panel. egui::pos2(label.left() + width - 12.0, label.center().y) } @@ -635,7 +637,7 @@ fn saved_tiff_alias_gear(alias: &str, asset_panel: bool) { }; draw(&mut h, &mut app, vec![]); let out = draw(&mut h, &mut app, vec![]); - let gear = screen_format_gear(&out, if asset_panel { 236.0 } else { 350.0 }); + let gear = screen_format_gear(&out, if asset_panel { 236.0 } else { 370.0 }); draw(&mut h, &mut app, vec![egui::Event::PointerMoved(gear)]); for pressed in [true, false] { draw( @@ -707,11 +709,12 @@ fn tiff_dropdown_exports_scaled_artboards_with_options_and_reopens() { // Begin with an existing PNG row; TIFF must be chosen from the actual popup. set(&mut app, "formats", json!([{"format": "png", "scale": "2x", "suffix": "@2x"}])); set(&mut app, "prefix", json!("proof-")); + set(&mut app, "subfolders", json!(false)); let mut h = ScreensFrame::new(); h.choose(&mut app, "PNG", "TIFF"); assert_eq!(field(&app, "formats"), json!([{"format": "tiff", "scale": "2x", "suffix": "@2x"}])); // Leave only the first of two boards checked. - h.click_label(&mut app, "Artboard 2"); + h.click_label(&mut app, "2 Artboard 2"); assert_eq!(field(&app, "boards"), json!([true, false])); assert_eq!(field(&app, "range"), json!("1")); @@ -766,168 +769,114 @@ fn tiff_dropdown_exports_scaled_artboards_with_options_and_reopens() { /// name, a prefix with characters Windows does not allow, a range, a Windows device name as an item /// folder, the rows' folders and sizes, Create Sub-folders, a vector row's size suffix, the counter /// typed as text, and the Layers and Selection tabs. +/// The dialog is laid out as Illustrator's: two tabs (Artboards, Assets), Clear Selection and the +/// prefix under the thumbnails, Create Sub-folders by scale or format, Export PDFs As, the iOS and +/// Android rows, and how many items and files the export takes; no naming, layer or selection +/// pages, presets bar or folders list. #[test] -fn the_example_names_the_first_file_the_export_writes() { +fn the_dialog_is_laid_out_as_illustrators() { let (mut app, _) = app(3, false); - app.run("artboard.setProps", json!({"index": 2, "name": "CON"})).unwrap(); - app.run("select.all", json!({})).unwrap(); - let dir = temp_folder("example"); - let folder = dir.to_string_lossy().to_string(); - let png = json!([{"format": "png", "scale": "1x", "suffix": ""}]); - let cases: Vec<Vec<(&str, Value)>> = vec![ - vec![], - vec![("prefix", json!("a?b"))], - vec![("select", json!("range")), ("range", json!("2-3"))], - vec![("select", json!("range")), ("range", json!("3")), ("folders", json!("item"))], - vec![("folders", json!("rows")), ("formats", json!([{"format": "png", "scale": "144ppi", "suffix": ""}]))], - vec![("subfolders", json!(true))], - vec![("folders", json!("rows")), ("formats", json!([{"format": "png", "scale": "2x", "suffix": "@2x", "folder": "retina"}]))], - vec![("formats", json!([{"format": "svg", "scale": "2x", "suffix": "@2x"}]))], - vec![("name", json!("<scale>-####")), ("counterStart", json!("7")), ("formats", json!([{"format": "png", "scale": "144ppi", "suffix": ""}]))], - vec![("tab", json!("layers"))], - vec![("tab", json!("selection")), ("selectionMode", json!("each"))], - ]; - let mut wrong = vec![]; - for case in cases { - let _ = std::fs::remove_dir_all(&dir); - open(&mut app); - let defaults = [ - ("folder", json!(folder)), - ("tab", json!("artboards")), - ("select", json!("all")), - ("prefix", json!("")), - ("name", json!("")), - ("counterStart", json!(1)), - ("folders", json!("none")), - ("subfolders", json!(false)), - ("formats", png.clone()), - ]; - for (k, v) in defaults.into_iter().chain(case.iter().cloned()) { - set(&mut app, k, v); - } - frame(&mut app); - let example = export_for_screens::example_name(&app, app.ui.dialog.as_ref().unwrap()); - let r = confirm(&mut app).unwrap(); - let first = r["files"][0].as_str().and_then(|f| f.strip_prefix(&format!("{folder}/"))).unwrap_or_default().to_string(); - if example != first { - wrong.push(format!("{case:?}: example {example:?}, written {first:?}")); - } + open(&mut app); + let text = crate::tests_labels::shapes_text(&ScreensFrame::new().settle(&mut app)); + for label in [ + "Artboards", + "Assets", + "Select:", + "Full Document", + "Include Bleed", + "Export to:", + "Open Location after Export", + "Create Sub-folders", + "Scale", + "Format", + "Export PDFs As:", + "Single File", + "Multiple Files", + "Formats:", + "iOS", + "Android", + "+ Add Scale", + "Clear Selection", + "Prefix:", + "Selected: 3, Total number of files to export: 3", + ] { + assert!(text.lines().any(|l| l.trim() == label), "{label} missing:\n{text}"); + } + for gone in ["Layers", "Selection", "Export Preset:", "File Name:", "Folders:", "Start at:"] { + assert!(!text.lines().any(|l| l.trim() == gone), "{gone} shown:\n{text}"); } - let _ = std::fs::remove_dir_all(&dir); - assert!(wrong.is_empty(), "{wrong:#?}"); } -/// The Example line shows before a folder is chosen and is left out while the settings choose -/// nothing to export (the Assets tab with no asset checked); Start at shows the counter the export -/// uses when it was set as text. +/// iOS and Android set the rows those platforms use (in sub-folders); Clear Selection unchecks +/// every artboard, so nothing is exported until one is checked again. #[test] -fn the_example_needs_no_folder_and_start_at_shows_the_counter_used() { - let (mut app, _) = app(1, false); +fn ios_android_and_clear_selection() { + let (mut app, _) = app(2, false); open(&mut app); - for (k, v) in [("folder", json!("")), ("name", json!("####")), ("counterStart", json!("7"))] { + set(&mut app, "subfolders", json!(false)); + let mut h = ScreensFrame::new(); + h.click_label(&mut app, "iOS"); + let scales: Vec<Value> = field(&app, "formats").as_array().unwrap().iter().map(|r| r["scale"].clone()).collect(); + assert_eq!((field(&app, "preset"), field(&app, "subfolders")), (json!("mobile"), json!(true))); + assert_eq!(scales, [json!("1x"), json!("2x"), json!("3x")]); + h.click_label(&mut app, "Android"); + assert_eq!((field(&app, "preset"), field(&app, "formats").as_array().unwrap().len()), (json!("density"), 6)); + h.click_label(&mut app, "Clear Selection"); + assert_eq!((field(&app, "boards"), field(&app, "select")), (json!([false, false]), json!("range"))); + let text = crate::tests_labels::shapes_text(&h.settle(&mut app)); + assert!(text.contains("Selected: 0, Total number of files to export: 0"), "{text}"); + set(&mut app, "folder", json!(temp_folder("cleared").to_string_lossy())); + assert!(confirm(&mut app).is_err(), "nothing to export"); +} + +/// Create Sub-folders sorts the files into a folder per scale or per format; Export PDFs As › +/// Single file writes the chosen artboards as one PDF named after the document. +#[test] +fn sub_folders_and_single_file_pdfs() { + let (mut app, _) = app(3, false); + let dir = temp_folder("subfolders"); + let _ = std::fs::remove_dir_all(&dir); + let folder = dir.to_string_lossy().to_string(); + let title = app.session.active().unwrap().doc.title.clone(); + let rows = json!([ + {"format": "png", "scale": "1x", "suffix": ""}, + {"format": "png", "scale": "2x", "suffix": "@2x"}, + {"format": "pdf", "scale": "1x", "suffix": ""} + ]); + let files = |app: &mut VectorcraftApp, extra: &[(&str, Value)]| -> Vec<String> { + open(app); + let base = [("folder", json!(folder)), ("select", json!("range")), ("range", json!("1-2")), ("formats", rows.clone())]; + for (k, v) in base.into_iter().chain(extra.iter().cloned()) { + set(app, k, v); + } + frame(app); + let r = confirm(app).unwrap(); + r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().strip_prefix(&format!("{folder}/")).unwrap().to_string()).collect() + }; + let by_scale = files(&mut app, &[("subfolders", json!(true)), ("subfolderBy", json!("scale"))]); + assert_eq!(&by_scale[..2], ["1x/Artboard-1.png", "2x/Artboard-1@2x.png"]); + let by_format = files(&mut app, &[("subfolders", json!(true)), ("subfolderBy", json!("format")), ("pdfs", json!("single"))]); + let pdf = format!("pdf/{title}.pdf"); + assert_eq!(by_format, ["png/Artboard-1.png", "png/Artboard-1@2x.png", pdf.as_str(), "png/Artboard-2.png", "png/Artboard-2@2x.png"]); + let flat = files(&mut app, &[("subfolders", json!(false)), ("pdfs", json!("multiple"))]); + assert_eq!(flat.len(), 6); + assert!(flat.contains(&"Artboard-2.pdf".to_string()), "{flat:?}"); + // The status line counts the files Single file writes. + open(&mut app); + for (k, v) in [("select", json!("range")), ("range", json!("1-2")), ("formats", rows.clone()), ("pdfs", json!("single"))] { set(&mut app, k, v); } - let mut h = ScreensFrame::new(); - let text = crate::tests_labels::shapes_text(&h.settle(&mut app)); - assert!(text.lines().any(|l| l == "Example: 0007.png"), "{text}"); - assert!(text.lines().any(|l| l.trim() == "7"), "{text}"); - set(&mut app, "tab", json!("assets")); - let text = crate::tests_labels::shapes_text(&h.settle(&mut app)); - assert!(!text.contains("Example:"), "{text}"); -} - -/// Batch exporting (#1935): a file name pattern and a folder per format, the Layers and Selection -/// tabs, and export presets applied and saved from the dialog. -#[test] -fn batch_naming_folders_layers_selection_and_presets() { - let (mut app, _) = app(3, false); - let dir = temp_folder("batch"); - let _ = std::fs::remove_dir_all(&dir); - let folder = dir.to_string_lossy().to_string(); - open(&mut app); - assert_eq!(field(&app, "folders"), json!("none")); - // Every tab draws; the OK button says what is exported. - for (tab, ok) in [("layers", "Export Layer"), ("selection", "Export Selection"), ("assets", "Export Asset"), ("artboards", "Export Artboard")] { - set(&mut app, "tab", json!(tab)); - frame(&mut app); - assert_eq!((spec(export_for_screens::KIND).ok_label.unwrap())(&app), ok); - } - // Artboards 1–2 as SVG and print PDF, named by pattern, a folder per format. - set(&mut app, "folder", json!(folder)); - set(&mut app, "select", json!("range")); - set(&mut app, "range", json!("1-2")); - set(&mut app, "name", json!("ACME-<name>-##")); - set(&mut app, "folders", json!("format")); - set( - &mut app, - "formats", - json!([{"format": "svg", "scale": "1x", "suffix": ""}, {"format": "pdf", "scale": "1x", "suffix": "-print", "marks": {"trim": true}}]), - ); - frame(&mut app); - { - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(export_for_screens::example_name(&app, d), "svg/ACME-Artboard 1-01.svg"); - } - let r = confirm(&mut app).unwrap(); - let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect(); - assert_eq!( - files, - [ - format!("{folder}/svg/ACME-Artboard 1-01.svg"), - format!("{folder}/pdf/ACME-Artboard 1-01-print.pdf"), - format!("{folder}/svg/ACME-Artboard 2-02.svg"), - format!("{folder}/pdf/ACME-Artboard 2-02-print.pdf") - ] - ); - // It reopens on the pattern and the folders. - open(&mut app); - assert_eq!((field(&app, "name"), field(&app, "folders")), (json!("ACME-<name>-##"), json!("format"))); - - // The Layers tab: one file of a layer's art. - let layer = app.session.active().unwrap().doc.layers[0].id.0; - set(&mut app, "folder", json!(folder)); - set(&mut app, "tab", json!("layers")); - set(&mut app, "layers", json!([layer])); - set(&mut app, "name", json!("")); - set(&mut app, "folders", json!("none")); - set(&mut app, "formats", json!([{"format": "png", "scale": "1x", "suffix": ""}])); - let r = confirm(&mut app).unwrap(); - assert_eq!(r["files"][0], json!(format!("{folder}/Layer-1.png"))); - - // The Selection tab: nothing selected keeps the dialog open; a file per selected object. - open(&mut app); - app.run("select.none", json!({})).unwrap(); - set(&mut app, "folder", json!(folder)); - set(&mut app, "tab", json!("selection")); - frame(&mut app); - assert!(confirm(&mut app).is_err()); - app.run("select.all", json!({})).unwrap(); - set(&mut app, "selectionMode", json!("each")); - set(&mut app, "name", json!("piece-#")); - set(&mut app, "formats", json!([{"format": "svg", "scale": "1x", "suffix": ""}])); - frame(&mut app); - let r = confirm(&mut app).unwrap(); - assert_eq!(r["files"][0], json!(format!("{folder}/piece-1.svg"))); - - // Presets: the Logo Package sets the formats, naming and folders; the dialog saves its own. - open(&mut app); + let text = crate::tests_labels::shapes_text(&ScreensFrame::new().settle(&mut app)); + assert!(text.contains("Selected: 2, Total number of files to export: 5"), "{text}"); + // A format preset sets the rows, their settings and the sub-folders, not a prefix it lacks. + set(&mut app, "prefix", json!("x-")); let presets = field(&app, "__exportPresets"); let logo = presets.as_array().unwrap().iter().find(|p| p["name"] == "Logo Package").unwrap().clone(); export_for_screens::apply_preset(app.ui.dialog.as_mut().unwrap(), &logo); assert_eq!(field(&app, "formats").as_array().unwrap().len(), 5); assert_eq!( - (field(&app, "folders"), field(&app, "name"), field(&app, "exportPreset")), - (json!("format"), json!("<filename>-<name>"), json!("Logo Package")) + (field(&app, "subfolders"), field(&app, "subfolderBy"), field(&app, "exportPreset")), + (json!(true), json!("format"), json!("Logo Package")) ); - frame(&mut app); - set(&mut app, "folder", json!(folder)); - set(&mut app, "__savePreset", json!("Client Pack")); - frame(&mut app); - let saved = app - .run("document.exportPresets.save", json!({"name": "Client Pack", "settings": {"formats": field(&app, "formats"), "folders": "item"}})) - .unwrap(); - assert_eq!(saved["name"], "Client Pack"); - let list = export_for_screens::export_presets(&mut app); - assert!(list.as_array().unwrap().iter().any(|p| p["name"] == "Client Pack" && p["builtIn"] == false)); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2cf931a8aa..99f0bbc2d8 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -649,6 +649,13 @@ font-technology Variable Променливи Create Report Създаване на отчет Create Slice Създаване на отрязък Create Sub-folders Създаване на подпапки + Clear Selection Изчистване на избора + Export PDFs As: Експортиране на PDF като: + Single File Един файл + Multiple Files Няколко файла + Format Presets Предварителни настройки на формата + Grid View Изглед на мрежа + Selected: {n}, Total number of files to export: {m} Избрани: {n}, общ брой файлове за експортиране: {m} Create Text Създаване на текст Create Trim Marks Създаване на режещи знаци Created Създадено @@ -3952,6 +3959,7 @@ axis Both И двете @msg cannot split an open path at its end point отворен път не може да бъде разделен в крайната му точка @msg closing needs three anchors затварянето изисква три опорни точки @msg check an asset to export изберете актив за експортиране +@msg check an artboard to export изберете монтажна област за експортиране @msg check a layer to export отметнете слой за експортиране @msg select the art to export first първо изберете графиката за експортиране @msg choice must be "merge" or "add", not `{choice}` изборът трябва да бъде "merge" или "add", а не `{choice}` diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 17de837b8e..700fd9ddee 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2228,6 +2228,13 @@ lighting Light Svjetlo Use Artboards Koristi radne ploče Choose a folder Odaberite folder Create Sub-folders Kreiraj podfoldere + Clear Selection Poništi odabir + Export PDFs As: Izvezi PDF kao: + Single File Jedna datoteka + Multiple Files Više datoteka + Format Presets Postavke formata + Grid View Prikaz mreže + Selected: {n}, Total number of files to export: {m} Odabrano: {n}, ukupan broj datoteka za izvoz: {m} Export Asset Izvezi resurs Export to: Izvezi u: Format Settings Postavke formata @@ -4339,6 +4346,7 @@ imageTrace Outline Obris @msg cannot split an open path at its end point nije moguće razdvojiti otvorenu putanju na njenoj krajnjoj tački @msg closing needs three anchors zatvaranje zahtijeva tri sidra @msg check an asset to export označite resurs za izvoz +@msg check an artboard to export označite radnu površinu za izvoz @msg check a layer to export označite sloj za izvoz @msg select the art to export first prvo odaberite crtež za izvoz @msg choice must be "merge" or "add", not `{choice}` choice mora biti "merge" ili "add", a ne `{choice}` diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a9adf22ae1..dc8fc7effd 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -918,6 +918,13 @@ Create Slice from Selection Crea un tall a partir de la selecció Create Slices from Guides Crea talls a partir de guies Create Sub-folders Crea subcarpetes + Clear Selection Esborra la selecció + Export PDFs As: Exporta els PDF com a: + Single File Un sol fitxer + Multiple Files Diversos fitxers + Format Presets Preajustos de format + Grid View Vista de quadrícula + Selected: {n}, Total number of files to export: {m} Seleccionats: {n}, nombre total de fitxers per exportar: {m} Create Text Crea text Create Trim Marks Crea marques de retall Create: Crea: @@ -4885,6 +4892,7 @@ @msg cannot split an open path at its end point no es pot dividir un traçat obert al seu punt final @msg check a layer to export marqueu una capa per exportar @msg check an asset to export marqueu un recurs per exportar +@msg check an artboard to export marqueu una mesa de treball per exportar @msg choice must be "merge" or "add", not `{choice}` l’opció ha de ser "merge" o "add", no `{choice}` @msg Choose a circle or a perfect arc Trieu un cercle o un arc perfecte @msg choose a destination folder trieu una carpeta de destinació diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 41d9b25f8f..5498e35481 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2257,6 +2257,13 @@ lighting Light Světlo Use Artboards Použít pracovní plochy Choose a folder Vyberte složku Create Sub-folders Vytvořit podsložky + Clear Selection Vymazat výběr + Export PDFs As: Exportovat PDF jako: + Single File Jeden soubor + Multiple Files Více souborů + Format Presets Přednastavení formátů + Grid View Zobrazení mřížky + Selected: {n}, Total number of files to export: {m} Vybráno: {n}, celkový počet souborů k exportu: {m} Export Asset Exportovat prvek Export to: Exportovat do: Format Settings Nastavení formátu @@ -4375,6 +4382,7 @@ imageTrace Outline Obrys @msg cannot split an open path at its end point otevřenou cestu nelze rozdělit v jejím koncovém bodu @msg closing needs three anchors uzavření vyžaduje tři kotevní body @msg check an asset to export zaškrtněte prvek k exportu +@msg check an artboard to export zaškrtněte kreslicí plátno k exportu @msg check a layer to export zaškrtněte vrstvu k exportu @msg select the art to export first nejprve vyberte kresbu k exportu @msg choice must be "merge" or "add", not `{choice}` volba musí být "merge" nebo "add", ne `{choice}` diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 1b6277fd59..c4e19d9939 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2061,6 +2061,13 @@ lighting Light Lys Use Artboards Brug tegnebrætter Choose a folder Vælg en mappe Create Sub-folders Opret undermapper + Clear Selection Ryd markering + Export PDFs As: Eksportér PDF'er som: + Single File Én fil + Multiple Files Flere filer + Format Presets Formatforudindstillinger + Grid View Gittervisning + Selected: {n}, Total number of files to export: {m} Valgt: {n}, samlet antal filer, der eksporteres: {m} Export Asset Eksportér aktiv Export to: Eksportér til: Format Settings Formatindstillinger @@ -4067,6 +4074,7 @@ imageTrace Outline Kontur @msg cannot split an open path at its end point kan ikke opdele en åben kurve i dens endepunkt @msg closing needs three anchors lukning kræver tre ankerpunkter @msg check an asset to export afkryds et aktiv, der skal eksporteres +@msg check an artboard to export afkryds en tegneflade, der skal eksporteres @msg choice must be "merge" or "add", not `{choice}` valget skal være "merge" eller "add", ikke `{choice}` @msg choose a direction to divide in vælg en retning at opdele i @msg choose a folder to export to vælg en mappe at eksportere til diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 405462042d..87ac4fc701 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -642,6 +642,13 @@ font-technology Variable Variabel Create Report Bericht erstellen Create Slice Slice erstellen Create Sub-folders Unterordner erstellen + Clear Selection Auswahl aufheben + Export PDFs As: PDFs exportieren als: + Single File Einzelne Datei + Multiple Files Mehrere Dateien + Format Presets Formatvorgaben + Grid View Rasteransicht + Selected: {n}, Total number of files to export: {m} Ausgewählt: {n}, Gesamtzahl der zu exportierenden Dateien: {m} Create Text Text erstellen Create Trim Marks Schnittmarken erstellen Created Erstellt @@ -3988,6 +3995,7 @@ theme Appearance Erscheinungsbild @msg cannot split an open path at its end point ein offener Pfad kann nicht an seinem Endpunkt geteilt werden @msg closing needs three anchors zum Schließen sind drei Ankerpunkte nötig @msg check an asset to export markieren Sie ein Asset für den Export +@msg check an artboard to export markieren Sie eine Zeichenfläche für den Export @msg check a layer to export wählen Sie eine Ebene für den Export @msg select the art to export first wählen Sie zuerst das zu exportierende Bildmaterial aus @msg choice must be "merge" or "add", not `{choice}` choice muss "merge" oder "add" sein, nicht `{choice}` diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 5147b4fd94..c7c2ab8980 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -623,6 +623,13 @@ font-technology Variable Μεταβλητές Create Report Δημιουργία αναφοράς Create Slice Δημιουργία τομής Create Sub-folders Δημιουργία υποφακέλων + Clear Selection Απαλοιφή επιλογής + Export PDFs As: Εξαγωγή PDF ως: + Single File Ένα αρχείο + Multiple Files Πολλά αρχεία + Format Presets Προεπιλογές μορφής + Grid View Προβολή πλέγματος + Selected: {n}, Total number of files to export: {m} Επιλεγμένα: {n}, συνολικός αριθμός αρχείων για εξαγωγή: {m} Create Text Δημιουργία κειμένου Create Trim Marks Δημιουργία σημαδιών ξακρίσματος Created Δημιουργήθηκε @@ -4028,6 +4035,7 @@ theme Appearance Εμφάνιση @msg cannot split an open path at its end point δεν είναι δυνατή η διαίρεση ανοιχτής διαδρομής στο τελικό σημείο της @msg closing needs three anchors το κλείσιμο απαιτεί τρία σημεία αγκύρωσης @msg check an asset to export επιλέξτε στοιχείο για εξαγωγή +@msg check an artboard to export επιλέξτε πινακίδα σχεδίασης για εξαγωγή @msg check a layer to export επιλέξτε ένα επίπεδο για εξαγωγή @msg select the art to export first επιλέξτε πρώτα το γραφικό για εξαγωγή @msg choice must be "merge" or "add", not `{choice}` η επιλογή πρέπει να είναι "merge" ή "add", όχι `{choice}` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index bbd74c412b..b517c4c791 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -663,6 +663,13 @@ font-technology Variable Variables Create Report Crear informe Create Slice Crear sector Create Sub-folders Crear subcarpetas + Clear Selection Borrar selección + Export PDFs As: Exportar PDF como: + Single File Un solo archivo + Multiple Files Varios archivos + Format Presets Preajustes de formato + Grid View Vista de cuadrícula + Selected: {n}, Total number of files to export: {m} Seleccionados: {n}, número total de archivos para exportar: {m} Create Text Crear texto Create Trim Marks Crear marcas de recorte Created Creado @@ -4068,6 +4075,7 @@ axis Both Ambos @msg cannot split an open path at its end point no se puede dividir un trazado abierto en su punto final @msg closing needs three anchors cerrar necesita tres puntos de ancla @msg check an asset to export marca un recurso para exportar +@msg check an artboard to export marca una mesa de trabajo para exportar @msg check a layer to export marque una capa para exportar @msg select the art to export first seleccione primero la ilustración que desea exportar @msg choice must be "merge" or "add", not `{choice}` choice debe ser "merge" o "add", no `{choice}` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 27c96b5301..92f4e48945 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2213,6 +2213,13 @@ lighting Light Valo Use Artboards Käytä piirtoalustoja Choose a folder Valitse kansio Create Sub-folders Luo alikansiot + Clear Selection Tyhjennä valinta + Export PDFs As: Vie PDF-tiedostot muodossa: + Single File Yksi tiedosto + Multiple Files Useita tiedostoja + Format Presets Muotoesiasetukset + Grid View Ruudukkonäkymä + Selected: {n}, Total number of files to export: {m} Valittu: {n}, vietävien tiedostojen määrä yhteensä: {m} Export Asset Vie resurssi Export to: Vie kohteeseen: Format Settings Muotoasetukset @@ -4284,6 +4291,7 @@ imageTrace Outline Ääriviiva @msg cannot split an open path at its end point avointa polkua ei voi jakaa sen päätepisteestä @msg closing needs three anchors sulkeminen vaatii kolme ankkuria @msg check an asset to export valitse vietävä resurssi +@msg check an artboard to export valitse vietävä piirtoalue @msg check a layer to export valitse vietävä taso @msg select the art to export first valitse ensin vietävä kuvitus @msg choice must be "merge" or "add", not `{choice}` choice-arvon on oltava "merge" tai "add", ei `{choice}` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index bbcab564e8..27a2d52010 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -665,6 +665,13 @@ font-technology Variable Variables Create Report Créer un rapport Create Slice Créer une tranche Create Sub-folders Créer des sous-dossiers + Clear Selection Effacer la sélection + Export PDFs As: Exporter les PDF sous : + Single File Un seul fichier + Multiple Files Plusieurs fichiers + Format Presets Paramètres prédéfinis de format + Grid View Vue en grille + Selected: {n}, Total number of files to export: {m} Sélectionnés : {n}, nombre total de fichiers à exporter : {m} Create Text Créer du texte Create Trim Marks Créer des traits de coupe Created Création @@ -4065,6 +4072,7 @@ axis Both Les deux @msg cannot split an open path at its end point impossible de scinder un tracé ouvert à son extrémité @msg closing needs three anchors la fermeture nécessite trois points d’ancrage @msg check an asset to export cochez une ressource à exporter +@msg check an artboard to export cochez un plan de travail à exporter @msg check a layer to export cochez un calque à exporter @msg select the art to export first sélectionnez d’abord l’illustration à exporter @msg choice must be "merge" or "add", not `{choice}` choice doit valoir "merge" ou "add", pas `{choice}` diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index a17b4724fb..ec63473054 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -859,6 +859,13 @@ font-technology Variable Változó Create Report Jelentés készítése Create Slice Szelet létrehozása Create Sub-folders Almappák létrehozása + Clear Selection Kijelölés törlése + Export PDFs As: PDF-ek exportálása: + Single File Egy fájlba + Multiple Files Több fájlba + Format Presets Formátum-előbeállítások + Grid View Rácsnézet + Selected: {n}, Total number of files to export: {m} Kijelölve: {n}, exportálandó fájlok száma összesen: {m} Create Text Szöveg létrehozása Create Trim Marks Vágójelek létrehozása Create: Létrehozás: @@ -4624,6 +4631,7 @@ imageTrace Outline Körvonal @msg cannot read PDF: {0} a PDF nem olvasható: {0} @msg cannot split an open path at its end point nyitott útvonal a végpontjánál nem vágható ketté @msg check an asset to export jelölj be egy exportálandó elemet +@msg check an artboard to export jelölj be egy exportálandó rajztáblát @msg check a layer to export jelöljön be egy exportálandó réteget @msg select the art to export first először jelölje ki az exportálandó grafikát @msg choice must be "merge" or "add", not `{choice}` a choice értéke "merge" vagy "add" lehet, ez nem az: `{choice}` diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 85f09a6a6d..f958f41b14 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2061,6 +2061,13 @@ lighting Light Cahaya Use Artboards Gunakan artboard Choose a folder Pilih folder Create Sub-folders Buat subfolder + Clear Selection Hapus pilihan + Export PDFs As: Ekspor PDF sebagai: + Single File Satu file + Multiple Files Beberapa file + Format Presets Preset format + Grid View Tampilan kisi + Selected: {n}, Total number of files to export: {m} Dipilih: {n}, jumlah total file yang akan diekspor: {m} Export Asset Ekspor aset Export to: Ekspor ke: Format Settings Pengaturan format @@ -4067,6 +4074,7 @@ imageTrace Outline Kontur @msg cannot split an open path at its end point tidak dapat membelah jalur terbuka pada titik ujungnya @msg closing needs three anchors penutupan memerlukan tiga jangkar @msg check an asset to export centang aset yang akan diekspor +@msg check an artboard to export centang artboard yang akan diekspor @msg choice must be "merge" or "add", not `{choice}` choice harus "merge" atau "add", bukan `{choice}` @msg choose a direction to divide in pilih arah untuk membagi @msg choose a folder to export to pilih folder tujuan ekspor diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8be70bb1ff..a326cf55fb 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -663,6 +663,13 @@ font-technology Variable Variabili Create Report Crea rapporto Create Slice Crea sezione Create Sub-folders Crea sottocartelle + Clear Selection Cancella selezione + Export PDFs As: Esporta PDF come: + Single File File singolo + Multiple Files Più file + Format Presets Predefiniti formato + Grid View Vista griglia + Selected: {n}, Total number of files to export: {m} Selezionati: {n}, numero totale di file da esportare: {m} Create Text Crea testo Create Trim Marks Crea segni di taglio Created Creato @@ -4108,6 +4115,7 @@ axis Both Entrambi @msg cannot split an open path at its end point impossibile dividere un tracciato aperto nel suo punto finale @msg closing needs three anchors per chiudere servono tre punti di ancoraggio @msg check an asset to export spunta una risorsa da esportare +@msg check an artboard to export spunta una tavola da disegno da esportare @msg check a layer to export seleziona un livello da esportare @msg select the art to export first seleziona prima la grafica da esportare @msg choice must be "merge" or "add", not `{choice}` choice deve essere "merge" o "add", non `{choice}` diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c7acb2adf3..50afc7d72b 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1231,6 +1231,13 @@ font-technology Variable バリアブル Create Path パスを作成 Create Slice スライスを作成 Create Sub-folders サブフォルダーを作成 + Clear Selection 選択を解除 + Export PDFs As: PDF の書き出し形式: + Single File 単一ファイル + Multiple Files 複数ファイル + Format Presets 形式プリセット + Grid View グリッド表示 + Selected: {n}, Total number of files to export: {m} 選択済み:{n}、書き出すファイルの合計数:{m} Create Text テキストを作成 Created 作成日 Created: 作成日: @@ -4425,6 +4432,7 @@ swatch Bright Violet ビビッドバイオレット @msg nothing to export: the document has no visible art (or turn on Use Artboards) 書き出すものがありません: ドキュメントに表示されているアートがありません (または「アートボードを使用」をオンにしてください) @msg add a format to export 書き出す形式を追加してください @msg check an asset to export 書き出すアセットにチェックを入れてください +@msg check an artboard to export 書き出すアートボードにチェックを入れてください @msg check a layer to export 書き出すレイヤーにチェックを入れてください @msg select the art to export first 先に書き出すアートを選択してください @msg `{tool}` isn't a freehand tool `{tool}` はフリーハンドツールではありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 903d741c74..8b52357ad9 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1961,6 +1961,13 @@ lighting Light სინათლე Use Artboards სამუშაო დაფების გამოყენება Choose a folder საქაღალდის არჩევა Create Sub-folders ქვესაქაღალდეების შექმნა + Clear Selection მონიშვნის გასუფთავება + Export PDFs As: PDF-ების ექსპორტი როგორც: + Single File ერთი ფაილი + Multiple Files რამდენიმე ფაილი + Format Presets ფორმატის პრესეტები + Grid View ბადის ხედი + Selected: {n}, Total number of files to export: {m} არჩეულია: {n}, ექსპორტის ფაილების საერთო რაოდენობა: {m} Export Asset რესურსის ექსპორტირება Export to: ექსპორტის ადგილი: Format Settings ფორმატის პარამეტრები @@ -3851,6 +3858,7 @@ font-technology Variable ცვლადი @msg cannot split an open path at its end point ღია ტრაექტორიის ბოლო წერტილში გაყოფა შეუძლებელია @msg closing needs three anchors შეკვრას სამი საყრდენი წერტილი სჭირდება @msg check an asset to export მონიშნეთ ექსპორტის რესურსი +@msg check an artboard to export მონიშნეთ ექსპორტის სახატავი დაფა @msg choice must be "merge" or "add", not `{choice}` choice უნდა იყოს "merge" ან "add" და არა `{choice}` @msg choose a direction to divide in აირჩიეთ დაყოფის მიმართულება @msg choose a folder to export to აირჩიეთ ექსპორტის საქაღალდე diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 732af24f62..d1ebee17d3 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1222,6 +1222,13 @@ font-technology Variable 가변 Create Path 패스 만들기 Create Slice 슬라이스 만들기 Create Sub-folders 하위 폴더 만들기 + Clear Selection 선택 지우기 + Export PDFs As: PDF 내보내기 방식: + Single File 단일 파일 + Multiple Files 여러 파일 + Format Presets 형식 사전 설정 + Grid View 격자 보기 + Selected: {n}, Total number of files to export: {m} 선택됨: {n}, 내보낼 총 파일 수: {m} Create Text 텍스트 만들기 Created 만든 날짜 Created: 만든 날짜: @@ -4353,6 +4360,7 @@ theme Appearance 외관 @msg nothing to export: the document has no visible art (or turn on Use Artboards) 내보낼 항목이 없습니다: 문서에 보이는 아트웍이 없습니다(또는 아트보드 사용을 켜세요) @msg add a format to export 내보낼 형식을 추가하세요 @msg check an asset to export 내보낼 자산을 체크하세요 +@msg check an artboard to export 내보낼 대지를 체크하세요 @msg check a layer to export 내보낼 레이어를 선택하십시오 @msg select the art to export first 먼저 내보낼 아트를 선택하십시오 @msg `{tool}` isn't a freehand tool `{tool}`은(는) 프리핸드 도구가 아닙니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index effdca022d..334707edc5 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2075,6 +2075,13 @@ lighting Light Licht Use Artboards Tekenborden gebruiken Choose a folder Kies een map Create Sub-folders Submappen maken + Clear Selection Selectie wissen + Export PDFs As: PDF's exporteren als: + Single File Eén bestand + Multiple Files Meerdere bestanden + Format Presets Indelingsvoorinstellingen + Grid View Rasterweergave + Selected: {n}, Total number of files to export: {m} Geselecteerd: {n}, totaal aantal te exporteren bestanden: {m} Export Asset Asset exporteren Export to: Exporteren naar: Format Settings Indelingsinstellingen @@ -4081,6 +4088,7 @@ imageTrace Outline Contour @msg cannot split an open path at its end point kan een open pad niet splitsen op zijn eindpunt @msg closing needs three anchors voor sluiten zijn drie ankers nodig @msg check an asset to export vink een asset aan om te exporteren +@msg check an artboard to export vink een tekengebied aan om te exporteren @msg choice must be "merge" or "add", not `{choice}` choice moet "merge" of "add" zijn, niet `{choice}` @msg choose a direction to divide in kies een richting om in te verdelen @msg choose a folder to export to kies een map om naar te exporteren diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 6be694f622..49d549c17b 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2174,6 +2174,13 @@ lighting Light Światło Use Artboards Użyj obszarów kompozycji Choose a folder Wybierz folder Create Sub-folders Utwórz podfoldery + Clear Selection Wyczyść zaznaczenie + Export PDFs As: Eksportuj pliki PDF jako: + Single File Jeden plik + Multiple Files Wiele plików + Format Presets Ustawienia formatów + Grid View Widok siatki + Selected: {n}, Total number of files to export: {m} Zaznaczono: {n}, łączna liczba plików do eksportu: {m} Export Asset Eksportuj zasób Export to: Eksportuj do: Format Settings Ustawienia formatu @@ -4199,6 +4206,7 @@ imageTrace Outline Kontur @msg cannot split an open path at its end point nie można podzielić otwartej ścieżki w jej punkcie końcowym @msg closing needs three anchors zamknięcie wymaga trzech punktów @msg check an asset to export zaznacz zasób do eksportu +@msg check an artboard to export zaznacz obszar kompozycji do eksportu @msg check a layer to export zaznacz warstwę do eksportu @msg select the art to export first najpierw zaznacz grafikę do eksportu @msg choice must be "merge" or "add", not `{choice}` wybór musi mieć wartość "merge" lub "add", nie `{choice}` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 5fe9922eda..26d60b4234 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -585,6 +585,13 @@ Create Path Criar Caminho Create Slice Criar Fatia Create Sub-folders Criar Subpastas + Clear Selection Limpar Seleção + Export PDFs As: Exportar PDFs Como: + Single File Arquivo Único + Multiple Files Vários Arquivos + Format Presets Predefinições de Formato + Grid View Exibição em Grade + Selected: {n}, Total number of files to export: {m} Selecionados: {n}, número total de arquivos a exportar: {m} Create Text Criar Texto Create Trim Marks Criar Marcas de Corte Create from Guides Criar a partir de Guias @@ -3646,6 +3653,7 @@ axis Both Ambos @msg cannot split an open path at its end point não é possível dividir um traçado aberto em sua extremidade @msg closing needs three anchors fechar exige três âncoras @msg check an asset to export marque um recurso para exportar +@msg check an artboard to export marque uma prancheta para exportar @msg check a layer to export marque uma camada para exportar @msg select the art to export first selecione primeiro a arte a exportar @msg choice must be "merge" or "add", not `{choice}` choice deve ser "merge" ou "add", não `{choice}` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index bd4faa713d..2fec550643 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -661,6 +661,13 @@ font-technology Variable Вариативные Create Report Создать отчёт Create Slice Создать фрагмент Create Sub-folders Создать вложенные папки + Clear Selection Снять выделение + Export PDFs As: Экспортировать PDF как: + Single File Один файл + Multiple Files Несколько файлов + Format Presets Наборы форматов + Grid View Сетка + Selected: {n}, Total number of files to export: {m} Выбрано: {n}, всего файлов для экспорта: {m} Create Text Создать текст Create Trim Marks Создать метки подрезки Created Создано @@ -4104,6 +4111,7 @@ axis Both Оба @msg cannot split an open path at its end point нельзя разделить открытый контур в его конечной точке @msg closing needs three anchors для замыкания нужны три опорные точки @msg check an asset to export отметьте ресурс для экспорта +@msg check an artboard to export отметьте монтажную область для экспорта @msg check a layer to export отметьте слой для экспорта @msg select the art to export first сначала выделите объекты для экспорта @msg choice must be "merge" or "add", not `{choice}` choice должно быть "merge" или "add", а не `{choice}` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 273720935b..fd253ed7a9 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -651,6 +651,13 @@ font-technology Variable Variabla Create Report Skapa rapport Create Slice Skapa skiva Create Sub-folders Skapa undermappar + Clear Selection Rensa markering + Export PDFs As: Exportera PDF-filer som: + Single File En fil + Multiple Files Flera filer + Format Presets Formatförinställningar + Grid View Rutnätsvy + Selected: {n}, Total number of files to export: {m} Markerade: {n}, totalt antal filer att exportera: {m} Create Text Skapa text Create Trim Marks Skapa skärmärken Created Skapad @@ -3979,6 +3986,7 @@ axis Both Båda @msg cannot split an open path at its end point kan inte dela en öppen bana vid dess slutpunkt @msg closing needs three anchors att sluta banan kräver tre ankarpunkter @msg check an asset to export kryssa för en resurs att exportera +@msg check an artboard to export kryssa för en rityta att exportera @msg check a layer to export markera ett lager att exportera @msg select the art to export first markera först teckningen som ska exporteras @msg choice must be "merge" or "add", not `{choice}` choice måste vara "merge" eller "add", inte `{choice}` diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 180f3448da..849c9c74f5 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -643,6 +643,13 @@ font-technology Variable Değişken Create Report Rapor Oluştur Create Slice Dilim Oluştur Create Sub-folders Alt Klasörler Oluşturun + Clear Selection Seçimi Temizle + Export PDFs As: PDF'leri Şu Şekilde Dışa Aktar: + Single File Tek Dosya + Multiple Files Birden Fazla Dosya + Format Presets Biçim Ön Ayarları + Grid View Izgara Görünümü + Selected: {n}, Total number of files to export: {m} Seçilen: {n}, dışa aktarılacak toplam dosya sayısı: {m} Create Text Metin Oluştur Create Trim Marks Kesim İşaretleri Oluşturun Created Oluşturuldu @@ -3848,6 +3855,7 @@ axis Both Her İkisi @msg cannot split an open path at its end point açık bir yolu bitiş noktasında bölemez @msg closing needs three anchors Kapanış üç çapaya ihtiyaç duyar @msg check an asset to export dışa aktarılacak bir varlığı kontrol etme +@msg check an artboard to export dışa aktarılacak bir çalışma yüzeyi işaretleyin @msg check a layer to export dışa aktarılacak katmanı kontrol edin @msg select the art to export first önce dışa aktarılacak resmi seçin @msg choice must be "merge" or "add", not `{choice}` seçim "{choice}" değil "birleştir" veya "ekle" olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 4d267593f6..9f06a0f787 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -657,6 +657,13 @@ font-technology Variable Варіативні Create Report Створити звіт Create Slice Створити фрагмент Create Sub-folders Створити вкладені папки + Clear Selection Зняти виділення + Export PDFs As: Експортувати PDF як: + Single File Один файл + Multiple Files Кілька файлів + Format Presets Набори форматів + Grid View Сітка + Selected: {n}, Total number of files to export: {m} Вибрано: {n}, усього файлів для експорту: {m} Create Text Створити текст Create Trim Marks Створити мітки підрізування Created Створено @@ -4092,6 +4099,7 @@ axis Both Обидві @msg cannot split an open path at its end point не можна розділити відкритий контур у його кінцевій точці @msg closing needs three anchors для замикання потрібні три опорні точки @msg check an asset to export позначте ресурс для експорту +@msg check an artboard to export позначте монтажну область для експорту @msg check a layer to export позначте шар для експорту @msg select the art to export first спочатку виділіть об’єкти для експорту @msg choice must be "merge" or "add", not `{choice}` choice має бути "merge" або "add", а не `{choice}` diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 67169df4de..814b2bd0d8 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -760,6 +760,13 @@ font-technology Variable Biến thiên Create Report Tạo báo cáo Create Slice Tạo lát cắt Create Sub-folders Tạo thư mục con + Clear Selection Xóa lựa chọn + Export PDFs As: Xuất PDF dưới dạng: + Single File Một tệp + Multiple Files Nhiều tệp + Format Presets Thiết lập sẵn định dạng + Grid View Chế độ lưới + Selected: {n}, Total number of files to export: {m} Đã chọn: {n}, tổng số tệp sẽ xuất: {m} Create Text Tạo văn bản Create Trim Marks Tạo dấu cắt xén Create: Tạo: @@ -4274,6 +4281,7 @@ theme Appearance Giao diện @msg cannot read PDF: {0} không thể đọc PDF: {0} @msg cannot split an open path at its end point không thể tách đường dẫn mở tại điểm cuối @msg check an asset to export hãy chọn một asset để xuất +@msg check an artboard to export hãy chọn một bảng vẽ để xuất @msg check a layer to export hãy đánh dấu một lớp để xuất @msg select the art to export first hãy chọn hình cần xuất trước @msg choice must be "merge" or "add", not `{choice}` lựa chọn phải là "merge" hoặc "add", không phải `{choice}` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 6da63132e7..8fa91dcae0 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -608,6 +608,13 @@ Create Report 创建报告 Create Slice 创建切片 Create Sub-folders 创建子文件夹 + Clear Selection 清除选择 + Export PDFs As: PDF 导出为: + Single File 单个文件 + Multiple Files 多个文件 + Format Presets 格式预设 + Grid View 网格视图 + Selected: {n}, Total number of files to export: {m} 已选择:{n},要导出的文件总数:{m} Create Text 创建文字 Create Trim Marks 创建裁切标记 Created 创建时间 @@ -4148,6 +4155,7 @@ imageTrace Outline 轮廓 @msg nothing to export: the document has no visible art (or turn on Use Artboards) 没有可导出的内容:文档中没有可见的图稿 (或请打开“使用画板”) @msg add a format to export 请添加要导出的格式 @msg check an asset to export 请勾选要导出的资源 +@msg check an artboard to export 请勾选要导出的画板 @msg `{tool}` isn't a freehand tool `{tool}` 不是手绘工具 @msg bad colour `{hex}` (#rrggbb) 颜色 `{hex}` 无效 (#rrggbb) @msg no gradient stop or freeform point is selected 未选择渐变色标或任意形状点 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 7e21abda50..8525483188 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -625,6 +625,13 @@ font-technology Variable 可變 Create Report 建立報告 Create Slice 建立切片 Create Sub-folders 建立子資料夾 + Clear Selection 清除選取 + Export PDFs As: PDF 轉存為: + Single File 單一檔案 + Multiple Files 多個檔案 + Format Presets 格式預設集 + Grid View 格點檢視 + Selected: {n}, Total number of files to export: {m} 已選取:{n},要轉存的檔案總數:{m} Create Text 建立文字 Create Trim Marks 建立剪裁標記 Created 建立時間 @@ -2088,6 +2095,7 @@ file-filter Templates 範本 @msg nothing to export: the document has no visible art (or turn on Use Artboards) 沒有可匯出的內容:文件中沒有可見的圖稿 (或請開啟「使用工作區域」) @msg add a format to export 請新增要匯出的格式 @msg check an asset to export 請勾選要匯出的資產 +@msg check an artboard to export 請勾選要匯出的工作區域 @msg `{tool}` isn't a freehand tool `{tool}` 不是手繪工具 @msg bad colour `{hex}` (#rrggbb) 顏色 `{hex}` 無效 (#rrggbb) @msg no gradient stop or freeform point is selected 未選取漸層色標或任意形狀點 diff --git a/crates/ui-egui/src/io/export.rs b/crates/ui-egui/src/io/export.rs index d7bb709771..9e463f49e9 100644 --- a/crates/ui-egui/src/io/export.rs +++ b/crates/ui-egui/src/io/export.rs @@ -285,6 +285,8 @@ fn report_exported(app: &mut VectorcraftApp, r: Value, folder: &str, open_locati } app.status(status); } else if let Some(download) = app.services.download.as_mut() { + // A browser download has no folders: a file from a sub-folder (`2x/Logo@2x.png`) is named alone. + let returned: Vec<(&str, &str)> = returned.iter().map(|(name, data)| (name.rsplit('/').next().unwrap_or(name), *data)).collect(); for (name, data) in &returned { let bytes = vectorcraft_format::base64_decode(data).ok_or("the export returned unreadable data")?; download(name, &bytes)?; diff --git a/crates/ui-egui/src/panels/asset_export.rs b/crates/ui-egui/src/panels/asset_export.rs index 3cc81fce7d..b9b620ac0f 100644 --- a/crates/ui-egui/src/panels/asset_export.rs +++ b/crates/ui-egui/src/panels/asset_export.rs @@ -263,7 +263,7 @@ fn settings(ui: &mut Ui, st: &DocState) -> (Option<Settings>, usize) { let preset = preset.unwrap_or_default().to_string(); let n = rows.len(); let mut d = Dialog::new(EXPORT_FOR_SCREENS, json!({ "formats": &rows, "preset": preset, "__settings": "" })); - screen_formats(ui, &mut d); + screen_formats(ui, &mut d, None); let (shown, picked) = (d.str("__settings"), d.str("preset")); let formats = d.fields.remove("formats").unwrap_or(Value::Null); let change = if !shown.is_empty() { diff --git a/crates/ui-egui/src/panels/tests_asset_export.rs b/crates/ui-egui/src/panels/tests_asset_export.rs index b3d29e2f4c..aac9cabc1d 100644 --- a/crates/ui-egui/src/panels/tests_asset_export.rs +++ b/crates/ui-egui/src/panels/tests_asset_export.rs @@ -209,7 +209,7 @@ fn the_rows_are_the_shared_export_settings() { // A preset set by an agent shows as its rows. app.run("assets.settings.set", json!({"preset": "mobile"})).unwrap(); let texts = frame(&ctx, &mut app, vec![], false); - assert!(has(&texts, "Mobile 1x/2x/3x") && has(&texts, "@3x")); + assert!(has(&texts, "iOS") && has(&texts, "@3x")); // Export (nothing selected: every asset) downloads one zip on the web. let texts = frame(&ctx, &mut app, vec![], false); frame(&ctx, &mut app, click(at(&texts, "Export")), false); From 46e165731c7b9a24320e8f9fb47e057ab757bfbc Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 21:41:10 +0700 Subject: [PATCH 087/260] Docs: Export for Screens laid out as Illustrator's --- docs/target-app-parity.md | 5 +++-- docs/ui-parity.md | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8d930ef07e..38d9ba8b6b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Artwork Cleanup add-on: Join Point Text, #4826; scores unchanged; previously: G13: Direct Selection snaps a dragged line end square to straight paths and grazing curves; Path Precision Tools add-on: Shared Edge Merge Tool; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Export for Screens laid out as Illustrator's, with Export PDFs As and sub-folders by scale or format; previously: Artwork Cleanup add-on: Join Point Text, #4826; scores unchanged; previously: G13: Direct Selection snaps a dragged line end square to straight paths and grazing curves; Path Precision Tools add-on: Shared Edge Merge Tool; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -19,6 +19,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Export for Screens is laid out as Illustrator's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged. | | 2026-10-31 | minor | Artwork Cleanup add-on: Join Point Text (`addon.cleanup.joinText`) joins stacked one-line point type into one object, a paragraph per line keeping its baseline (#4826); scores unchanged. | | 2026-10-31 | minor | Width tool: a stroke with a width profile keeps its shape while the view zooms out; the minimum visible width goes to its widest point instead of scaling the whole profile (#995); scores unchanged. | | 2026-10-31 | minor | Patterns: Grid Repeat Options has a Preview checkbox, as the public grid options page lists (#2651); scores unchanged. | @@ -542,7 +543,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Batch…: Override Save and Override Export name each file with the extension of the format the step writes, however the step spells the format (`.svg` and `SVG` give `.svg`, `png8` gives `.png`), in `action.batch`. - Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. - - Export for Screens: the dialog's Example line shows the path of the file the export writes first, sub-folder included, named as the export names it, for the first chosen artboard, asset, layer or object (`document.exportForScreens`). + - Export for Screens is laid out as Illustrator's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`. - Save for Web: Preview in Browser writes each preview's page and images to a folder of its own inside `VectorCraft Save for Web` in the system's temporary folder. A later preview, from the same app or another one running, does not overwrite an earlier one. Each preview first removes the preview folders there that are an hour old or older and, on Linux, macOS and FreeBSD, belong to the current user; it leaves other files and folders alone. The folders a preview makes there are open to their owner only on those systems. When `VectorCraft Save for Web` is a link or is not a folder, or on those systems belongs to another user or can be written by other users, the preview goes to a new folder of its own in the temporary folder, which a later preview removes once it is an hour old (`file.saveForWeb.browser`). - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). - Variables (data merge): text, visibility and image variables bound to objects (an object may carry several), dataset rows applied in one undo step (`variable.*`, `dataset.*`) from a Variables panel and Window › Variables, with dialogs to define, bind and edit, Make Text/Visibility/Image Dynamic, Capture/Update Data Set, CSV import/export (`dataset.import` / `dataset.export`), and a row in italics when an edit leaves the art not matching it; an image dataset value is a file path and apply keeps the object's bounds; bindings let go of deleted art and locked art is left alone; every command, like the rest, is drivable over MCP and the CLI. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f32db08429..afd2fac04d 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Properties: Blend Options in Quick Actions for one selected blend with any tool, #4817; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Export for Screens laid out as Illustrator's; previously: Properties: Blend Options in Quick Actions for one selected blend with any tool, #4817; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -376,6 +376,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Export for Screens is laid out as Illustrator's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged | | 2026-10-31 | minor | Properties: Quick Actions has Blend Options for one selected blend with any tool, not only the Blend tool, as the blending page describes (#4817); scores unchanged | | 2026-10-31 | minor | Smart guides and snapping: Snap to Perpendicular and Snap to Tangent for an existing line's end dragged with Direct Selection (#2530), so the tangent and perpendicular row is done; scores and estimates unchanged | | 2026-10-31 | minor | Grid Repeat Options has a Preview checkbox (#2651); scores and estimates unchanged | From ca0785573d22231a0530602bf33dbeeea08ae485 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 19:24:09 +0700 Subject: [PATCH 088/260] =?UTF-8?q?Add-ons:=20Arrange=20Tools=20=E2=80=94?= =?UTF-8?q?=20Arrange=20in=20Grid,=20Swap,=20Replace=20with=20Top=20Object?= =?UTF-8?q?,=20Set=20Size=20of=20Each,=20Zoom=20to=20Selection?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A built-in add-on in Object › Plug-ins › Arrange Tools (#4830, #4831, #4832, #4833, #4834): - addon.arrange.grid lays the top-level selected objects out in rows and columns, a row or a column (stacking order from the back, visual bounds, each object centred in its cell), from the selection's top-left or centred on the artboard. - addon.arrange.swap swaps two objects' bounds centres, and with `size` their widths and heights. - addon.arrange.replace puts a copy of the topmost selected object centred on each of the others, in its stacking place, kept, stretched or fitted in proportion; the replaced objects are deleted unless `keep`. - addon.arrange.size gives each selected object an exact width and/or height about a reference point. - addon.arrange.zoomSelection (a UI command) fits the active view to the selection. Places and sizes are measured as object.setBounds measures them (its transform, now also available per object), strokes scale as Scale Strokes & Effects says, each command is one undo step, and Arrange in Grid, Replace with Top Object and Set Size of Each open previewed dialogs. Catalog rows, command sweep cases, docs/mcp.md, parity docs and the ROADMAP progress log. --- ROADMAP.md | 4 +- crates/engine/src/cmd/addons.rs | 4 +- crates/engine/src/cmd/addons/arrange.rs | 272 ++++++++++++++++++ crates/engine/src/cmd/addons/arrange/tests.rs | 263 +++++++++++++++++ crates/engine/src/cmd/object.rs | 2 +- crates/engine/src/cmd/object/bounds.rs | 22 +- crates/engine/tests/command_sweep.rs | 9 + crates/ui-egui/src/addons.rs | 2 + crates/ui-egui/src/addons/arrange.rs | 175 +++++++++++ crates/ui-egui/src/addons/arrange/tests.rs | 127 ++++++++ crates/ui-egui/src/canvas/view.rs | 3 +- crates/ui-egui/src/dialogs.rs | 3 +- crates/ui-egui/src/dialogs/form.rs | 12 +- crates/ui-egui/src/i18n/bg.tsv | 12 + crates/ui-egui/src/i18n/bs.tsv | 12 + crates/ui-egui/src/i18n/ca.tsv | 12 + crates/ui-egui/src/i18n/cs.tsv | 12 + crates/ui-egui/src/i18n/da.tsv | 12 + crates/ui-egui/src/i18n/de.tsv | 12 + crates/ui-egui/src/i18n/el.tsv | 12 + crates/ui-egui/src/i18n/es.tsv | 12 + crates/ui-egui/src/i18n/fi.tsv | 12 + crates/ui-egui/src/i18n/fr.tsv | 12 + crates/ui-egui/src/i18n/hu.tsv | 12 + crates/ui-egui/src/i18n/id.tsv | 12 + crates/ui-egui/src/i18n/it.tsv | 12 + crates/ui-egui/src/i18n/ja.tsv | 12 + crates/ui-egui/src/i18n/ka.tsv | 12 + crates/ui-egui/src/i18n/ko.tsv | 12 + crates/ui-egui/src/i18n/nl.tsv | 12 + crates/ui-egui/src/i18n/pl.tsv | 12 + crates/ui-egui/src/i18n/pt-br.tsv | 12 + crates/ui-egui/src/i18n/ru.tsv | 12 + crates/ui-egui/src/i18n/sv.tsv | 12 + crates/ui-egui/src/i18n/tr.tsv | 12 + crates/ui-egui/src/i18n/uk.tsv | 12 + crates/ui-egui/src/i18n/vi.tsv | 12 + crates/ui-egui/src/i18n/zh-hans.tsv | 12 + crates/ui-egui/src/i18n/zh-hant.tsv | 12 + crates/ui-egui/src/menus/invoke.rs | 3 + crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/state.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 8 +- docs/mcp.md | 26 ++ docs/target-app-parity.md | 29 +- docs/ui-parity.md | 24 +- 46 files changed, 1269 insertions(+), 34 deletions(-) create mode 100644 crates/engine/src/cmd/addons/arrange.rs create mode 100644 crates/engine/src/cmd/addons/arrange/tests.rs create mode 100644 crates/ui-egui/src/addons/arrange.rs create mode 100644 crates/ui-egui/src/addons/arrange/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index e7d8f0bbad..515e2824d6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -9,7 +9,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (OpenType SVG colour fonts draw and export as vector art; previously: COLR colour fonts (v0 and v1) draw and export as vector art; previously: G2: the Effect Gallery shipped (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step; remaining: filter thumbnails and a preview area inside the dialog; G2 estimate 4–6 → 1–2 h; Raster effects 82% → 85% (power-user view 49% → 52%), estimated, a modest move because the named missing dialog landed without thumbnails or an in-dialog preview; previously: colour emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; headline numbers unchanged; previously:; Affinity import AF.5: master pages, tables, paragraph formats, shadows, glows, outlines, overlays and embedded documents; ruby (ふりがな) for live text: `type.ruby` sets or removes a reading over a byte range, above or below (right of the column in vertical type), aligned, sized and overhanging or squeezed; saved natively, laid out with line growth, drawn on the canvas and in SVG/PDF (outlines where ruby is present); headline numbers unchanged; previously:; 3D: original Standard, Diffuse, Top Left and Right lighting presets; command access, effective-setting recognition and preview/history; scores and estimates unchanged; Print: Japanese paper sizes in the Print dialog's Media list — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (which keep their ISO 216 sizes), はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判; about 90 community PRs of 2026-10-19: Objects on Path, the Simplify slider, Pencil Edit Selected Paths in the middle of a path, Georgian, and more; Background Export progress dialog with Cancel, #2564; about 85 community PRs of 2026-10-18: Justification…, Word .docx placed as area type, CCITT Group 3 TIFF, Roman Hanging Punctuation, blend spines edited with the Anchor Point tool, shadows and glows in stack order, coloured 3D lights, a Dutch catalog completed; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; about 145 community PRs of 2026-10-17: image-decode overflow guards, opaque floating panels, MCP export cancel and progress, editable Illustrator EPS import, scoped `doc_inspect`, Dutch, Danish and Indonesian, Simplified Chinese messages, screen-reader names; headline numbers unchanged; about 160 community PRs of 2026-10-15/16: PDF import crash fixes, Dimension tool, legacy `.ai` save, Intertwine, web pen input, Image Trace fixes, `.ai`/EPS/PDF import fidelity, Bulgarian, Greek, Swedish and Finnish catalogs; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Arrange Tools add-on: Arrange in Grid, Swap Objects, Replace with Top Object, Set Size of Each and Zoom to Selection; headline numbers unchanged; previously: OpenType SVG colour fonts draw and export as vector art; previously: COLR colour fonts (v0 and v1) draw and export as vector art; previously: G2: the Effect Gallery shipped (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step; remaining: filter thumbnails and a preview area inside the dialog; G2 estimate 4–6 → 1–2 h; Raster effects 82% → 85% (power-user view 49% → 52%), estimated, a modest move because the named missing dialog landed without thumbnails or an in-dialog preview; previously: colour emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; headline numbers unchanged; previously:; Affinity import AF.5: master pages, tables, paragraph formats, shadows, glows, outlines, overlays and embedded documents; ruby (ふりがな) for live text: `type.ruby` sets or removes a reading over a byte range, above or below (right of the column in vertical type), aligned, sized and overhanging or squeezed; saved natively, laid out with line growth, drawn on the canvas and in SVG/PDF (outlines where ruby is present); headline numbers unchanged; previously:; 3D: original Standard, Diffuse, Top Left and Right lighting presets; command access, effective-setting recognition and preview/history; scores and estimates unchanged; Print: Japanese paper sizes in the Print dialog's Media list — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (which keep their ISO 216 sizes), はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判; about 90 community PRs of 2026-10-19: Objects on Path, the Simplify slider, Pencil Edit Selected Paths in the middle of a path, Georgian, and more; Background Export progress dialog with Cancel, #2564; about 85 community PRs of 2026-10-18: Justification…, Word .docx placed as area type, CCITT Group 3 TIFF, Roman Hanging Punctuation, blend spines edited with the Anchor Point tool, shadows and glows in stack order, coloured 3D lights, a Dutch catalog completed; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; about 145 community PRs of 2026-10-17: image-decode overflow guards, opaque floating panels, MCP export cancel and progress, editable Illustrator EPS import, scoped `doc_inspect`, Dutch, Danish and Indonesian, Simplified Chinese messages, screen-reader names; headline numbers unchanged; about 160 community PRs of 2026-10-15/16: PDF import crash fixes, Dimension tool, legacy `.ai` save, Intertwine, web pen input, Image Trace fixes, `.ai`/EPS/PDF import fidelity, Bulgarian, Greek, Swedish and Finnish catalogs; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged. - 2026-10-30: Gradient panel presets: a Presets menu applies one of the built-in gradient libraries' presets (grouped by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the current gradient as a preset, kept with the preferences, and deletes saved ones (`gradient.presets.list/apply/save/delete`). - 2026-10-23: Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add a thin overprinting strip of the lighter colour inside the darker one where two solid colours meet, so misregistered plates leave no gap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)), with Thickness, Height/Width, Tint Reduction, Traps with Process Color and Reverse Traps. Illustrator effects 49/50 (SVG Filters remains); Live vector effects hours 6–10 → 4–8; headline numbers unchanged. - 2026-10-23: OpenType SVG colour fonts draw as vector art: each glyph's SVG document is read by the SVG importer, in the text's colours where it asks for them, and draws, exports and outlines as COLR glyphs do; all colour font formats are now drawn. @@ -202,6 +203,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Progress log row for the Arrange Tools add-on; headline numbers unchanged. | | 2026-10-29 | minor | Progress log row for the Linux Flatpak clipboard's core Wayland protocol text fallback; headline numbers unchanged. | | 2026-10-29 | minor | Progress log row for the Linux clipboard retry backoff; headline numbers unchanged. | | 2026-10-23 | minor | Progress log row for Pathfinder › Trap; Live vector effects hours 6–10 → 4–8; headline numbers unchanged. | diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index ca6625540e..2e153491b1 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -1,6 +1,7 @@ //! VectorCraft's built-in add-ons: extra tools beyond the standard menus, each a module of its own //! with commands under `addon.<name>.*` (see `docs/mcp.md`). +mod arrange; mod cleanup; mod color; mod pathtools; @@ -10,7 +11,8 @@ use super::CommandSpec; /// The commands of every built-in add-on. pub fn specs() -> Vec<CommandSpec> { - let mut v = cleanup::specs(); + let mut v = arrange::specs(); + v.extend(cleanup::specs()); v.extend(color::specs()); v.extend(pathtools::specs()); v.extend(pen::specs()); diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs new file mode 100644 index 0000000000..2011559c3b --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -0,0 +1,272 @@ +//! Arrange Tools (`addon.arrange.*`), a built-in add-on: Arrange in Grid lays the selected objects +//! out in rows and columns, a row or a column; Swap Objects swaps the places (and sizes) of two; +//! Replace with Top Object puts a copy of the topmost selected object in place of each of the +//! others; and Set Size of Each gives every selected object an exact width and height. Places and +//! sizes are measured and set as `object.setBounds` does. Its submenu (Object › Plug-ins › Arrange +//! Tools), its dialogs and Zoom to Selection (a view command) are the UI's. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, OrientedBox}; +use vectorcraft_geom::{Affine, Point, Rect}; +use vectorcraft_render::effects; + +use super::super::edit::selected_roots; +use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns}; +use super::super::typecmd::refresh_bounds_of; +use super::super::{CommandSpec, bad, cmd, has_doc, has_multi, has_selection, number_or, switch_or}; +use crate::{EngineError, Result, Session}; + +/// The largest gap, width or height (pt) the commands take. +const LIMIT: f64 = 1e6; +/// The smallest width or height (pt) Set Size of Each takes. +const LEAST: f64 = 0.001; +/// The most columns Arrange in Grid takes. +const MAX_COLUMNS: u64 = 10_000; + +pub fn specs() -> Vec<CommandSpec> { + vec![ + cmd!( + "addon.arrange.grid", + "Arrange in Grid", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{layout?: \"grid\" (rows and columns) | \"row\" (one row) | \"column\" (one column), columns?: 1..10000 (grid; default ⌈√count⌉; never more than the count), gapX?: pt −1000000..1000000 (10), gapY?: pt −1000000..1000000 (gapX), centerOnArtboard?: false (true: the grid is centred on the artboard under the selection's centre, else the first; false: it starts at the selection's top-left)} lay the selected objects (the top-level ones) out in their stacking order from the back, left to right and top to bottom, as one undo step. Each cell is as wide as the widest object in its column and as tall as the tallest in its row, each object is centred in its cell, and everything is measured by visual bounds (strokes and effects as drawn) → {count}", + has_selection, + grid + ), + cmd!( + "addon.arrange.swap", + "Swap Objects", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{size?: false (true: each also takes the other's width and height), scaleStrokes?: the Scale Strokes & Effects preference} swap the places (bounds centres) of the two selected objects, measured as object.setBounds measures them (Use Preview Bounds), as one undo step. Off unless exactly two objects are selected", + exactly_two, + swap + ), + cmd!( + "addon.arrange.replace", + "Replace with Top Object", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{fit?: \"keep\" (the copy keeps its size) | \"bounds\" (scaled to the replaced object's width and height) | \"proportional\" (scaled to fit inside them, in proportion) (\"keep\"), scaleStrokes?: the Scale Strokes & Effects preference, keep?: false (true: the replaced objects stay, under their copies)} put a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order, as one undo step; sizes and centres are measured as object.setBounds measures them, and the copies are selected → {ids}", + has_multi, + replace + ), + cmd!( + "addon.arrange.size", + "Set Size of Each", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{width?: pt, height?: pt (at least one; each 0.001..1000000), proportional?: false (with only one of them given, the other follows in proportion; else it stays), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the centre: the point of each object that stays put), scaleStrokes?: the Scale Strokes & Effects preference} give each selected object (the top-level ones) that width and height, measured as object.setBounds measures them (Use Preview Bounds), as one undo step → {count}", + has_selection, + size + ), + ] +} + +/// Exactly two objects are selected (Swap Objects). +fn exactly_two(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + let n = selected_roots(s).map_err(|e| e.to_string())?.len(); + if n == 2 { Ok(()) } else { Err("select exactly two objects".into()) } +} + +/// Number param `key` (`default` when left out) within `lo..=hi`. +fn number_in(p: &Value, key: &str, default: f64, (lo, hi): (f64, f64), cmd: &str) -> Result<f64> { + let v = number_or(p, key, default, cmd)?; + if (lo..=hi).contains(&v) { Ok(v) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } +} + +/// Whole-number param `key` within `lo..=hi`, `None` when left out. +fn whole_in(p: &Value, key: &str, (lo, hi): (u64, u64), cmd: &str) -> Result<Option<u64>> { + let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) }; + let n = v.as_u64().ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number")))?; + if (lo..=hi).contains(&n) { Ok(Some(n)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } +} + +/// A width or height param of Set Size of Each, `None` when left out. +fn size_param(p: &Value, key: &str, cmd: &str) -> Result<Option<f64>> { + p.get(key).filter(|v| !v.is_null()).map(|_| number_in(p, key, 0.0, (LEAST, LIMIT), cmd)).transpose() +} + +/// `object.setBounds` params that centre an object on `at`, with Scale Strokes & Effects `strokes` +/// and, when given, a width and height. +fn place(at: Point, size: Option<(f64, f64)>, strokes: bool) -> Value { + let mut q = json!({ "x": at.x, "y": at.y, "reference": 4, "strokes": strokes }); + if let Some((w, h)) = size { + q["width"] = json!(w); + q["height"] = json!(h); + } + q +} + +/// Transform each object of `xfs` by its own transform as undo step `label`, strokes and effects +/// scaling with Scale Strokes & Effects `strokes`, pattern tiles as Transform Pattern Tiles says. +/// When every transform is (within rounding) the identity, nothing changes. +fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, Affine)]) -> Result<()> { + let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9); + if xfs.iter().all(|(_, xf)| still(xf)) { + return Ok(()); + } + let p = json!({ "strokes": strokes }); + let ids: Vec<NodeId> = xfs.iter().map(|(id, _)| *id).collect(); + let mut sc = scaling(s, &p); + sc.patterns = transform_patterns(s, &p, &ids)?; + s.edit(label, |d, _| { + for (id, xf) in xfs { + if let Some(n) = d.node_mut(*id) { + transform_node(n, *xf, sc, true); + } + } + Ok(()) + }) +} + +/// The box of object `id` as `object.setBounds` measures it. +fn box_of(s: &Session, id: NodeId) -> Result<OrientedBox> { + s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into())) +} + +fn grid(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "addon.arrange.grid"; + let layout = choice(p, C, "layout", &["grid", "row", "column"])?.unwrap_or("grid"); + let columns = whole_in(p, "columns", (1, MAX_COLUMNS), C)?; + let gap_x = number_in(p, "gapX", 10.0, (-LIMIT, LIMIT), C)?; + let gap_y = number_in(p, "gapY", gap_x, (-LIMIT, LIMIT), C)?; + let center = switch_or(p, "centerOnArtboard", false, C)?; + let roots = selected_roots(s)?; + let d = &s.doc()?.doc; + let items: Vec<(NodeId, Rect)> = roots.iter().filter_map(|id| Some((*id, effects::preview::bounds_of(d, &[*id], true)?))).collect(); + let Some(all) = items.iter().map(|(_, b)| *b).reduce(|a, b| a.union(b)) else { return Ok(json!({ "count": 0 })) }; + let n = items.len(); + let cols = match layout { + "row" => n, + "column" => 1, + _ => columns.map_or_else(|| (n as f64).sqrt().ceil() as usize, |c| usize::try_from(c).unwrap_or(n)), + } + .clamp(1, n); + let mut widths = vec![0.0_f64; cols]; + let mut heights = vec![0.0_f64; n.div_ceil(cols)]; + for (i, (_, b)) in items.iter().enumerate() { + if let Some(w) = widths.get_mut(i % cols) { + *w = w.max(b.width()); + } + if let Some(h) = heights.get_mut(i / cols) { + *h = h.max(b.height()); + } + } + let total = |sizes: &[f64], gap: f64| sizes.iter().sum::<f64>() + gap * sizes.len().saturating_sub(1) as f64; + let origin = if center { + let board = d.artboards.get(d.artboard_at(all.center()).unwrap_or(0)).map_or(all, |a| a.rect); + Point::new(board.center().x - total(&widths, gap_x) / 2.0, board.center().y - total(&heights, gap_y) / 2.0) + } else { + Point::new(all.x0, all.y0) + }; + // The middle of each column (row): the sizes and gaps before it, and half its own size. + let middles = |sizes: &[f64], gap: f64, from: f64| -> Vec<f64> { + sizes + .iter() + .scan(from, |at, size| { + let mid = *at + size / 2.0; + *at += size + gap; + Some(mid) + }) + .collect() + }; + let (xs, ys) = (middles(&widths, gap_x, origin.x), middles(&heights, gap_y, origin.y)); + let xfs: Vec<(NodeId, Affine)> = items + .iter() + .enumerate() + .filter_map(|(i, (id, b))| Some((*id, Affine::translate(Point::new(*xs.get(i % cols)?, *ys.get(i / cols)?) - b.center())))) + .collect(); + transform_each(s, "Arrange in Grid", false, &xfs)?; + Ok(json!({ "count": n })) +} + +fn swap(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "addon.arrange.swap"; + let size = switch_or(p, "size", false, C)?; + let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let roots = selected_roots(s)?; + let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) }; + let (ba, bb) = (box_of(s, a)?, box_of(s, b)?); + let to = |o: &OrientedBox| place(o.center(), size.then(|| (o.rect.width(), o.rect.height())), strokes); + let xfs = [(a, object_bounds_transform(s, &to(&bb), a)?), (b, object_bounds_transform(s, &to(&ba), b)?)]; + transform_each(s, "Swap Objects", strokes, &xfs)?; + Ok(json!({})) +} + +fn replace(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "addon.arrange.replace"; + let fit = choice(p, C, "fit", &["keep", "bounds", "proportional"])?.unwrap_or("keep"); + let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let keep = switch_or(p, "keep", false, C)?; + let roots = selected_roots(s)?; + let Some((&top, others)) = roots.split_last().filter(|(_, others)| !others.is_empty()) else { + return Err(bad(C, "select at least two objects")); + }; + let tb = box_of(s, top)?; + let (tw, th) = (tb.rect.width(), tb.rect.height()); + let mut xfs = Vec::with_capacity(others.len()); + for &id in others { + let Some(b) = s.transform_box(&[id]) else { continue }; + let (w, h) = (b.rect.width(), b.rect.height()); + let size = match fit { + "bounds" => Some((w, h)), + // The smaller of the two scales that fit; a side the copy doesn't have doesn't count. + "proportional" => { + [(w, tw), (h, th)].into_iter().filter(|(_, t)| *t > 1e-9).map(|(v, t)| v / t).reduce(f64::min).map(|k| (tw * k, th * k)) + } + _ => None, + }; + xfs.push((id, object_bounds_transform(s, &place(b.center(), size, strokes), top)?)); + } + let p = json!({ "strokes": strokes }); + let mut sc = scaling(s, &p); + sc.patterns = transform_patterns(s, &p, &[top])?; + let ids = s.edit("Replace with Top Object", |d, sel| { + let Some(n) = d.node(top).cloned() else { return Ok(vec![]) }; + let mut items = Vec::with_capacity(xfs.len()); + for (id, xf) in &xfs { + let mut c = d.reid(&n); + transform_node(&mut c, *xf, sc, true); + items.push((*id, vec![c])); + } + let out: Vec<NodeId> = items.iter().flat_map(|(_, c)| c.iter().map(|n| n.id)).collect(); + d.insert_beside(items, !keep)?; + refresh_bounds_of(d, &out); + sel.set(out.iter().copied()); + Ok(out) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })) +} + +fn size(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "addon.arrange.size"; + let width = size_param(p, "width", C)?; + let height = size_param(p, "height", C)?; + if width.is_none() && height.is_none() { + return Err(bad(C, "give `width` or `height`")); + } + let proportional = switch_or(p, "proportional", false, C)?; + let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4); + let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) }); + if let Some(w) = width { + q["width"] = json!(w); + } + if let Some(h) = height { + q["height"] = json!(h); + } + let mut xfs = vec![]; + for id in selected_roots(s)? { + if s.transform_box(&[id]).is_some() { + xfs.push((id, object_bounds_transform(s, &q, id)?)); + } + } + transform_each(s, "Set Size of Each", strokes, &xfs)?; + Ok(json!({ "count": xfs.len() })) +} diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs new file mode 100644 index 0000000000..db19cc1e9e --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -0,0 +1,263 @@ +//! Arrange Tools' commands: the geometry each one leaves, one undo step each, when they are off, +//! and bad params refused without a change. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::Rect; + +use crate::Session; + +/// A new document whose new art has no stroke, so visual and geometric bounds agree. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap(); +} + +fn bounds(s: &Session, id: NodeId) -> Rect { + s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap() +} + +fn near(a: Rect, b: (f64, f64, f64, f64)) -> bool { + [(a.x0, b.0), (a.y0, b.1), (a.width(), b.2), (a.height(), b.3)].iter().all(|(x, y)| (x - y).abs() < 1e-6) +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// Each of `bad` is refused and leaves the document as it was. +fn refuses(s: &mut Session, cmd: &str, bad: &[Value]) { + let (before, n) = (s.doc().unwrap().doc.clone(), steps(s)); + for p in bad { + assert!(s.execute(cmd, p).is_err(), "{cmd} {p}"); + } + assert_eq!(steps(s), n, "{cmd}"); + assert!(*s.doc().unwrap().doc == *before, "{cmd} changed the document"); +} + +fn enabled(s: &Session, cmd: &str) -> bool { + s.commands().into_iter().find(|c| c.id == cmd).unwrap().enabled +} + +#[test] +fn grid_lays_objects_out_in_rows_and_columns_from_the_back() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 20.0, 10.0); + let b = rect(&mut s, 300.0, 50.0, 40.0, 30.0); + let c = rect(&mut s, 10.0, 200.0, 10.0, 10.0); + let d = rect(&mut s, 50.0, 5.0, 30.0, 20.0); + select(&mut s, &[d, c, b, a]); + let n = steps(&s); + // Four objects: two columns. The grid starts at the selection's top-left (10, 5). + let r = s.execute("addon.arrange.grid", &json!({"gapX": 5, "gapY": 2})).unwrap(); + assert_eq!(r["count"], json!(4)); + assert_eq!(steps(&s), n + 1, "one undo step"); + // Columns 20 and 40 wide (the widest in each), rows 30 and 20 tall; each object centred. + assert!(near(bounds(&s, a), (10.0, 15.0, 20.0, 10.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (35.0, 5.0, 40.0, 30.0)), "{:?}", bounds(&s, b)); + assert!(near(bounds(&s, c), (15.0, 42.0, 10.0, 10.0)), "{:?}", bounds(&s, c)); + assert!(near(bounds(&s, d), (40.0, 37.0, 30.0, 20.0)), "{:?}", bounds(&s, d)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(near(bounds(&s, a), (100.0, 100.0, 20.0, 10.0))); +} + +#[test] +fn grid_lays_out_a_row_or_a_column_and_centres_on_the_artboard() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 100.0, 100.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("addon.arrange.grid", &json!({"layout": "row"})).unwrap(); + assert!(near(bounds(&s, b), (30.0, 0.0, 20.0, 20.0)), "gapX defaults to 10"); + s.execute("addon.arrange.grid", &json!({"layout": "column", "gapX": 4})).unwrap(); + assert!(near(bounds(&s, b), (0.0, 24.0, 20.0, 20.0)), "gapY follows gapX"); + // 20 × 44 centred on the 400 × 300 artboard. + s.execute("addon.arrange.grid", &json!({"layout": "column", "gapY": 4, "centerOnArtboard": true})).unwrap(); + assert!(near(bounds(&s, a), (190.0, 128.0, 20.0, 20.0)), "{:?}", bounds(&s, a)); + // In place already: no step. + let n = steps(&s); + s.execute("addon.arrange.grid", &json!({"layout": "column", "gapY": 4, "centerOnArtboard": true})).unwrap(); + assert_eq!(steps(&s), n); + // More columns than objects: one row. + s.execute("addon.arrange.grid", &json!({"columns": 50, "gapX": 0})).unwrap(); + assert!(near(bounds(&s, b), (210.0, 128.0, 20.0, 20.0)), "{:?}", bounds(&s, b)); +} + +#[test] +fn grid_measures_visual_bounds() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + s.execute("addon.arrange.grid", &json!({"layout": "row", "gapX": 0})).unwrap(); + // Visual boxes 24 wide, touching. + assert!(near(bounds(&s, b), (24.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, b)); +} + +#[test] +fn swap_trades_places_and_optionally_sizes() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0); + let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + let c = rect(&mut s, 200.0, 200.0, 5.0, 5.0); + select(&mut s, &[a]); + assert!(!enabled(&s, "addon.arrange.swap")); + select(&mut s, &[a, b, c]); + assert!(!enabled(&s, "addon.arrange.swap")); + refuses(&mut s, "addon.arrange.swap", &[json!({})]); + select(&mut s, &[a, b]); + assert!(enabled(&s, "addon.arrange.swap")); + let n = steps(&s); + s.execute("addon.arrange.swap", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1); + // Centres (10, 5) and (120, 120) swap; sizes stay. + assert!(near(bounds(&s, a), (110.0, 115.0, 20.0, 10.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (-10.0, -15.0, 40.0, 40.0)), "{:?}", bounds(&s, b)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.arrange.swap", &json!({"size": true})).unwrap(); + assert!(near(bounds(&s, a), (100.0, 100.0, 40.0, 40.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (0.0, 0.0, 20.0, 10.0)), "{:?}", bounds(&s, b)); +} + +#[test] +fn swap_with_sizes_scales_strokes_as_asked() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 2})).unwrap(); + let weight = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width(); + s.execute("addon.arrange.swap", &json!({"size": true})).unwrap(); + assert_eq!((weight(&s, a), weight(&s, b)), (2.0, 2.0), "off by default (the preference)"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.arrange.swap", &json!({"size": true, "scaleStrokes": true})).unwrap(); + assert!((weight(&s, a) - 4.0).abs() < 1e-9 && (weight(&s, b) - 1.0).abs() < 1e-9, "{} {}", weight(&s, a), weight(&s, b)); +} + +#[test] +fn replace_puts_a_copy_of_the_top_object_in_each_place() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0); + let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + let top = rect(&mut s, 200.0, 200.0, 10.0, 5.0); + select(&mut s, &[top]); + assert!(!enabled(&s, "addon.arrange.replace")); + refuses(&mut s, "addon.arrange.replace", &[json!({})]); + select(&mut s, &[a, b, top]); + let n = steps(&s); + let r = s.execute("addon.arrange.replace", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1); + let ids: Vec<NodeId> = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + assert_eq!(ids.len(), 2); + let st = s.doc().unwrap(); + assert!(st.doc.node(a).is_none() && st.doc.node(b).is_none(), "replaced objects deleted"); + assert!(st.doc.node(top).is_some(), "the top object stays"); + assert_eq!(st.selection.objects, ids, "the copies are selected"); + // Kept size, centred on (10, 20) and (120, 120); each in its object's place (bottom, then middle). + assert!(near(bounds(&s, ids[0]), (5.0, 17.5, 10.0, 5.0)), "{:?}", bounds(&s, ids[0])); + assert!(near(bounds(&s, ids[1]), (115.0, 117.5, 10.0, 5.0)), "{:?}", bounds(&s, ids[1])); + let layer = &s.doc().unwrap().doc.layers[0]; + let order: Vec<NodeId> = layer.children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(order, [ids[0], ids[1], top]); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(a).is_some()); +} + +#[test] +fn replace_fits_the_copies_and_can_keep_the_originals() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0); + let top = rect(&mut s, 200.0, 200.0, 10.0, 5.0); + select(&mut s, &[a, top]); + let r = s.execute("addon.arrange.replace", &json!({"fit": "bounds", "keep": true})).unwrap(); + let copy = NodeId(r["ids"][0].as_u64().unwrap()); + assert!(near(bounds(&s, copy), (0.0, 0.0, 20.0, 40.0)), "{:?}", bounds(&s, copy)); + let order: Vec<NodeId> = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(order, [a, copy, top], "kept: the copy goes right above it"); + s.execute("edit.undo", &json!({})).unwrap(); + select(&mut s, &[a, top]); + let r = s.execute("addon.arrange.replace", &json!({"fit": "proportional"})).unwrap(); + let copy = NodeId(r["ids"][0].as_u64().unwrap()); + // 10 × 5 into 20 × 40: twice as large, centred on (10, 20). + assert!(near(bounds(&s, copy), (0.0, 15.0, 20.0, 10.0)), "{:?}", bounds(&s, copy)); +} + +#[test] +fn size_gives_each_object_a_width_and_height() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0); + let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + select(&mut s, &[a, b]); + let n = steps(&s); + s.execute("addon.arrange.size", &json!({"width": 30})).unwrap(); + assert_eq!(steps(&s), n + 1); + // About each centre; the height stays. + assert!(near(bounds(&s, a), (-5.0, 0.0, 30.0, 10.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (105.0, 100.0, 30.0, 40.0)), "{:?}", bounds(&s, b)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.arrange.size", &json!({"width": 40, "proportional": true, "reference": 0})).unwrap(); + assert!(near(bounds(&s, a), (0.0, 0.0, 40.0, 20.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (100.0, 100.0, 40.0, 40.0)), "{:?}", bounds(&s, b)); + s.execute("addon.arrange.size", &json!({"width": 10, "height": 12, "proportional": true, "reference": 8})).unwrap(); + assert!(near(bounds(&s, a), (30.0, 8.0, 10.0, 12.0)), "both given: both set, {:?}", bounds(&s, a)); +} + +#[test] +fn bad_params_are_refused() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0); + let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + select(&mut s, &[a, b]); + refuses( + &mut s, + "addon.arrange.grid", + &[ + json!({"layout": "spiral"}), + json!({"columns": 0}), + json!({"columns": 1.5}), + json!({"columns": 1e12}), + json!({"gapX": 1e308}), + json!({"gapY": "10"}), + json!({"centerOnArtboard": "yes"}), + ], + ); + refuses(&mut s, "addon.arrange.swap", &[json!({"size": 1}), json!({"scaleStrokes": "no"})]); + refuses(&mut s, "addon.arrange.replace", &[json!({"fit": "stretch"}), json!({"keep": 0})]); + refuses( + &mut s, + "addon.arrange.size", + &[ + json!({}), + json!({"width": 0}), + json!({"height": -5}), + json!({"width": 1e308}), + json!({"width": "10"}), + json!({"width": 10, "reference": 9}), + json!({"width": 10, "proportional": "yes"}), + ], + ); +} + +#[test] +fn off_without_a_selection() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 20.0, 10.0); + s.execute("select.none", &json!({})).unwrap(); + for c in ["addon.arrange.grid", "addon.arrange.swap", "addon.arrange.replace", "addon.arrange.size"] { + assert!(!enabled(&s, c), "{c}"); + } + assert!(!enabled(&Session::new(), "addon.arrange.swap")); +} diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 4839a0ac41..bac3540fad 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -32,7 +32,7 @@ mod transform; pub(crate) use align::choice; pub(crate) use arrange::group_nodes; -pub(crate) use bounds::bounds_rewrite; +pub(crate) use bounds::{bounds_rewrite, object_bounds_transform}; pub use commands::specs; pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip}; pub(super) use shape::recut; diff --git a/crates/engine/src/cmd/object/bounds.rs b/crates/engine/src/cmd/object/bounds.rs index 2e07471706..9d4795235f 100644 --- a/crates/engine/src/cmd/object/bounds.rs +++ b/crates/engine/src/cmd/object/bounds.rs @@ -6,7 +6,7 @@ use super::{ }; pub(super) fn set_bounds(s: &mut Session, p: &Value) -> Result<Value> { - match bounds_transform(s, p, selected_roots_to_transform(s)?, 0.0)? { + match bounds_transform(s, p, selected_roots_to_transform(s)?, 0.0, true)? { Bounds::Anchors(ids, b) => set_anchor_bounds(s, p, ids, b), Bounds::Objects(ids, xf) => apply_transform(s, "Transform", ids, xf, p, false), } @@ -32,7 +32,7 @@ pub(crate) fn bounds_rewrite(s: &Session, cmd: &str, params: &Value) -> Option<( if cmd != "object.setBounds" { return None; } - let Ok(Bounds::Objects(_, xf)) = bounds_transform(s, params, selected_roots_to_transform(s).ok()?, 1e-4) else { return None }; + let Ok(Bounds::Objects(_, xf)) = bounds_transform(s, params, selected_roots_to_transform(s).ok()?, 1e-4, true) else { return None }; let mut p = params.as_object().cloned().unwrap_or_default(); for k in ["x", "y", "width", "height", "reference", "proportional"] { p.remove(k); @@ -41,14 +41,26 @@ pub(crate) fn bounds_rewrite(s: &Session, cmd: &str, params: &Value) -> Option<( Some(("object.transform".to_string(), Value::Object(p))) } +/// The transform that gives object `id` on its own the place and size `p` asks for, as +/// `object.setBounds` measures them (Use Preview Bounds, `strokes`, `reference`, `proportional`), +/// whatever anchors are direct-selected. The art keeps at least 1e-4 of its width and height. +pub(crate) fn object_bounds_transform(s: &Session, p: &Value, id: NodeId) -> Result<Affine> { + match bounds_transform(s, p, vec![id], 1e-4, false)? { + Bounds::Objects(_, xf) => Ok(xf), + Bounds::Anchors(..) => Err(EngineError::Other("no bounds".into())), + } +} + /// How `object.setBounds` with params `p` changes the objects `ids`. A scale that would leave the -/// art with a width or height below `least` of the one it has keeps `least` of it. -fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64) -> Result<Bounds> { +/// art with a width or height below `least` of the one it has keeps `least` of it. With `anchors`, +/// direct-selected anchors are what changes ([`Bounds::Anchors`]). +fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchors: bool) -> Result<Bounds> { check_numbers(p, &["x", "y", "width", "height", "reference"], "object.setBounds")?; let st = s.doc()?; check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?; check_switches(p, &["proportional"], "object.setBounds")?; - if transforms_objects(p) + if anchors + && transforms_objects(p) && !bool_or(p, "copy", false) && let Some(b) = effects::preview::anchor_bounds(&st.selection, &st.doc, s.prefs.use_preview_bounds) { diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index e80e93ce8a..69c69097ec 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -579,6 +579,15 @@ fn structured_junk() { ("addon.pathtools.movePointsTogether", json!({"enabled": true})), ("addon.pathtools.slideAnchor", json!({"id": 2, "anchor": 1, "t": 0.5})), ("addon.pathtools.movePointsTogether", json!({"enabled": false})), + // Arrange Tools add-on. + ("addon.arrange.grid", json!({"columns": u64::MAX, "gapX": 1e6, "gapY": -1e6, "centerOnArtboard": true})), + ("addon.arrange.grid", json!({"layout": "row", "gapX": f64::MAX, "columns": -1})), + ("addon.arrange.grid", json!({"layout": "column", "gapX": -1e6})), + ("addon.arrange.swap", json!({"size": true, "scaleStrokes": true})), + ("addon.arrange.replace", json!({"fit": "proportional", "keep": true})), + ("addon.arrange.replace", json!({"fit": "bounds", "scaleStrokes": true})), + ("addon.arrange.size", json!({"width": 1e6, "height": 0.001, "reference": 8, "scaleStrokes": true})), + ("addon.arrange.size", json!({"width": 0.001, "proportional": true, "reference": u64::MAX})), // Smart Pen add-on. ("addon.pen.append", json!({"id": 2, "x": 1e308, "y": 0, "in": [1e308, -1e308]})), ("addon.pen.append", json!({"id": 2, "subpath": u64::MAX, "x": 0, "y": 0, "segment": "curved"})), diff --git a/crates/ui-egui/src/addons.rs b/crates/ui-egui/src/addons.rs index 36106b72b6..4d148ff586 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -1,6 +1,7 @@ //! VectorCraft's built-in add-ons in the interface: each has a panel and a submenu at the top of //! Object › Plug-ins, and acts through its engine commands (`addon.<name>.*`). +pub mod arrange; pub mod cleanup; pub mod color; pub mod pathtools; @@ -11,6 +12,7 @@ use crate::menus::Item; /// The add-ons' submenus, then a separator: the head of Object › Plug-ins. pub fn plugin_menu() -> Vec<Item> { vec![ + Item::Sub("Arrange Tools", arrange::menu()), Item::Sub("Artwork Cleanup", cleanup::menu()), Item::Sub("Color Effects", color::menu()), Item::Sub("Path Precision Tools", pathtools::menu()), diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs new file mode 100644 index 0000000000..8435483cb8 --- /dev/null +++ b/crates/ui-egui/src/addons/arrange.rs @@ -0,0 +1,175 @@ +//! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of +//! Arrange in Grid, Replace with Top Object and Set Size of Each, which preview on the canvas and +//! run their `addon.arrange.*` command on OK; and Zoom to Selection ([`ZOOM`]), which fits the +//! active view to the selection. + +use egui::Ui; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::menus::Item; +use crate::state::Dialog; +use crate::widgets; + +/// Zoom to Selection: a view command, since the view is the interface's. +pub const ZOOM: &str = "addon.arrange.zoomSelection"; +/// The dialogs' kinds. +pub const GRID: &str = "arrangeGrid"; +pub const REPLACE: &str = "arrangeReplace"; +pub const SIZE: &str = "arrangeSize"; +/// Each dialog's kind, command and heading. +const DIALOGS: [(&str, &str, &str); 3] = [ + (GRID, "addon.arrange.grid", "Arrange in Grid"), + (REPLACE, "addon.arrange.replace", "Replace with Top Object"), + (SIZE, "addon.arrange.size", "Set Size of Each"), +]; +/// The widths and heights Set Size of Each takes (pt), and the gaps Arrange in Grid takes. +const SIZES: std::ops::RangeInclusive<f64> = 0.001..=1e6; +const GAPS: std::ops::RangeInclusive<f64> = -1e6..=1e6; +const LABEL_W: f32 = 110.0; +const FIELD_W: f32 = 90.0; + +/// Object › Plug-ins › Arrange Tools. +pub fn menu() -> Vec<Item> { + vec![ + Item::Cmd("Arrange in Grid…", "addon.arrange.grid", Value::Null), + Item::Cmd("Swap Objects", "addon.arrange.swap", json!({})), + Item::Cmd("Swap Objects and Sizes", "addon.arrange.swap", json!({ "size": true })), + Item::Cmd("Replace with Top Object…", "addon.arrange.replace", Value::Null), + Item::Cmd("Set Size of Each…", "addon.arrange.size", Value::Null), + Item::Sep, + Item::Cmd("Zoom to Selection", ZOOM, json!({})), + ] +} + +/// The dialog (kind, fields) the menu item of command `id` opens; `None` for other commands and +/// without a document. +pub(crate) fn dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static str, Value)> { + let &(kind, ..) = DIALOGS.iter().find(|(_, cmd, _)| *cmd == id)?; + let st = app.session.active()?; + let strokes = app.session.prefs.scale_strokes; + let fields = match kind { + // A square grid to start with: as many columns as the square root of the count. + GRID => json!({ + "layout": "grid", "columns": (st.selection.objects.len().max(1) as f64).sqrt().ceil() as u64, + "gapX": 10, "gapY": 10, "centerOnArtboard": false, + }), + REPLACE => json!({ "fit": "keep", "keep": false, "scaleStrokes": strokes }), + // The first selected object's size, as the command measures it (a side it lacks: the least). + _ => { + let b = st.selection.objects.first().and_then(|id| app.session.transform_box(&[*id])).map_or((100.0, 100.0), |b| { + (b.rect.width().clamp(*SIZES.start(), *SIZES.end()), b.rect.height().clamp(*SIZES.start(), *SIZES.end())) + }); + json!({ + "width": b.0, "height": b.1, "__width": true, "__height": true, "proportional": false, "reference": 4, "scaleStrokes": strokes, + }) + } + }; + Some((kind, fields)) +} + +pub(crate) const SPEC: DialogSpec = DialogSpec { + heading: |d| tl!(command(d).1).to_string(), + body, + confirm, + preview: true, + min_width: 320.0, + ok_enabled: Some(|_, d| d.kind != SIZE || d.bool("__width") || d.bool("__height")), + ..DialogSpec::FORM +}; + +/// The command and heading of dialog `d`. +fn command(d: &Dialog) -> (&'static str, &'static str) { + DIALOGS.iter().find(|(kind, ..)| *kind == d.kind).map_or(("", ""), |&(_, cmd, label)| (cmd, label)) +} + +/// The command's params: the fields, and of Set Size of Each's width and height those ticked. +fn params(d: &Dialog) -> Value { + let mut p = form::params(d); + if let Some(o) = p.as_object_mut() { + for side in ["width", "height"] { + if !d.bool(&format!("__{side}")) { + o.remove(side); + } + } + } + p +} + +fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + let unit = app.session.general_unit(); + let widths = (LABEL_W, 150.0); + match d.kind.as_str() { + GRID => { + let layouts = [("grid", "Grid by Row"), ("row", "Arrange by Row"), ("column", "Arrange by Column")]; + form::choice(ui, d, "layout", tl!("Layout:"), widths, &layouts); + ui.add_enabled_ui(d.str("layout") == "grid", |ui| { + widgets::label_row(ui, tl!("Columns:"), LABEL_W, |ui| { + if let Some(v) = widgets::range_field(ui, ("arrange", "columns"), d.f64("columns", 1.0), 1.0..=10_000.0, "", 0, FIELD_W) { + d.fields.insert("columns".into(), json!(v as u64)); + } + }); + }); + widgets::label_row(ui, tl!("H Spacing:"), LABEL_W, |ui| { + form::length_within(ui, d, "gapX", unit, FIELD_W, Some(GAPS)); + }); + widgets::label_row(ui, tl!("V Spacing:"), LABEL_W, |ui| { + form::length_within(ui, d, "gapY", unit, FIELD_W, Some(GAPS)); + }); + form::check(ui, d, "centerOnArtboard", tl!("Center on Artboard")); + } + REPLACE => { + let fits = [("keep", "Actual Size"), ("bounds", "Bounds"), ("proportional", "Bounds (Fit Proportionally)")]; + form::choice(ui, d, "fit", tl!("Size:"), widths, &fits); + form::check(ui, d, "keep", tl!("Keep Original")); + form::check(ui, d, "scaleStrokes", tl!("Scale Strokes & Effects")); + } + _ => { + egui::Grid::new("arrange-size").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { + for (side, tick, label) in [("width", "__width", tl!("Width:")), ("height", "__height", tl!("Height:"))] { + form::check(ui, d, tick, label); + let on = d.bool(tick); + ui.add_enabled_ui(on, |ui| { + form::length_within(ui, d, side, unit, FIELD_W, Some(SIZES)); + }); + ui.end_row(); + } + }); + // Only one size given: the other can follow it. + let one = d.bool("__width") != d.bool("__height"); + if widgets::check(ui, tl!("Constrain Width and Height Proportions"), d.bool("proportional"), one) { + let on = !d.bool("proportional"); + d.fields.insert("proportional".into(), json!(on)); + } + ui.horizontal(|ui| { + if let Some(i) = widgets::reference_point(ui, d.f64("reference", 4.0).clamp(0.0, 8.0) as usize) { + d.fields.insert("reference".into(), json!(i)); + } + widgets::dim_label(ui, tl!("Reference Point")); + }); + form::check(ui, d, "scaleStrokes", tl!("Scale Strokes & Effects")); + } + } + let (cmd, label) = command(d); + form::preview(app, ui, d, label, cmd, params(d)); + false +} + +/// OK: run the command (keep its preview) and close. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { + form::commit_preview(app, command(d).0, params(d)) +} + +/// Zoom to Selection: the active view zooms and centres so the selection's bounds fill the +/// window, with a margin. An error with nothing selected. +pub(crate) fn zoom(app: &mut VectorcraftApp) -> Result<Value, String> { + if app.session.active().is_none_or(|st| st.selection.objects.is_empty()) { + return Err("nothing selected".into()); + } + crate::canvas::fit(app, ZOOM); + Ok(Value::Null) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs new file mode 100644 index 0000000000..63e58448b6 --- /dev/null +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -0,0 +1,127 @@ +use serde_json::json; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::Session; + +use super::{GRID, REPLACE, SIZE, ZOOM}; +use crate::tests_labels::painted_text; +use crate::{VectorcraftApp, menus}; + +/// An app with two rectangles without a stroke, both selected. +fn app() -> (VectorcraftApp, NodeId, NodeId) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + let mut rect = |x, y, w, h| NodeId(app.run("shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()); + let (a, b) = (rect(0, 0, 20, 10), rect(100, 100, 40, 40)); + app.run("select.all", json!({})).unwrap(); + (app, a, b) +} + +fn bounds(app: &VectorcraftApp, id: NodeId) -> vectorcraft_geom::Rect { + app.session.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap() +} + +/// Click the Arrange Tools item `label`. +fn click(app: &mut VectorcraftApp, label: &str) { + let entries = menus::menu_entries(app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Arrange Tools"] && e.label == label).expect(label); + let (id, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(app, &id, p); +} + +#[test] +fn the_plugins_submenu_lists_the_tools() { + let (app, ..) = app(); + let entries = menus::menu_entries(&app); + let under = |label: &str| entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Arrange Tools"] && e.label == label); + for (label, id) in [ + ("Arrange in Grid…", "addon.arrange.grid"), + ("Swap Objects", "addon.arrange.swap"), + ("Swap Objects and Sizes", "addon.arrange.swap"), + ("Replace with Top Object…", "addon.arrange.replace"), + ("Set Size of Each…", "addon.arrange.size"), + ("Zoom to Selection", ZOOM), + ] { + assert_eq!(under(label).and_then(|e| e.command.as_deref()), Some(id), "{label}"); + } + assert!(entries.iter().any(|e| e.path == ["Object", "Plug-ins"] && e.label == "Install Plug-in…"), "the rest follows"); +} + +#[test] +fn arrange_in_grid_opens_its_dialog_and_runs_on_ok() { + let (mut app, a, b) = app(); + click(&mut app, "Arrange in Grid…"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(GRID)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Arrange in Grid", "Layout:", "Columns:", "H Spacing:", "V Spacing:", "Center on Artboard", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.fields["columns"], json!(2), "√2, rounded up"); + d.fields.insert("layout".into(), json!("row")); + let n = app.session.doc().unwrap().history.undo.len(); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1); + assert_eq!((bounds(&app, a).x0, bounds(&app, b).x0, bounds(&app, b).y0), (0.0, 30.0, 0.0)); +} + +#[test] +fn arrange_in_grid_previews_and_cancel_rolls_back() { + let (mut app, _, b) = app(); + click(&mut app, "Arrange in Grid…"); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(bounds(&app, b).x0, 30.0, "previewed"); + crate::dialogs::cancel(&mut app); + assert_eq!(bounds(&app, b).x0, 100.0, "rolled back"); +} + +#[test] +fn set_size_of_each_sets_the_sides_ticked() { + let (mut app, a, b) = app(); + click(&mut app, "Set Size of Each…"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(SIZE)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Set Size of Each", "Width:", "Height:", "Constrain Width and Height Proportions", "Reference Point", "Scale Strokes & Effects"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((&d.fields["width"], &d.fields["height"]), (&json!(20.0), &json!(10.0)), "the first object's size"); + d.fields.insert("width".into(), json!(30)); + d.fields.insert("__height".into(), json!(false)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((bounds(&app, a).width(), bounds(&app, a).height()), (30.0, 10.0)); + assert_eq!((bounds(&app, b).width(), bounds(&app, b).height()), (30.0, 40.0)); +} + +#[test] +fn replace_opens_with_the_scale_strokes_preference_and_swap_runs_directly() { + let (mut app, a, b) = app(); + app.run("prefs.set", json!({"key": "scaleStrokes", "value": true})).unwrap(); + click(&mut app, "Replace with Top Object…"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), &d.fields["scaleStrokes"], &d.fields["fit"]), (REPLACE, &json!(true), &json!("keep"))); + crate::dialogs::cancel(&mut app); + click(&mut app, "Swap Objects"); + assert!(app.ui.dialog.is_none()); + assert_eq!( + (bounds(&app, a).center(), bounds(&app, b).center()), + (vectorcraft_geom::Point::new(120.0, 120.0), vectorcraft_geom::Point::new(10.0, 5.0)) + ); +} + +#[test] +fn zoom_to_selection_fits_the_selection_in_the_view() { + let (mut app, _, b) = app(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(560.0, 460.0))); + app.run("select.set", json!({"ids": [b.0]})).unwrap(); + assert!(menus::enabled(&app, ZOOM)); + app.run(ZOOM, json!({})).unwrap(); + let v = app.view().unwrap(); + // 40 × 40 into 500 × 400 (the window less the margin). + assert_eq!((v.center, v.zoom), (vectorcraft_geom::Point::new(120.0, 120.0), 10.0)); + app.run("select.none", json!({})).unwrap(); + assert!(!menus::enabled(&app, ZOOM)); + assert!(app.run(ZOOM, json!({})).is_err()); +} diff --git a/crates/ui-egui/src/canvas/view.rs b/crates/ui-egui/src/canvas/view.rs index add1716110..b25f36b9dc 100644 --- a/crates/ui-egui/src/canvas/view.rs +++ b/crates/ui-egui/src/canvas/view.rs @@ -1,7 +1,7 @@ use super::drag::{drag_id, drop_press}; use super::{CornerRadius, Drag, Point, Pos2, Rect, SCROLL_BAR, Sense, Stroke, Tokens, Ui, VectorcraftApp, View, Xf, pos2, vec2}; -/// Fit the view (View → Fit Artboard / Fit All / Actual Size). +/// Fit the view (View → Fit Artboard / Fit All / Actual Size, Arrange Tools › Zoom to Selection). pub fn fit(app: &mut VectorcraftApp, how: &str) { let Some(rect) = app.canvas_rect else { if let Some(v) = app.view_mut() { @@ -15,6 +15,7 @@ pub fn fit(app: &mut VectorcraftApp, how: &str) { "view.fitAll" => { st.doc.art_bounds().map(|a| st.doc.artboards.iter().fold(a, |r, ab| r.union(ab.rect))).or(st.doc.artboards.first().map(|a| a.rect)) } + crate::addons::arrange::ZOOM => st.doc.bounds_of(&st.selection.objects, true), // The navigator's artboard (the first if it has gone). _ => st.doc.artboards.get(current).or(st.doc.artboards.first()).map(|a| a.rect), }; diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index acbad17508..83e7850f4e 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -39,7 +39,7 @@ pub mod find_links; pub mod flare_options; pub mod flatten; pub mod flattener_presets; -mod form; +pub(crate) mod form; pub(crate) mod free_distort; pub mod freehand; mod gradient_stop; @@ -387,6 +387,7 @@ registry! { PathfinderOptions: [pathfinder_options::KIND] => pathfinder_options::SPEC, RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC, PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC, + ArrangeTools: [crate::addons::arrange::GRID, crate::addons::arrange::REPLACE, crate::addons::arrange::SIZE] => crate::addons::arrange::SPEC, ShortcutImport: [shortcut_import::KIND] => DialogSpec::window(shortcut_import::show, shortcut_import::confirm), } diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index ce01777507..ed6be47e86 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -49,7 +49,7 @@ pub(super) fn length(ui: &mut egui::Ui, d: &mut Dialog, key: &str, unit: Unit, w /// [`length`] whose value is kept within `range` (points): a value typed outside it becomes the /// nearer end, so the field shows the distance the command applies (#4637). -pub(super) fn length_within( +pub(crate) fn length_within( ui: &mut egui::Ui, d: &mut Dialog, key: &str, @@ -247,7 +247,7 @@ pub(super) fn text_area_named(ui: &mut egui::Ui, d: &mut Dialog, key: &str, name } /// A checkbox bound to `d.fields[key]` (its box shows while unchecked too). -pub(super) fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) { +pub(crate) fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) { let b = d.bool(key); if crate::widgets::check(ui, label, b, true) { d.fields.insert(key.into(), Value::Bool(!b)); @@ -256,7 +256,7 @@ pub(super) fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) { /// A dropdown row bound to the string `d.fields[key]`: `label` in a column `widths.0` wide, the /// dropdown `widths.1` wide; `options` are (value, label). -pub(super) fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, widths: (f32, f32), options: &[(&str, &str)]) { +pub(crate) fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, widths: (f32, f32), options: &[(&str, &str)]) { crate::widgets::label_row(ui, label, widths.0, |ui| dropdown(ui, d, key, widths.1, options, false)); } @@ -339,7 +339,7 @@ pub(super) fn grid_then(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit, more: imp } /// Command/effect parameters from the dialog fields (drop UI-only keys). -pub(super) fn params(d: &Dialog) -> Value { +pub(crate) fn params(d: &Dialog) -> Value { Value::Object(d.fields.iter().filter(|(k, _)| !k.starts_with("__") && k.as_str() != "preview").map(|(k, v)| (k.clone(), v.clone())).collect()) } @@ -817,7 +817,7 @@ pub(super) const PREVIEWED: &str = "__previewed"; /// The Preview checkbox of a dialog that previews `cmd` on the canvas: while it is on, `params` run /// again on the interaction's snapshot whenever they differ from the last preview (whether a widget /// or `ui.dialog.set` changed them); turning it off rolls back. -pub(super) fn preview(app: &mut crate::VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, label: &str, cmd: &str, params: Value) { +pub(crate) fn preview(app: &mut crate::VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, label: &str, cmd: &str, params: Value) { let _ = preview_result(app, ui, d, label, cmd, params); } @@ -866,7 +866,7 @@ pub(super) fn preview_now(app: &mut crate::VectorcraftApp, d: &mut Dialog, label /// OK of a dialog using [`preview`]: keep the previewed `cmd` as one undo step (or run it when no /// preview runs) and close; the command's warning shows in the status bar either way. On an error /// the dialog stays open. -pub(super) fn commit_preview(app: &mut crate::VectorcraftApp, cmd: &str, params: Value) -> Result<Value, String> { +pub(crate) fn commit_preview(app: &mut crate::VectorcraftApp, cmd: &str, params: Value) -> Result<Value, String> { let r = if app.session.in_interaction() { match app.session.preview(cmd, ¶ms) { Ok(v) => { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 99f0bbc2d8..5b65923a19 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5891,3 +5891,15 @@ breakText Glyphs Глифи Gap 4 Разстояние 4 Dash 5 Тире 5 Gap 5 Разстояние 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Инструменти за подреждане + Arrange in Grid… Подреждане в мрежа… + Arrange in Grid Подреждане в мрежа + Swap Objects Размяна на обекти + Swap Objects and Sizes Размяна на обекти и размери + Replace with Top Object… Замяна с горния обект… + Replace with Top Object Замяна с горния обект + Set Size of Each… Задаване на размер на всеки… + Set Size of Each Задаване на размер на всеки +@msg select exactly two objects изберете точно два обекта +@msg give `width` or `height` задайте `width` или `height` diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 700fd9ddee..5798a7a798 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5924,3 +5924,15 @@ shape Open Otvoren @msg `follow` must be "average", "a" or "b" `follow` mora biti "average", "a" ili "b" @msg the paths have nothing to merge there putanje tu nemaju šta spojiti @msg the path is locked or hidden putanja je zaključana ili skrivena +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Alati za raspoređivanje + Arrange in Grid… Rasporedi u mrežu… + Arrange in Grid Rasporedi u mrežu + Swap Objects Zamijeni objekte + Swap Objects and Sizes Zamijeni objekte i veličine + Replace with Top Object… Zamijeni gornjim objektom… + Replace with Top Object Zamijeni gornjim objektom + Set Size of Each… Postavi veličinu svakog… + Set Size of Each Postavi veličinu svakog +@msg select exactly two objects odaberite tačno dva objekta +@msg give `width` or `height` zadajte `width` ili `height` diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index dc8fc7effd..d93092418f 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5991,3 +5991,15 @@ breakText Glyphs Glifs Gap 4 Separació 4 Dash 5 Guió 5 Gap 5 Separació 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Eines d’organització + Arrange in Grid… Organitza en quadrícula… + Arrange in Grid Organitza en quadrícula + Swap Objects Intercanvia els objectes + Swap Objects and Sizes Intercanvia els objectes i les mides + Replace with Top Object… Reemplaça per l’objecte superior… + Replace with Top Object Reemplaça per l’objecte superior + Set Size of Each… Defineix la mida de cadascun… + Set Size of Each Defineix la mida de cadascun +@msg select exactly two objects selecciona exactament dos objectes +@msg give `width` or `height` indica `width` o `height` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 5498e35481..50a8f953e1 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6000,3 +6000,15 @@ breakText Glyphs Glyfy Gap 4 Mezera 4 Dash 5 Čárka 5 Gap 5 Mezera 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Nástroje uspořádání + Arrange in Grid… Uspořádat do mřížky… + Arrange in Grid Uspořádat do mřížky + Swap Objects Prohodit objekty + Swap Objects and Sizes Prohodit objekty a velikosti + Replace with Top Object… Nahradit horním objektem… + Replace with Top Object Nahradit horním objektem + Set Size of Each… Nastavit velikost jednotlivě… + Set Size of Each Nastavit velikost jednotlivě +@msg select exactly two objects vyberte právě dva objekty +@msg give `width` or `height` zadejte `width` nebo `height` diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index c4e19d9939..87249badf8 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5905,3 +5905,15 @@ breakText Glyphs Glyffer Gap 4 Mellemrum 4 Dash 5 Streg 5 Gap 5 Mellemrum 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Arrangeringsværktøjer + Arrange in Grid… Arrangér i gitter… + Arrange in Grid Arrangér i gitter + Swap Objects Byt objekter + Swap Objects and Sizes Byt objekter og størrelser + Replace with Top Object… Erstat med øverste objekt… + Replace with Top Object Erstat med øverste objekt + Set Size of Each… Angiv størrelse for hver… + Set Size of Each Angiv størrelse for hver +@msg select exactly two objects markér præcis to objekter +@msg give `width` or `height` angiv `width` eller `height` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 87ac4fc701..513ff8e4f4 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5586,3 +5586,15 @@ breakText Glyphs Glyphen Gap 4 Lücke 4 Dash 5 Strich 5 Gap 5 Lücke 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Anordnungswerkzeuge + Arrange in Grid… In Raster anordnen… + Arrange in Grid In Raster anordnen + Swap Objects Objekte vertauschen + Swap Objects and Sizes Objekte und Größen vertauschen + Replace with Top Object… Durch oberstes Objekt ersetzen… + Replace with Top Object Durch oberstes Objekt ersetzen + Set Size of Each… Größe einzeln festlegen… + Set Size of Each Größe einzeln festlegen +@msg select exactly two objects wählen Sie genau zwei Objekte aus +@msg give `width` or `height` geben Sie `width` oder `height` an diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index c7c2ab8980..ce282989f0 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5953,3 +5953,15 @@ breakText Glyphs Γλύφοι Gap 4 Διάκενο 4 Dash 5 Παύλα 5 Gap 5 Διάκενο 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Εργαλεία διάταξης + Arrange in Grid… Διάταξη σε πλέγμα… + Arrange in Grid Διάταξη σε πλέγμα + Swap Objects Εναλλαγή αντικειμένων + Swap Objects and Sizes Εναλλαγή αντικειμένων και μεγεθών + Replace with Top Object… Αντικατάσταση με το επάνω αντικείμενο… + Replace with Top Object Αντικατάσταση με το επάνω αντικείμενο + Set Size of Each… Ορισμός μεγέθους καθενός… + Set Size of Each Ορισμός μεγέθους καθενός +@msg select exactly two objects επιλέξτε ακριβώς δύο αντικείμενα +@msg give `width` or `height` δώστε `width` ή `height` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index b517c4c791..fe945423e6 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5943,3 +5943,15 @@ breakText Glyphs Glifos Gap 4 Hueco 4 Dash 5 Guion 5 Gap 5 Hueco 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Herramientas de organización + Arrange in Grid… Organizar en cuadrícula… + Arrange in Grid Organizar en cuadrícula + Swap Objects Intercambiar objetos + Swap Objects and Sizes Intercambiar objetos y tamaños + Replace with Top Object… Reemplazar por el objeto superior… + Replace with Top Object Reemplazar por el objeto superior + Set Size of Each… Definir el tamaño de cada uno… + Set Size of Each Definir el tamaño de cada uno +@msg select exactly two objects selecciona exactamente dos objetos +@msg give `width` or `height` indica `width` o `height` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 92f4e48945..7ebd23d6bc 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6031,3 +6031,15 @@ breakText Glyphs Merkit Gap 4 Väli 4 Dash 5 Viiva 5 Gap 5 Väli 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Järjestelytyökalut + Arrange in Grid… Järjestä ruudukkoon… + Arrange in Grid Järjestä ruudukkoon + Swap Objects Vaihda objektien paikat + Swap Objects and Sizes Vaihda objektien paikat ja koot + Replace with Top Object… Korvaa ylimmällä objektilla… + Replace with Top Object Korvaa ylimmällä objektilla + Set Size of Each… Aseta kunkin koko… + Set Size of Each Aseta kunkin koko +@msg select exactly two objects valitse täsmälleen kaksi objektia +@msg give `width` or `height` anna `width` tai `height` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 27a2d52010..859b2bfcd3 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5999,3 +5999,15 @@ breakText Glyphs Glyphes Gap 4 Écart 4 Dash 5 Tiret 5 Gap 5 Écart 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Outils de disposition + Arrange in Grid… Disposer en grille… + Arrange in Grid Disposer en grille + Swap Objects Permuter les objets + Swap Objects and Sizes Permuter les objets et leurs tailles + Replace with Top Object… Remplacer par l’objet supérieur… + Replace with Top Object Remplacer par l’objet supérieur + Set Size of Each… Définir la taille de chaque objet… + Set Size of Each Définir la taille de chaque objet +@msg select exactly two objects sélectionnez exactement deux objets +@msg give `width` or `height` indiquez `width` ou `height` diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index ec63473054..02e7303ed4 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5987,3 +5987,15 @@ breakText Glyphs Glifák Gap 4 Hézag 4 Dash 5 Vonal 5 Gap 5 Hézag 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Elrendezőeszközök + Arrange in Grid… Elrendezés rácsba… + Arrange in Grid Elrendezés rácsba + Swap Objects Objektumok cseréje + Swap Objects and Sizes Objektumok és méretek cseréje + Replace with Top Object… Csere a legfelső objektumra… + Replace with Top Object Csere a legfelső objektumra + Set Size of Each… Egyenkénti méret beállítása… + Set Size of Each Egyenkénti méret beállítása +@msg select exactly two objects jelölj ki pontosan két objektumot +@msg give `width` or `height` add meg a `width` vagy a `height` értéket diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index f958f41b14..c2d3695755 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5905,3 +5905,15 @@ breakText Glyphs Glif Gap 4 Jarak 4 Dash 5 Garis 5 Gap 5 Jarak 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Alat penyusunan + Arrange in Grid… Susun dalam grid… + Arrange in Grid Susun dalam grid + Swap Objects Tukar objek + Swap Objects and Sizes Tukar objek dan ukuran + Replace with Top Object… Ganti dengan objek teratas… + Replace with Top Object Ganti dengan objek teratas + Set Size of Each… Atur ukuran masing-masing… + Set Size of Each Atur ukuran masing-masing +@msg select exactly two objects pilih tepat dua objek +@msg give `width` or `height` berikan `width` atau `height` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index a326cf55fb..8021409d21 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5620,3 +5620,15 @@ breakText Glyphs Glifi Gap 4 Spazio 4 Dash 5 Tratto 5 Gap 5 Spazio 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Strumenti di disposizione + Arrange in Grid… Disponi in griglia… + Arrange in Grid Disponi in griglia + Swap Objects Scambia oggetti + Swap Objects and Sizes Scambia oggetti e dimensioni + Replace with Top Object… Sostituisci con l’oggetto superiore… + Replace with Top Object Sostituisci con l’oggetto superiore + Set Size of Each… Imposta dimensione di ciascuno… + Set Size of Each Imposta dimensione di ciascuno +@msg select exactly two objects seleziona esattamente due oggetti +@msg give `width` or `height` indica `width` o `height` diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 50afc7d72b..269651408f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5686,3 +5686,15 @@ breakText Glyphs 字形 Gap 4 間隔 4 Dash 5 線分 5 Gap 5 間隔 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools 配置ツール + Arrange in Grid… グリッドに配置… + Arrange in Grid グリッドに配置 + Swap Objects オブジェクトを入れ替え + Swap Objects and Sizes オブジェクトとサイズを入れ替え + Replace with Top Object… 最前面のオブジェクトで置き換え… + Replace with Top Object 最前面のオブジェクトで置き換え + Set Size of Each… 個別にサイズを設定… + Set Size of Each 個別にサイズを設定 +@msg select exactly two objects オブジェクトをちょうど 2 つ選択してください +@msg give `width` or `height` `width` または `height` を指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8b52357ad9..fd0eaae44a 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5990,3 +5990,15 @@ breakText Glyphs გლიფები Gap 4 შუალედი 4 Dash 5 ტირე 5 Gap 5 შუალედი 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools განლაგების ხელსაწყოები + Arrange in Grid… ბადეში განლაგება… + Arrange in Grid ბადეში განლაგება + Swap Objects ობიექტების გაცვლა + Swap Objects and Sizes ობიექტებისა და ზომების გაცვლა + Replace with Top Object… ზედა ობიექტით ჩანაცვლება… + Replace with Top Object ზედა ობიექტით ჩანაცვლება + Set Size of Each… თითოეულის ზომის დაყენება… + Set Size of Each თითოეულის ზომის დაყენება +@msg select exactly two objects მონიშნეთ ზუსტად ორი ობიექტი +@msg give `width` or `height` მიუთითეთ `width` ან `height` diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index d1ebee17d3..00666a8401 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5583,3 +5583,15 @@ breakText Glyphs 글리프 Gap 4 간격 4 Dash 5 대시 5 Gap 5 간격 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools 배치 도구 + Arrange in Grid… 격자로 배치… + Arrange in Grid 격자로 배치 + Swap Objects 개체 맞바꾸기 + Swap Objects and Sizes 개체와 크기 맞바꾸기 + Replace with Top Object… 맨 위 개체로 바꾸기… + Replace with Top Object 맨 위 개체로 바꾸기 + Set Size of Each… 각각 크기 설정… + Set Size of Each 각각 크기 설정 +@msg select exactly two objects 개체를 정확히 두 개 선택하세요 +@msg give `width` or `height` `width` 또는 `height`를 지정하세요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 334707edc5..f04ea4da45 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5949,3 +5949,15 @@ breakText Glyphs Glyphs Gap 4 Tussenruimte 4 Dash 5 Streepje 5 Gap 5 Tussenruimte 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Schikgereedschappen + Arrange in Grid… In raster schikken… + Arrange in Grid In raster schikken + Swap Objects Objecten omwisselen + Swap Objects and Sizes Objecten en formaten omwisselen + Replace with Top Object… Vervangen door bovenste object… + Replace with Top Object Vervangen door bovenste object + Set Size of Each… Formaat van elk instellen… + Set Size of Each Formaat van elk instellen +@msg select exactly two objects selecteer precies twee objecten +@msg give `width` or `height` geef `width` of `height` op diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 49d549c17b..17810fe501 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5856,3 +5856,15 @@ breakText Glyphs Glify Gap 4 Odstęp 4 Dash 5 Kreska 5 Gap 5 Odstęp 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Narzędzia układania + Arrange in Grid… Ułóż w siatce… + Arrange in Grid Ułóż w siatce + Swap Objects Zamień obiekty miejscami + Swap Objects and Sizes Zamień obiekty miejscami i rozmiarami + Replace with Top Object… Zastąp górnym obiektem… + Replace with Top Object Zastąp górnym obiektem + Set Size of Each… Ustaw rozmiar każdego… + Set Size of Each Ustaw rozmiar każdego +@msg select exactly two objects zaznacz dokładnie dwa obiekty +@msg give `width` or `height` podaj `width` lub `height` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 26d60b4234..e1fc3b3e6d 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5920,3 +5920,15 @@ breakText Glyphs Glifos Gap 4 Lacuna 4 Dash 5 Traço 5 Gap 5 Lacuna 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Ferramentas de Organização + Arrange in Grid… Organizar em Grade… + Arrange in Grid Organizar em Grade + Swap Objects Trocar Objetos + Swap Objects and Sizes Trocar Objetos e Tamanhos + Replace with Top Object… Substituir pelo Objeto Superior… + Replace with Top Object Substituir pelo Objeto Superior + Set Size of Each… Definir Tamanho de Cada Um… + Set Size of Each Definir Tamanho de Cada Um +@msg select exactly two objects selecione exatamente dois objetos +@msg give `width` or `height` informe `width` ou `height` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 2fec550643..412d4d129b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5978,3 +5978,15 @@ breakText Glyphs Глифы Gap 4 Зазор 4 Dash 5 Штрих 5 Gap 5 Зазор 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Инструменты размещения + Arrange in Grid… Разместить по сетке… + Arrange in Grid Разместить по сетке + Swap Objects Поменять объекты местами + Swap Objects and Sizes Поменять объекты местами и размерами + Replace with Top Object… Заменить верхним объектом… + Replace with Top Object Заменить верхним объектом + Set Size of Each… Задать размер каждого… + Set Size of Each Задать размер каждого +@msg select exactly two objects выделите ровно два объекта +@msg give `width` or `height` укажите `width` или `height` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index fd253ed7a9..08b0b8105c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6053,3 +6053,15 @@ breakText Glyphs Glyfer Gap 4 Mellanrum 4 Dash 5 Streck 5 Gap 5 Mellanrum 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Ordningsverktyg + Arrange in Grid… Ordna i rutnät… + Arrange in Grid Ordna i rutnät + Swap Objects Byt plats på objekt + Swap Objects and Sizes Byt plats och storlek på objekt + Replace with Top Object… Ersätt med översta objektet… + Replace with Top Object Ersätt med översta objektet + Set Size of Each… Ange storlek för vart och ett… + Set Size of Each Ange storlek för vart och ett +@msg select exactly two objects markera exakt två objekt +@msg give `width` or `height` ange `width` eller `height` diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 849c9c74f5..fff0356575 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5958,3 +5958,15 @@ breakText Glyphs Glifler Gap 4 Boşluk 4 Dash 5 Çizgi 5 Gap 5 Boşluk 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Düzenleme Araçları + Arrange in Grid… Izgarada Düzenle… + Arrange in Grid Izgarada Düzenle + Swap Objects Nesnelerin Yerini Değiştir + Swap Objects and Sizes Nesnelerin Yerini ve Boyutunu Değiştir + Replace with Top Object… En Üstteki Nesneyle Değiştir… + Replace with Top Object En Üstteki Nesneyle Değiştir + Set Size of Each… Her Birinin Boyutunu Ayarla… + Set Size of Each Her Birinin Boyutunu Ayarla +@msg select exactly two objects tam olarak iki nesne seç +@msg give `width` or `height` `width` veya `height` belirt diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 9f06a0f787..1c6f93e5d0 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5600,3 +5600,15 @@ breakText Glyphs Гліфи Gap 4 Проміжок 4 Dash 5 Штрих 5 Gap 5 Проміжок 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Інструменти розміщення + Arrange in Grid… Розмістити сіткою… + Arrange in Grid Розмістити сіткою + Swap Objects Поміняти об’єкти місцями + Swap Objects and Sizes Поміняти об’єкти місцями та розмірами + Replace with Top Object… Замінити верхнім об’єктом… + Replace with Top Object Замінити верхнім об’єктом + Set Size of Each… Задати розмір кожного… + Set Size of Each Задати розмір кожного +@msg select exactly two objects виділіть рівно два об’єкти +@msg give `width` or `height` укажіть `width` або `height` diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 814b2bd0d8..99d8437f89 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5602,3 +5602,15 @@ breakText Glyphs Glyph Gap 4 Khoảng hở 4 Dash 5 Nét 5 Gap 5 Khoảng hở 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools Công cụ sắp xếp + Arrange in Grid… Sắp xếp theo lưới… + Arrange in Grid Sắp xếp theo lưới + Swap Objects Hoán đổi đối tượng + Swap Objects and Sizes Hoán đổi đối tượng và kích thước + Replace with Top Object… Thay bằng đối tượng trên cùng… + Replace with Top Object Thay bằng đối tượng trên cùng + Set Size of Each… Đặt kích thước từng cái… + Set Size of Each Đặt kích thước từng cái +@msg select exactly two objects hãy chọn đúng hai đối tượng +@msg give `width` or `height` hãy cho `width` hoặc `height` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 8fa91dcae0..6ecaf09308 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5842,3 +5842,15 @@ breakText Glyphs 字形 Gap 4 间隔 4 Dash 5 虚线 5 Gap 5 间隔 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools 排列工具 + Arrange in Grid… 按网格排列… + Arrange in Grid 按网格排列 + Swap Objects 交换对象 + Swap Objects and Sizes 交换对象和大小 + Replace with Top Object… 替换为顶层对象… + Replace with Top Object 替换为顶层对象 + Set Size of Each… 分别设置大小… + Set Size of Each 分别设置大小 +@msg select exactly two objects 请恰好选择两个对象 +@msg give `width` or `height` 请提供 `width` 或 `height` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 8525483188..75ee3a4134 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5639,3 +5639,15 @@ breakText Glyphs 字符 Gap 4 間隙 4 Dash 5 虛線 5 Gap 5 間隙 5 +# Arrange Tools add-on (Object › Plug-ins › Arrange Tools). + Arrange Tools 排列工具 + Arrange in Grid… 依格狀排列… + Arrange in Grid 依格狀排列 + Swap Objects 對調物件 + Swap Objects and Sizes 對調物件和大小 + Replace with Top Object… 以最上層物件取代… + Replace with Top Object 以最上層物件取代 + Set Size of Each… 個別設定大小… + Set Size of Each 個別設定大小 +@msg select exactly two objects 請選取正好兩個物件 +@msg give `width` or `height` 請提供 `width` 或 `height` diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 382c730aa1..70c8639710 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -37,6 +37,9 @@ fn queried_dialog(id: &str) -> Option<(&'static str, &'static [&'static str])> { /// The dialog (kind, fields) the menu item of command `id` opens, as the reference app's does. pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static str, Value)> { + if let Some(found) = crate::addons::arrange::dialog(app, id) { + return Some(found); + } Some(match id { // Move opens on the offset moved last and the checkboxes it was last confirmed with. "object.move" => ("move", crate::dialogs::transform::move_fields(app)), diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 772d5a8e19..bb20fbbca5 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -529,6 +529,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result< }, crate::addons::pathtools::corner::COMMAND => crate::addons::pathtools::corner::open(app), crate::addons::pathtools::shared_edge::COMMAND => crate::addons::pathtools::shared_edge::open(app), + crate::addons::arrange::ZOOM => crate::addons::arrange::zoom(app), "tool.setOption" => app.session.set_tool_option_cmd(p), "effect.dialog" => crate::dialogs::open_effect_dialog(app, p), "ui.recolorDialog" => crate::dialogs::recolor::open(app, p), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 55ee84b800..c1cdf4f59d 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -206,7 +206,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { | "view.fitAll" | "view.actualSize" | "view.rotate" => app.session.active().is_some(), - "view.rotateToSelection" => app.session.active().is_some_and(|d| !d.selection.objects.is_empty()), + "view.rotateToSelection" | crate::addons::arrange::ZOOM => app.session.active().is_some_and(|d| !d.selection.objects.is_empty()), id if id.starts_with("file.openRecent") => recent_slot(app, id).is_some(), "file.clearRecent" => !app.ui.recent_files.is_empty(), id if id.starts_with("type.recentFont") => { diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index bdc0966164..ba3e700c62 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -12,6 +12,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} choose the Shared Edge Merge Tool and show the Anchor Inspector panel with its brush, coincidence and Keep Shared Points Together", ), + ( + crate::addons::arrange::ZOOM, + "Zoom to Selection", + "", + "{} zoom and centre the active view so the selection's visual bounds fill the window, with a margin (as view.fitArtboard fits the artboard); off with nothing selected", + ), ( "app.language", "Interface Language", @@ -922,7 +928,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, envelopeWarp, envelopeMesh, envelopeOptions; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", ), ( "ui.widthPointEdit", diff --git a/docs/mcp.md b/docs/mcp.md index c1568ae63c..09d114cf0b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6160,3 +6160,29 @@ one, out of range values and a request with no fix on. ```json {"name":"run_command","arguments":{"command":"addon.color.printFixes","params":{"scope":"document","inkLimit":300,"removeWhiteOverprint":true,"overprintBlack":100}}} ``` + +## Arrange Tools add-on + +Arrange Tools is a built-in add-on that lays out, swaps, replaces and sizes selected objects: its commands are +`addon.arrange.*`, and in the desktop app it lives in Object › Plug-ins › Arrange Tools. Each command acts on the +top-level selected objects and is one undo step; a run that moves nothing makes no step. Places and sizes are measured +as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid, which uses visual bounds. + +| Command | Parameters (default) | Does | +|---|---|---| +| `addon.arrange.grid` | `layout`: `grid`, `row`, `column` (`grid`); `columns`: 1…10000 (⌈√count⌉, never more than the count); `gapX` pt (10), `gapY` pt (`gapX`), each −1000000…1000000; `centerOnArtboard` (false) | Lays the objects out in their stacking order from the back, left to right and top to bottom. Each cell is as wide as the widest object in its column and as tall as the tallest in its row, and each object is centred in its cell. The grid starts at the selection's top-left, or is centred on the artboard under the selection's centre (the first artboard when none is there). → `{count}` | +| `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. | +| `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | +| `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | + +Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the +active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, +and fails with nothing selected. Arrange in Grid…, Replace with Top Object… and Set Size of Each… open dialogs +(`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace` and `arrangeSize`) whose fields are the +command's parameters, with Preview; Set Size of Each's `__width` and `__height` say which sizes OK applies. + +```json +{"name":"run_command","arguments":{"command":"addon.arrange.grid","params":{"columns":4,"gapX":12,"gapY":12}}} +{"name":"run_command","arguments":{"command":"addon.arrange.replace","params":{"fit":"proportional"}}} +{"name":"run_command","arguments":{"command":"addon.arrange.size","params":{"width":72,"proportional":true}}} +``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 38d9ba8b6b..639e286939 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Export for Screens laid out as Illustrator's, with Export PDFs As and sub-folders by scale or format; previously: Artwork Cleanup add-on: Join Point Text, #4826; scores unchanged; previously: G13: Direct Selection snaps a dragged line end square to straight paths and grazing curves; Path Precision Tools add-on: Shared Edge Merge Tool; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Arrange Tools add-on; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -1236,7 +1236,7 @@ applies to fills). Tests: `color::gradient::tests` (perceptual midpoint, expansi ## Artwork Cleanup add-on (2026-10-30) -A VectorCraft addition, not an Illustrator feature, so no area score moves. Object › Plug-ins › Artwork Cleanup and its +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Artwork Cleanup and its panel run `addon.cleanup.*`: Simplify Anchors (Keep Shape) on the shared kernel `vectorcraft_pathops::addons::keep_shape`, a health check of 16 kinds of issue on the selection or the document with Show, Fix Selected and Fix All (each one undo step), Deep Ungroup and Rejoin Path Pieces. Tests: `addons::` in @@ -1255,7 +1255,7 @@ refusals), `addons::cleanup::tests` in `vectorcraft-ui-egui` (the submenu and th ## Path Precision Tools add-on (2026-10-30) -A VectorCraft addition, not an Illustrator feature, so no area score moves. Object › Plug-ins › Path Precision Tools, +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools, its Anchor Inspector panel and three tools kept out of the shipped toolbars (listed in the All Tools drawer) run `addon.pathtools.*`: an Anchor Eraser Brush on the shared keep-shape kernel, an Extend Path tool (straight, stretched curve or arc; shortening back along the path), a Measure & Inspect tool with hover readouts (lengths, area, curvature, @@ -1318,7 +1318,7 @@ ends), `addons::shared_edge` in `vectorcraft-tools`, `cmd::addons::pathtools::sh ## Smart Pen add-on (2026-10-30) -A VectorCraft addition, not an Illustrator feature, so no area score moves. Object › Plug-ins › Smart Pen selects the +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Smart Pen selects the Smart Pen Tool (kept out of the shipped toolbars, listed in the All Tools drawer, no shortcut) and opens its panel. The tool draws with a straight or curved next segment (a curve after a straight segment leaves it tangent), smooth drags with Alt, Shift and Space, Tab to switch a segment, a rubber band, closing, joining and continuing open ends; and edits @@ -1333,7 +1333,7 @@ through the session) and `addons::pen::tests` in `vectorcraft-ui-egui` (the subm ## Color Effects add-on (2026-10-30) -A VectorCraft addition, not an Illustrator feature, so no area score moves. Effect › Color Effects adds live Exposure +A VectorCraft addition, not a feature of the reference app, so no area score moves. Effect › Color Effects adds live Exposure (stops of linear light, offset and gamma), Desaturate and Invert Colors as colour adjustments evaluated with those of Effect › Color Adjustments (`vectorcraft_effects::addons::color`), and `addon.color.filter` applies any colour adjustment to the colours themselves through the Edit Colors pass. Object › Plug-ins › Color Effects and its panel reach them. @@ -1360,10 +1360,29 @@ tints, curves, multiplied inks, skip spot), `duotone_*` and `cmd::addons::color: params and RGB documents refused), and `the_duotone_dialog_has_a_row_per_tone_and_the_curve_of_one` and `print_ink_fixes_opens_its_options_and_runs_on_ok` in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Color Effects add-on. +## Arrange Tools add-on (2026-10-31) + +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools: Arrange in +Grid… lays the top-level selected objects out in their stacking order from the back, in rows and columns (⌈√count⌉ by +default), one row or one column, each centred in a cell as wide as its column's widest object and as tall as its row's +tallest (visual bounds), with horizontal and vertical gaps, from the selection's top-left or centred on the artboard; +Swap Objects swaps the bounds centres of two objects, and Swap Objects and Sizes their widths and heights too; Replace +with Top Object… puts a copy of the topmost selected object centred on each of the others, in its stacking place, at its +own size, the replaced object's size or fitted inside it in proportion, deleting or keeping the replaced objects; Set +Size of Each… gives every object an exact width and/or height (one side may follow in proportion) about one of the nine +reference points; Zoom to Selection fits the active view to the selection. Sizes and places are measured as +`object.setBounds` measures them (Use Preview Bounds), strokes and effects scale as Scale Strokes & Effects says, each +command is one undo step, and the three dialogs preview on the canvas. Tests: `cmd::addons::arrange::tests` in +`vectorcraft-engine` (grid, row, column and artboard centring, visual bounds, swap with and without sizes and stroke +scaling, replace with each fit and kept originals in stacking order, size with proportions and reference points, one +undo step, off states, bad params refused), `addons::arrange::tests` in `vectorcraft-ui-egui` (the submenu, the +dialogs, Preview and Cancel, Zoom to Selection) and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. + ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Arrange Tools add-on (a VectorCraft addition): evidence added; scores unchanged. | | 2026-10-31 | minor | Guides and snapping: Snap to Perpendicular and Snap to Tangent apply to an existing line's end dragged with Direct Selection, as the public pages describe for editing existing lines (the end anchor of a straight segment, not mid-line anchors or curved segments); a regression test covers both snaps, both toggles and non-snapping controls (#2530); scores and estimates unchanged. | | 2026-10-30 | minor | File formats: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | | 2026-10-31 | minor | Path Precision Tools add-on: the Shared Edge Merge Tool and Keep Shared Points Together; evidence added; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index afd2fac04d..add5e8fd75 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Export for Screens laid out as Illustrator's; previously: Properties: Blend Options in Quick Actions for one selected blend with any tool, #4817; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Arrange Tools add-on; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -134,7 +134,7 @@ tools, never checked side by side) isn't captured row by row. | Corners between curved sides (#1144), Relative rounding | done | #1144 closed; Relative rounding in the Corners dialog (Relative / Absolute, radius as a percentage of each corner's maximum, kept as the shape is resized; `object.setLiveShape` `relativeRadii`, #3091, `tests_livecorners::relative_corner_rounding_keeps_fraction_on_resize`) | | Pie widgets on a live ellipse: drag one to set Pie Start or End Angle, double-click one to make the ellipse whole | done | Selection tool, with the bounding box showing | | Isolation mode by double-click (groups and single objects), breadcrumbs, Esc to exit | done | Single paths, compound paths, images, meshes and placed files isolate too ([helpx: Isolate objects](https://helpx.adobe.com/africa/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) | -| "Magnetic" moves of selected anchors with a modifier (#955 request) | missing | not an Illustrator feature as documented; under discussion | +| "Magnetic" moves of selected anchors with a modifier (#955 request) | missing | not a feature of the reference app as documented; under discussion | | Coinciding anchors of overlapping objects: the selected object's anchor is taken, also under another object | done | #1508 | ## Smart guides and snapping @@ -326,16 +326,17 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, <https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>); arcs, spirals, flares and Pen paths are not turned | | Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 | | Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | -| Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not an Illustrator feature, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its seven tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not an Illustrator feature, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not an Illustrator feature, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its four tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/shape.rs` and their tests; not an Illustrator feature, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its six tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not an Illustrator feature, so it is not scored | -| Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point); an Alt-drag away from paths selects the points inside a marquee | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not an Illustrator feature, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its three tools (Anchor Eraser Brush, Extend Path, Measure & Inspect), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and runs Add Points at / Split at Crossings; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not an Illustrator feature, so it is not scored | -| Artwork Cleanup add-on (VectorCraft addition): Object › Plug-ins › Artwork Cleanup opens its panel, which checks the selection or the document for 16 kinds of issue, lists them with counts, and shows or fixes the picked rows or all of them, each fix one undo step; Simplify Anchors (Keep Shape), Rejoin Path Pieces and Deep Ungroup open their options first | done | `addon.cleanup.*`, `crates/ui-egui/src/addons/cleanup.rs` and its tests; not an Illustrator feature, so it is not scored | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | +| Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its seven tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its four tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/shape.rs` and their tests; not a feature of the reference app, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its six tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | +| Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point); an Alt-drag away from paths selects the points inside a marquee | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its three tools (Anchor Eraser Brush, Extend Path, Measure & Inspect), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and runs Add Points at / Split at Crossings; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | +| Artwork Cleanup add-on (VectorCraft addition): Object › Plug-ins › Artwork Cleanup opens its panel, which checks the selection or the document for 16 kinds of issue, lists them with counts, and shows or fixes the picked rows or all of them, each fix one undo step; Simplify Anchors (Keep Shape), Rejoin Path Pieces and Deep Ungroup open their options first | done | `addon.cleanup.*`, `crates/ui-egui/src/addons/cleanup.rs` and its tests; not a feature of the reference app, so it is not scored | | Artwork Cleanup add-on text tools (VectorCraft addition): the panel's Text row, which the panel can hide, and Object › Plug-ins › Artwork Cleanup set the alignment of point type keeping its place, break type into lines (Shift-click: paragraphs), words or glyphs, split type at the cursor, reset a text transform (Alt-click: and its horizontal scale), combine point type, remove line or paragraph breaks and replace missing fonts, each one undo step | done | `addon.cleanup.*` text commands, `crates/ui-egui/src/addons/cleanup.rs` and its tests; a VectorCraft addition, so it is not scored | -| Color Effects add-on (VectorCraft addition): live Exposure, Desaturate and Invert Colors in Effect › Color Effects and Object › Plug-ins › Color Effects; its panel picks a colour adjustment and its values and adds it as a live effect or applies it as a filter, into the colours, as one undo step; Select by Color Kind selects the objects that use spot colours, carry colour effects, or are RGB, CMYK or grayscale images; Vector Halftone draws an object as halftone dots live (the dots Object › Vector Halftone makes), which Expand Appearance and the exporters write as paths; Duotone prints each colour's tone with one to four inks (a tint of a spot tone's swatch, or the CMYK mix of several), live or as a filter, its dialog a row per tone and the picked tone's curve; Print Ink Fixes (a CMYK document's ink limit, white overprint removed, black overprint set) opens its options from the submenu and the panel's Inks | done | `addon.color.*`, `crates/ui-egui/src/addons/color.rs` and its tests; not an Illustrator feature, so it is not scored | +| Color Effects add-on (VectorCraft addition): live Exposure, Desaturate and Invert Colors in Effect › Color Effects and Object › Plug-ins › Color Effects; its panel picks a colour adjustment and its values and adds it as a live effect or applies it as a filter, into the colours, as one undo step; Select by Color Kind selects the objects that use spot colours, carry colour effects, or are RGB, CMYK or grayscale images; Vector Halftone draws an object as halftone dots live (the dots Object › Vector Halftone makes), which Expand Appearance and the exporters write as paths; Duotone prints each colour's tone with one to four inks (a tint of a spot tone's swatch, or the CMYK mix of several), live or as a filter, its dialog a row per tone and the picked tone's curve; Print Ink Fixes (a CMYK document's ink limit, white overprint removed, black overprint set) opens its options from the submenu and the panel's Inks | done | `addon.color.*`, `crates/ui-egui/src/addons/color.rs` and its tests; not a feature of the reference app, so it is not scored | ## Look and feel @@ -376,6 +377,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Arrange Tools add-on (a VectorCraft addition): Object › Plug-ins › Arrange Tools; scores and estimates unchanged | | 2026-10-31 | minor | Export for Screens is laid out as Illustrator's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged | | 2026-10-31 | minor | Properties: Quick Actions has Blend Options for one selected blend with any tool, not only the Blend tool, as the blending page describes (#4817); scores unchanged | | 2026-10-31 | minor | Smart guides and snapping: Snap to Perpendicular and Snap to Tangent for an existing line's end dragged with Direct Selection (#2530), so the tangent and perpendicular row is done; scores and estimates unchanged | From 427de74f376f892fd076545a7b0c42e4a75b6e9b Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 21:46:47 +0700 Subject: [PATCH 089/260] Fix #4890: Alt with Direct Selection marquee-selects whole paths --- crates/tools/src/direct.rs | 31 ++++++++++++++++++++----------- crates/tools/src/direct/tests.rs | 21 +++++++++++++++++++++ 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index c27466935e..c1aae51a4e 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -8,7 +8,9 @@ //! Group Selection's clicks do), drag a direction handle to //! reshape (Shift keeps it at 45° steps round its anchor, Alt moves it alone; smart guides snap //! it), marquee to select anchors (Shift-drag toggles them: the selected ones inside are -//! deselected, the others selected), drag a corner widget of any path (a star, a pen path) to round its corners +//! deselected, the others selected; with Alt held at the press, as Group Selection for the drag, +//! it selects every object it touches, whole), drag a corner widget of any path (a star, a pen +//! path) to round its corners //! (the selected ones when anchors are selected; Alt-click cycles their kind, double-click opens //! the Corners dialog). //! Group Selection: click selects the leaf; each further click on it adds the next enclosing group; @@ -103,6 +105,9 @@ enum State { /// Group Selection, E pressed an odd number of times during the drag: the marquee selects /// only the objects that lie entirely inside it, whole. enclosed: bool, + /// Direct Selection with Alt held at the press, which makes it the Group Selection tool + /// for the drag: the marquee selects every object it touches, whole (#4890). + whole: bool, }, Corner(CornerDrag), /// Dragging a bracket of type on a path. @@ -756,7 +761,7 @@ impl Tool for DirectSelectionTool { if let Some(out) = self.press_hidden(cx, ev, p) { return out; } - self.state = State::Marquee { start: p, cur: p, toggle: ev.mods.shift, enclosed: false }; + self.state = State::Marquee { start: p, cur: p, toggle: ev.mods.shift, enclosed: false, whole: ev.mods.alt }; vec![] } (PointerKind::Drag, State::MoveAnchors { start, grab, began }) => self.drag_move_anchors(cx, ev, p, (start, grab, began)), @@ -839,8 +844,8 @@ impl Tool for DirectSelectionTool { self.state = State::Idle; self.mesh.release(cx).unwrap_or_default() } - (PointerKind::Drag, State::Marquee { start, toggle, enclosed, .. }) => { - self.state = State::Marquee { start, cur: p, toggle, enclosed }; + (PointerKind::Drag, State::Marquee { start, toggle, enclosed, whole, .. }) => { + self.state = State::Marquee { start, cur: p, toggle, enclosed, whole }; vec![] } (PointerKind::Drag, State::Corner(mut c)) => { @@ -875,7 +880,7 @@ impl Tool for DirectSelectionTool { self.guides.clear(); vec![Action::Commit] } - (PointerKind::Up, State::Marquee { start, toggle, enclosed, .. }) => self.release_marquee(cx, p, (start, toggle, enclosed)), + (PointerKind::Up, State::Marquee { start, toggle, enclosed, whole, .. }) => self.release_marquee(cx, p, (start, toggle, enclosed, whole)), _ => vec![], } } @@ -913,6 +918,8 @@ impl Tool for DirectSelectionTool { match self.state { // Alt-dragging leaves a copy behind. State::MoveObject { began: true, .. } if m.alt => return Cursor::SelectionCopy, + // An Alt-marquee is Group Selection's until it is released. + State::Marquee { whole: true, .. } => return Cursor::GroupSelection, // Bending a segment keeps the cursor that offered it. State::Segment { began: true, .. } | State::SpineSegment { began: true, .. } => return Cursor::ReshapeSegment, // A drag shows the filled arrow, hollow while it snaps to a point or a guide. @@ -1102,7 +1109,7 @@ impl DirectSelectionTool { if let Some(out) = self.press_hidden(cx, ev, p) { return out; } - self.state = State::Marquee { start: p, cur: p, toggle: ev.mods.shift, enclosed: false }; + self.state = State::Marquee { start: p, cur: p, toggle: ev.mods.shift, enclosed: false, whole: false }; return vec![]; }; // A compound path's paths are picked one at a time, below the compound path (#2441). @@ -1381,7 +1388,7 @@ impl DirectSelectionTool { (false, None, None, None) => group.map(|g| Action::Exec("select.add".into(), json!({"ids": [g.0]}))).into_iter().collect(), } } - fn release_marquee(&mut self, cx: &ToolContext, p: Point, (start, toggle, enclosed): (Point, bool, bool)) -> Vec<Action> { + fn release_marquee(&mut self, cx: &ToolContext, p: Point, (start, toggle, enclosed, whole): (Point, bool, bool, bool)) -> Vec<Action> { self.state = State::Idle; let r = Rect::from_points(start, p); if r.width() < cx.tol(3.0) && r.height() < cx.tol(3.0) { @@ -1392,14 +1399,16 @@ impl DirectSelectionTool { return vec![Action::Exec("select.none".into(), json!({}))]; } // With Group Selection's enclosed marquee, the tool selects the objects inside it - // (members of groups too), each whole, as a click selects one. - if enclosed { + // (members of groups too), each whole, as a click selects one; with an Alt-marquee, every + // object it touches, each whole. + if enclosed || whole { let mut touched = vectorcraft_doc::hit::marquee(cx.doc, r, cx.isolation, true); let editable = cx.doc.editable(); touched.retain(|id| editable(*id)); - let ids: Vec<Value> = crate::select::inside(cx, r, touched).into_iter().map(|id| json!(id.0)).collect(); + let picked = if enclosed { crate::select::inside(cx, r, touched) } else { touched }; + let ids: Vec<Value> = picked.into_iter().map(|id| json!(id.0)).collect(); let art = Action::Exec(if toggle { "select.toggle" } else { "select.set" }.into(), json!({ "ids": ids })); - return std::iter::once(art).chain(crate::rulerguide::marquee_select(cx, r, true)).collect(); + return std::iter::once(art).chain(crate::rulerguide::marquee_select(cx, r, enclosed)).collect(); } // Anchors inside the rect, on editable paths inside isolation mode. let mut sel: Vec<(NodeId, Vec<AnchorRef>)> = vec![]; diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index cb852c5531..6a7be3eccd 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -922,6 +922,27 @@ fn shift_marquee_toggles_anchors() { } } +/// #4890: Alt held at the press makes a Direct Selection marquee Group Selection's for the drag: +/// it selects each path it touches whole (with Shift, toggles it), not the anchors inside it, and +/// leaves the paths it misses; the Group Selection cursor stays until the release. +#[test] +fn an_alt_marquee_selects_the_paths_it_touches_whole() { + let (d, a, _) = two_squares(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Default::default() }; + let alt_shift = Mods { shift: true, ..alt }; + for (mods, cmd) in [(alt, "select.set"), (alt_shift, "select.toggle")] { + let mut t = DirectSelectionTool::new(false); + // Round A's top-right corner only; B (300..400) is left out. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 50.0).with_mods(mods)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 250.0, 150.0).with_mods(mods)); + assert_eq!(t.cursor(&cx, Point::new(250.0, 150.0), mods), Cursor::GroupSelection, "{mods:?}"); + let up = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 150.0).with_mods(mods)); + assert_eq!(up, vec![Action::Exec(cmd.into(), json!({"ids": [a.0]}))], "{mods:?}"); + } +} + /// Group Selection: E pressed during a marquee drag makes it select the objects entirely inside /// it whole, a group's member without its group. Direct Selection does not take E. #[test] From 83c158703a22e4f5033c08a7f035566e48cf7cc6 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 21:48:48 +0700 Subject: [PATCH 090/260] Fix #4891: Direct Selection selects and moves an object by its center point Docs: ui-parity and target-app-parity rows for #4890 and #4891. --- crates/tools/src/direct.rs | 28 ++++++++++++++++++++++++++ crates/tools/src/direct/tests.rs | 34 ++++++++++++++++++++++++++++++++ docs/target-app-parity.md | 5 ++++- docs/ui-parity.md | 5 ++++- 4 files changed, 70 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index c1aae51a4e..c519b2e56d 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -38,6 +38,8 @@ //! them all, and the arrow keys nudge them; otherwise the type is selected whole. Dragging an anchor of type on //! a path's path reshapes the path (`text.reshapePath`): the text reflows along it. //! Dragging the brackets of selected type on a path moves or flips it ([`crate::pathtype`]). +//! A press on a selected object's centre point (Attributes panel › Show Center) selects the object +//! whole, and a drag from it moves the object. //! //! A press on the stroke of a path that isn't selected as a whole selects that segment's two anchors //! (the fill, or Alt, selects the whole path); dragging the segment bends it if it's curved, else @@ -513,6 +515,16 @@ fn nearest_anchor(pd: &PathData, p: Point, tol: f64) -> Option<(usize, usize, Po pd.anchors().map(|(si, ai, a)| (si, ai, a.p)).filter(|(.., a)| a.distance(p) <= tol).min_by(|x, y| x.2.distance(p).total_cmp(&y.2.distance(p))) } +/// The selected object whose centre point (Attributes panel › Show Center), drawn while it is +/// selected, is within `tol` of `p`: (object, where the point is). +fn hit_center(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, Point)> { + let (symbols, editable) = (cx.doc.symbol_boxes(), cx.doc.editable()); + cx.selection.objects.iter().copied().filter(|id| editable(*id) && in_scope(cx.doc, cx.isolation, *id)).find_map(|id| { + let c = cx.doc.node(id).filter(|n| n.shows_center())?.geometric_bounds_with(&symbols)?.center(); + (c.distance(p) <= tol).then_some((id, c)) + }) +} + /// An edge of an area type frame under `p`, topmost first: (text, the edge's two anchors). fn hit_frame_edge(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, Vec<AnchorRef>)> { anchor_owners(cx, is_area_type).into_iter().find_map(|id| { @@ -742,6 +754,9 @@ impl Tool for DirectSelectionTool { if let Some((id, si, ai, grab)) = hit_anchor(cx, p, point) { return self.press_anchor(cx, ev, p, (id, si, ai, grab)); } + if let Some((id, center)) = hit_center(cx, p, point) { + return self.press_center(cx, ev, p, id, center); + } if let Some((id, anchors)) = hit_frame_edge(cx, p, tol) { self.frame.clear(); return self.press_type_area(cx, id, vec![(id, anchors)], p, ev.mods.shift); @@ -1198,6 +1213,19 @@ impl DirectSelectionTool { } vec![] } + /// Press on the centre point of object `id`: it selects the object whole (Shift toggles it), + /// as a press on its fill does, and a drag moves it held by that point (#4891). + fn press_center(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point, id: NodeId, center: Point) -> Vec<Action> { + self.state = State::MoveObject { start: p, grab: None, hold: center, began: false, deselect: None }; + self.frame.clear(); + if ev.mods.shift { + return vec![Action::Exec("select.toggle".into(), json!({"id": id.0}))]; + } + if cx.selection.partial(id).is_some() || cx.selection.segments.contains_key(&id) { + return vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]; + } + vec![] + } fn press_object(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point, tol: f64, mut h: vectorcraft_doc::hit::Hit) -> Vec<Action> { if let Some(part) = cx.doc.node(h.leaf).and_then(|n| compound_part_at(n, p, tol)) { h.ancestry.push(part); diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 6a7be3eccd..b7892cc2d3 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -943,6 +943,40 @@ fn an_alt_marquee_selects_the_paths_it_touches_whole() { } } +/// #4891: a press on the centre point a selected object shows (Show Center) selects it whole, and +/// a drag from there moves it by the drag as one Move; the square is unfilled, so the press finds +/// no fill there. +#[test] +fn the_centre_point_selects_and_moves_the_object_whole() { + let (mut d, id) = doc_with_rect(); + let n = d.node_mut(id).unwrap(); + n.appearance.items.retain(|i| !matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))); + n.edit_attrs(|a| a.show_center = Some(true)); + let p = paint(); + // One anchor selected: the square shows its centre, (150, 150). + let one = anchors_of(id, &[(0, 0)]); + let mut t = DirectSelectionTool::new(false); + let c = cx(&d, &one, &p); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 151.0, 149.0)), vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 151.0, 149.0)).is_empty()); + // Selected whole: the press keeps the selection and the drag moves the square. + let mut whole = Selection::default(); + whole.set([id]); + let c = ToolContext { smart_guides: false, ..cx(&d, &whole, &p) }; + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 170.0, 140.0)); + let moved = json!({"matrix": matrix_json(vectorcraft_geom::Affine::translate(Vec2::new(20.0, -10.0))), "copy": false}); + assert_eq!(a, vec![Action::Begin("Move".into()), Action::Preview("object.transform".into(), moved)]); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 170.0, 140.0)), vec![Action::Commit]); + // Unselected, the centre isn't shown and a press there starts a marquee. + let none = Selection::default(); + let mut t = DirectSelectionTool::new(false); + let c = cx(&d, &none, &p); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)).is_empty()); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 170.0, 140.0)); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Marquee(_)))); +} + /// Group Selection: E pressed during a marquee drag makes it select the objects entirely inside /// it whole, a group's member without its group. Direct Selection does not take E. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 639e286939..340854a0de 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Arrange Tools add-on; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Direct Selection: Alt-marquee selects whole paths, #4890; the centre point selects and moves its object, #4891; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -704,8 +704,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur `path.reshapeSegment`, `object.blend.spine.reshapeSegment`, `path.convertAnchor`, `path.curvatureEdit`, `path.insertAnchor`, `path.moveAnchors`, `path.reshape`, `path.close` and the Pencil, Curvature, Knife, Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a number, point or handle given as text, such as "10", and leave the document unchanged; `path.convertAnchor` refuses an `x` without a `y`, or a `y` without an `x`. `path.close` and `path.setHandle` (`independent`), `path.moveAnchors` (`patterns`), the Pencil (`closed`, `keepSelected`, `fill`), Curvature (`closed` and a point's `corner`), `path.curvatureEdit` (`corner`), `path.reshapeSegment` (`perpendicular`) and the Blob Brush (`keepSelected`, `mergeOnlySelection`, `merge`) refuse a value other than true, false or null, such as "true", and leave the document unchanged. Direct Selection's marquee selects the frame anchors of area type that lie inside it, and a click on a frame anchor selects that one; Shift toggles them. The selected frame anchors show filled. A drag of one of them moves all of them, the arrow keys nudge them, and the type reflows at its size (`text.reshapeArea`, which takes `items` to move the anchors of several frames in one step), as [Create text](http://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html) and [Selecting objects](http://web.archive.org/web/20211230015528/https://helpx.adobe.com/illustrator/using/selecting-objects.html) describe. When the selection also holds other objects, path anchors or ruler guides, or when another change to the document or the selection follows the pick, the type is selected whole. + A press on a selected object's centre point (Attributes panel › Show Center) selects the object whole, and a drag from it moves the object as one Move, held by that point (#4891; test `the_centre_point_selects_and_moves_the_object_whole`). - **Group Selection (#2441):** a click picks one path of a compound path (its outline within the pick tolerance, else the innermost path whose area holds the click: the outer shape or a hole), Shift-click adds another, and a click on a selected path adds the compound path, as a click on a group member climbs to its group. A path selected this way moves, rotates and scales on its own; paint still goes to the compound path. With Direct Selection, an Alt-click on a path selected whole adds its group, and each further Alt-click adds the next group up, as Group Selection's clicks do; the climb stops below the layer and its sublayers and at the isolated object. An Alt-drag still copies the selection, and Alt+Shift-click on a segment or the fill still adds or removes the path. Public references: [Select objects](https://web.archive.org/web/20250904012025/https://helpx.adobe.com/illustrator/using/selecting-objects.html) and [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copies). + With Alt held at the press, a Direct Selection marquee is Group Selection's for the drag: it selects every path it touches, whole (Shift toggles them), not the anchors inside it, and the Group Selection pointer stays until the release (#4890; test `an_alt_marquee_selects_the_paths_it_touches_whole`). With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. With the Anchor Point tool, Shift held at the press on an anchor (or a selected blend's spine point) moves it, handles and all, instead of pulling out handles; Shift kept down keeps the move at 45° steps, and a Shift-click that doesn't move leaves the anchor as it was (`path.moveAnchor`). A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. @@ -1382,6 +1384,7 @@ dialogs, Preview and Cancel, Zoom to Selection) and `command_sweep`. Commands: ` | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Selection tools: with Alt held at the press, a Direct Selection marquee selects every path it touches whole and keeps the Group Selection pointer (#4890); a press on a selected object's centre point selects the object whole and a drag from it moves it (#4891); regression tests in `direct/tests.rs`; scores and estimates unchanged. | | 2026-10-31 | minor | Arrange Tools add-on (a VectorCraft addition): evidence added; scores unchanged. | | 2026-10-31 | minor | Guides and snapping: Snap to Perpendicular and Snap to Tangent apply to an existing line's end dragged with Direct Selection, as the public pages describe for editing existing lines (the end anchor of a straight segment, not mid-line anchors or curved segments); a regression test covers both snaps, both toggles and non-snapping controls (#2530); scores and estimates unchanged. | | 2026-10-30 | minor | File formats: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index add5e8fd75..2ad33fd86a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Arrange Tools add-on; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Direct Selection: an Alt-marquee selects the paths it touches whole, #4890; a click on a selected object's centre point selects it whole and a drag moves it, #4891; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -129,6 +129,8 @@ tools, never checked side by side) isn't captured row by row. | Direct Selection and Group Selection pick only inside the isolated object in isolation mode | done | #1666 | | Group Selection picks one path of a compound path (the outer shape or a hole) and moves it on its own; a second click adds the compound path | done | #2441; Shift-click on a selected member deselects it on release | | Direct Selection, Group Selection and the Selection tool take a clipping path (a clip group's, or a layer's clipping mask) on its outline, within the selection tolerance, even where the art it clips lies over its edge | done | `HitOptions::clip_outlines`; Select Behind lists the same; the eyedropper and the tools that act on what is drawn take the art | +| Alt with Direct Selection makes a marquee Group Selection's for the drag: it selects every path it touches, whole (Shift toggles them), and the Group Selection pointer stays until the release | done | #4890 | +| Direct Selection: a click on a selected object's centre point (Attributes › Show Center) selects the object whole, and a drag from it moves the object in one undo step | done | #4891 | | Escape cancels a Direct Selection drag | done | #1803 (#1743) | | Live Corners widgets (radius readout, Alt-click cycles kind, double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239); a press-and-drag on a widget of a path selected whole still rounds every corner (#908), and adding widgets to the selection by Shift-click (#1232) is missing; the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | | Corners between curved sides (#1144), Relative rounding | done | #1144 closed; Relative rounding in the Corners dialog (Relative / Absolute, radius as a percentage of each corner's maximum, kept as the shape is resized; `object.setLiveShape` `relativeRadii`, #3091, `tests_livecorners::relative_corner_rounding_keeps_fraction_on_resize`) | @@ -377,6 +379,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Direct Selection: with Alt held at the press, a marquee selects every path it touches whole and keeps the Group Selection pointer while dragging (#4890); a click on a selected object's centre point (Show Center) selects the object whole, and a drag from it moves the object (#4891); scores unchanged | | 2026-10-31 | minor | Arrange Tools add-on (a VectorCraft addition): Object › Plug-ins › Arrange Tools; scores and estimates unchanged | | 2026-10-31 | minor | Export for Screens is laid out as Illustrator's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged | | 2026-10-31 | minor | Properties: Quick Actions has Blend Options for one selected blend with any tool, not only the Blend tool, as the blending page describes (#4817); scores unchanged | From 9b407edbbe00176925b3654005ed39567ec70807 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 21:59:23 +0700 Subject: [PATCH 091/260] Docs: ROADMAP progress log for 2026-10-31 --- ROADMAP.md | 4 +++- docs/target-app-parity.md | 6 +++--- docs/ui-parity.md | 3 ++- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 515e2824d6..3511fe3f23 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -9,7 +9,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Arrange Tools add-on: Arrange in Grid, Swap Objects, Replace with Top Object, Set Size of Each and Zoom to Selection; headline numbers unchanged; previously: OpenType SVG colour fonts draw and export as vector art; previously: COLR colour fonts (v0 and v1) draw and export as vector art; previously: G2: the Effect Gallery shipped (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step; remaining: filter thumbnails and a preview area inside the dialog; G2 estimate 4–6 → 1–2 h; Raster effects 82% → 85% (power-user view 49% → 52%), estimated, a modest move because the named missing dialog landed without thumbnails or an in-dialog preview; previously: colour emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; headline numbers unchanged; previously:; Affinity import AF.5: master pages, tables, paragraph formats, shadows, glows, outlines, overlays and embedded documents; ruby (ふりがな) for live text: `type.ruby` sets or removes a reading over a byte range, above or below (right of the column in vertical type), aligned, sized and overhanging or squeezed; saved natively, laid out with line growth, drawn on the canvas and in SVG/PDF (outlines where ruby is present); headline numbers unchanged; previously:; 3D: original Standard, Diffuse, Top Left and Right lighting presets; command access, effective-setting recognition and preview/history; scores and estimates unchanged; Print: Japanese paper sizes in the Print dialog's Media list — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (which keep their ISO 216 sizes), はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判; about 90 community PRs of 2026-10-19: Objects on Path, the Simplify slider, Pencil Edit Selected Paths in the middle of a path, Georgian, and more; Background Export progress dialog with Cancel, #2564; about 85 community PRs of 2026-10-18: Justification…, Word .docx placed as area type, CCITT Group 3 TIFF, Roman Hanging Punctuation, blend spines edited with the Anchor Point tool, shadows and glows in stack order, coloured 3D lights, a Dutch catalog completed; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; about 145 community PRs of 2026-10-17: image-decode overflow guards, opaque floating panels, MCP export cancel and progress, editable Illustrator EPS import, scoped `doc_inspect`, Dutch, Danish and Indonesian, Simplified Chinese messages, screen-reader names; headline numbers unchanged; about 160 community PRs of 2026-10-15/16: PDF import crash fixes, Dimension tool, legacy `.ai` save, Intertwine, web pen input, Image Trace fixes, `.ai`/EPS/PDF import fidelity, Bulgarian, Greek, Swedish and Finnish catalogs; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Progress log rows for the Arrange Tools add-on, Export for Screens as the reference app's dialog and the 2026-10-31 community landings; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. - 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged. - 2026-10-30: Gradient panel presets: a Presets menu applies one of the built-in gradient libraries' presets (grouped by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the current gradient as a preset, kept with the preferences, and deletes saved ones (`gradient.presets.list/apply/save/delete`). - 2026-10-23: Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add a thin overprinting strip of the lighter colour inside the darker one where two solid colours meet, so misregistered plates leave no gap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)), with Thickness, Height/Width, Tint Reduction, Traps with Process Color and Reverse Traps. Illustrator effects 49/50 (SVG Filters remains); Live vector effects hours 6–10 → 4–8; headline numbers unchanged. @@ -203,6 +204,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Progress log row for Export for Screens laid out as the reference app's (#4895) and the 2026-10-31 community landings; headline numbers unchanged. | | 2026-10-31 | minor | Progress log row for the Arrange Tools add-on; headline numbers unchanged. | | 2026-10-29 | minor | Progress log row for the Linux Flatpak clipboard's core Wayland protocol text fallback; headline numbers unchanged. | | 2026-10-29 | minor | Progress log row for the Linux clipboard retry backoff; headline numbers unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 340854a0de..dcf21aa418 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Direct Selection: Alt-marquee selects whole paths, #4890; the centre point selects and moves its object, #4891; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Export for Screens laid out as the reference app's, with Export PDFs As and sub-folders by scale or format) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -19,7 +19,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| -| 2026-10-31 | minor | Export for Screens is laid out as Illustrator's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged. | +| 2026-10-31 | minor | Export for Screens is laid out as the reference app's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged. | | 2026-10-31 | minor | Artwork Cleanup add-on: Join Point Text (`addon.cleanup.joinText`) joins stacked one-line point type into one object, a paragraph per line keeping its baseline (#4826); scores unchanged. | | 2026-10-31 | minor | Width tool: a stroke with a width profile keeps its shape while the view zooms out; the minimum visible width goes to its widest point instead of scaling the whole profile (#995); scores unchanged. | | 2026-10-31 | minor | Patterns: Grid Repeat Options has a Preview checkbox, as the public grid options page lists (#2651); scores unchanged. | @@ -543,7 +543,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Batch…: Override Save and Override Export name each file with the extension of the format the step writes, however the step spells the format (`.svg` and `SVG` give `.svg`, `png8` gives `.png`), in `action.batch`. - Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. - - Export for Screens is laid out as Illustrator's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`. + - Export for Screens is laid out as the reference app's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`. - Save for Web: Preview in Browser writes each preview's page and images to a folder of its own inside `VectorCraft Save for Web` in the system's temporary folder. A later preview, from the same app or another one running, does not overwrite an earlier one. Each preview first removes the preview folders there that are an hour old or older and, on Linux, macOS and FreeBSD, belong to the current user; it leaves other files and folders alone. The folders a preview makes there are open to their owner only on those systems. When `VectorCraft Save for Web` is a link or is not a folder, or on those systems belongs to another user or can be written by other users, the preview goes to a new folder of its own in the temporary folder, which a later preview removes once it is an hour old (`file.saveForWeb.browser`). - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). - Variables (data merge): text, visibility and image variables bound to objects (an object may carry several), dataset rows applied in one undo step (`variable.*`, `dataset.*`) from a Variables panel and Window › Variables, with dialogs to define, bind and edit, Make Text/Visibility/Image Dynamic, Capture/Update Data Set, CSV import/export (`dataset.import` / `dataset.export`), and a row in italics when an edit leaves the art not matching it; an image dataset value is a file path and apply keeps the object's bounds; bindings let go of deleted art and locked art is left alone; every command, like the rest, is drivable over MCP and the CLI. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 2ad33fd86a..df96d05276 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Direct Selection: an Alt-marquee selects the paths it touches whole, #4890; a click on a selected object's centre point selects it whole and a drag moves it, #4891; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Export for Screens laid out as the reference app's) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -379,6 +379,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Export for Screens is laid out as the reference app's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged | | 2026-10-31 | minor | Direct Selection: with Alt held at the press, a marquee selects every path it touches whole and keeps the Group Selection pointer while dragging (#4890); a click on a selected object's centre point (Show Center) selects the object whole, and a drag from it moves the object (#4891); scores unchanged | | 2026-10-31 | minor | Arrange Tools add-on (a VectorCraft addition): Object › Plug-ins › Arrange Tools; scores and estimates unchanged | | 2026-10-31 | minor | Export for Screens is laid out as Illustrator's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged | From cd2b5f77a44695d555ffbea45c086eabfbfb33ac Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 22:07:50 +0700 Subject: [PATCH 092/260] Fix #4882: Rasterize to CMYK makes a CMYK image --- crates/engine/src/cmd/menucmds.rs | 90 +++++++++++++++++++---- crates/engine/src/cmd/rasterfx.rs | 4 +- crates/engine/src/tests/rastersettings.rs | 46 ++++++++++++ docs/target-app-parity.md | 4 +- 4 files changed, 126 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index cd8e0c27c4..7a93ac6176 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -115,7 +115,7 @@ pub fn specs() -> Vec<CommandSpec> { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\", antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded PNG image; each defaults to document.rasterEffectsSettings; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\", antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -513,15 +513,15 @@ pub(crate) fn unique_key(d: &vectorcraft_doc::Document, stem: &str) -> String { } } -/// `doc` rendered over `region` with `opts` as a PNG in colour model `color`, with the note that an -/// image in it couldn't be decoded ([`super::rasterfx::undecoded_warning`]). -fn render_png( +/// `doc` rendered over `region` with `opts` in colour model `color` (premultiplied RGBA), with the +/// note that an image in it couldn't be decoded ([`super::rasterfx::undecoded_warning`]). +fn render_pixels( doc: &vectorcraft_doc::Document, region: Rect, scale: f64, opts: &vectorcraft_render::RenderOptions, color: RasterColorModel, -) -> Result<(Vec<u8>, u32, u32, Option<&'static str>)> { +) -> Result<(vectorcraft_render::Rendered, Option<&'static str>)> { if region.width() * region.height() * scale * scale > MAX_PIXELS || region.width() * scale > 65535.0 || region.height() * scale > 65535.0 { return Err(EngineError::Other("image would be too large; lower the resolution".into())); } @@ -530,13 +530,57 @@ fn render_png( let mut img = r.render_region_with(doc, region, scale, opts); let warning = super::rasterfx::undecoded_warning(failed); RasterEffectsSettings { color_model: color, ..Default::default() }.finish_pixels(&mut img.pixels); + Ok((img, warning)) +} + +/// [`render_pixels`] as a PNG, with its width and height. +fn render_png( + doc: &vectorcraft_doc::Document, + region: Rect, + scale: f64, + opts: &vectorcraft_render::RenderOptions, + color: RasterColorModel, +) -> Result<(Vec<u8>, u32, u32, Option<&'static str>)> { + let (img, warning) = render_pixels(doc, region, scale, opts, color)?; Ok((img.to_png().map_err(EngineError::Other)?, img.width, img.height, warning)) } +/// `doc` over `region` as a CMYK image of its ink amounts (as CMYK exports draw them), with the +/// transparency of `img` (the same art in screen colours) as a greyscale PNG when it has any: a +/// CMYK image keeps no alpha of its own. +fn cmyk_raster( + doc: &vectorcraft_doc::Document, + region: Rect, + scale: f64, + opts: &vectorcraft_render::RenderOptions, + img: &vectorcraft_render::Rendered, +) -> Result<(vectorcraft_doc::ImageBlob, Option<Vec<u8>>)> { + let inks = vectorcraft_render::Renderer::new().render_region_inks(doc, region, scale, opts); + let alpha: Vec<u8> = img.pixels.as_chunks::<4>().0.iter().map(|p| p[3]).collect(); + // Partly covered pixels carry that much ink: divided back out, as straight colour is, since + // the mask applies the coverage. + let straight = |v: u8, a: u8| if a == 0 { 0 } else { ((u32::from(v) * 255 + u32::from(a) / 2) / u32::from(a)).min(255) as u8 }; + let data = inks.as_chunks::<4>().0.iter().zip(&alpha).flat_map(|(p, &a)| p.map(|v| straight(v, a))).collect(); + let blob = vectorcraft_doc::cmyk::Inks::new(img.width, img.height, data) + .and_then(|i| vectorcraft_doc::ImageBlob::cmyk_tiff(&i)) + .ok_or_else(|| EngineError::Other("the CMYK image couldn't be written".into()))?; + if alpha.iter().all(|&a| a == 255) { + return Ok((blob, None)); + } + let mask = image::GrayImage::from_raw(img.width, img.height, alpha) + .ok_or_else(|| EngineError::Other("the image's transparency doesn't fit it".into()))?; + let mut png = Vec::new(); + mask.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| EngineError::Other(e.to_string()))?; + Ok((blob, Some(png))) +} + /// The image Object › Rasterize makes of some art, before it goes in a document /// ([`rasterize_art`]). pub(crate) struct Rasterized { - png: Vec<u8>, + /// A PNG, or a CMYK image of the art's inks ([`cmyk_raster`]). + blob: vectorcraft_doc::ImageBlob, + /// A CMYK image's transparency, a greyscale PNG: it becomes the image's opacity mask. + alpha: Option<Vec<u8>>, width: u32, height: u32, /// Image pixels → document. @@ -551,11 +595,18 @@ impl Rasterized { /// The image as a new object of `d` (its pixels in `d.images`), in a clip group with the art's /// outline when it has one. pub(crate) fn into_node(self, d: &mut vectorcraft_doc::Document) -> Node { - let key = unique_key(d, "raster"); - d.images.insert(key.clone(), vectorcraft_doc::ImageBlob::new("image/png", self.png)); - let id = d.alloc_id(); - let image = ImageObject { key, width: self.width, height: self.height, xf: self.xf, link: None, placement: Default::default(), pixels: None }; - let node = Node::new(id, NodeKind::Image(Box::new(image))); + let image = |d: &mut vectorcraft_doc::Document, blob: vectorcraft_doc::ImageBlob| { + let key = unique_key(d, "raster"); + d.images.insert(key.clone(), blob); + let image = + ImageObject { key, width: self.width, height: self.height, xf: self.xf, link: None, placement: Default::default(), pixels: None }; + Node::new(d.alloc_id(), NodeKind::Image(Box::new(image))) + }; + let mut node = image(d, self.blob); + if let Some(png) = self.alpha { + let art = image(d, vectorcraft_doc::ImageBlob::new("image/png", png)); + node.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true))); + } match self.clip { Some((path, rule)) => super::rasterfx::clip_group(d, path, rule, node), None => node, @@ -565,8 +616,9 @@ impl Rasterized { /// Object › Rasterize's image of `nodes` (drawn also where hidden) with the params `p` of command /// `cmd`, each defaulting to `doc`'s raster effects settings: over the bounds of what the art draws -/// ([`vectorcraft_render::drawn_bounds`]) and the room around them, in whole pixels. -pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec<Node>, p: &Value, cmd: &str) -> Result<Rasterized> { +/// ([`vectorcraft_render::drawn_bounds`]) and the room around them, in whole pixels. With `inks`, +/// a CMYK document's colour model makes a CMYK image ([`cmyk_raster`]); otherwise images are PNGs. +pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec<Node>, p: &Value, cmd: &str, inks: bool) -> Result<Rasterized> { check_numbers(p, &["ppi"], cmd)?; let ppi = f64_or(p, "ppi", doc.raster_effects_ppi); if !(1.0..=2400.0).contains(&ppi) { @@ -630,9 +682,15 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec<Node>, p .flatten() .map(|(bp, rule)| (PathData::from_bezpath(&bp), rule)); let tmp = isolated_doc(doc, nodes); - let (png, width, height, warning) = render_png(&tmp, region, scale, &raster.render_options(RasterFormat::Png), look.color_model)?; + let opts = raster.render_options(RasterFormat::Png); + let (img, warning) = render_pixels(&tmp, region, scale, &opts, look.color_model)?; + let (blob, alpha) = if inks && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk && look.color_model == RasterColorModel::Document { + cmyk_raster(&tmp, region, scale, &opts, &img)? + } else { + (vectorcraft_doc::ImageBlob::new("image/png", img.to_png().map_err(EngineError::Other)?), None) + }; let xf = Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale); - Ok(Rasterized { png, width, height, xf, clip, warning }) + Ok(Rasterized { blob, alpha, width: img.width, height: img.height, xf, clip, warning }) } fn rasterize(s: &mut Session, p: &Value) -> Result<Value> { @@ -640,7 +698,7 @@ fn rasterize(s: &mut Session, p: &Value) -> Result<Value> { let roots = selected_roots(s)?; let st = s.doc()?; let nodes: Vec<Node> = roots.iter().filter_map(|id| st.doc.node(*id).cloned()).collect(); - let image = rasterize_art(&st.doc, nodes, p, C)?; + let image = rasterize_art(&st.doc, nodes, p, C, true)?; let (w, h, warning) = (image.width, image.height, image.warning); if roots.is_empty() { return Err(bad(C, "nothing selected")); diff --git a/crates/engine/src/cmd/rasterfx.rs b/crates/engine/src/cmd/rasterfx.rs index 43ec3e40d7..938d2643a4 100644 --- a/crates/engine/src/cmd/rasterfx.rs +++ b/crates/engine/src/cmd/rasterfx.rs @@ -351,7 +351,9 @@ fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> { whole.appearance.effects.remove(at); (whole.opacity, whole.blend) = (1.0, Default::default()); whole.extras_mut().mask = None; - let image = super::menucmds::rasterize_art(d, vec![whole], &p, "object.rasterize").ok()?; + // shortcut: expanded Rasterize effects stay RGB, as the object keeps its own opacity mask and the + // image's transparency would need one too; upgrade when CMYK images carry alpha. + let image = super::menucmds::rasterize_art(d, vec![whole], &p, "object.rasterize", false).ok()?; Some(image.into_node(d)) } diff --git a/crates/engine/src/tests/rastersettings.rs b/crates/engine/src/tests/rastersettings.rs index b3f1cf50b6..2110e611ea 100644 --- a/crates/engine/src/tests/rastersettings.rs +++ b/crates/engine/src/tests/rastersettings.rs @@ -409,3 +409,49 @@ fn a_gradient_exports_at_the_resolution_the_file_opens_with() { assert_eq!(sizes, [(10, 10)], "saved as {saved}"); } } + +/// Rasterize in a CMYK document's colour model makes a CMYK image of the art's inks (#4882): the +/// image says CMYK, CMYK colours keep their numbers, a CMYK export keeps them, and a transparent +/// background becomes the image's opacity mask. +#[test] +fn rasterize_to_cmyk_makes_a_cmyk_image() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "colorMode": "cmyk"})).unwrap(); + let r = id(&s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"color": {"c": 0.2, "m": 0.4, "y": 0.6, "k": 0.1}, "ids": [r.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true, "ids": [r.0]})).unwrap(); + let want = [51u8, 102, 153, 26]; + let near = |p: &[u8]| p.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 1); + let rasterize = |s: &mut Session, background: &str| { + s.execute("select.set", &json!({"ids": [r.0]})).unwrap(); + let p = json!({"ppi": 72, "colorModel": "cmyk", "background": background, "addAround": 5}); + let img = id(&s.execute("object.rasterize", &p).unwrap()); + assert_eq!(s.execute("image.info", &json!({"id": img.0})).unwrap()["colorMode"], "CMYK"); + let d = &s.doc().unwrap().doc; + let n = d.node(img).unwrap().clone(); + let NodeKind::Image(im) = &n.kind else { panic!("an image") }; + let inks = d.images[&im.key].cmyk().expect("a CMYK image"); + assert_eq!((inks.width, inks.height), (50, 50)); + let at = |x: u32, y: u32| inks.data[((y * 50 + x) * 4) as usize..][..4].to_vec(); + assert!(near(&at(25, 25)), "the fill's inks: {:?}", at(25, 25)); + assert_eq!(at(1, 1), [0; 4], "no ink around the art"); + n + }; + let opaque = rasterize(&mut s, "white"); + assert!(opaque.extras().mask.is_none(), "opaque: no mask"); + // A CMYK TIFF export keeps the image's inks. + let tiff = s.execute("document.export", &json!({"format": "tiff", "colorModel": "cmyk", "ppi": 72})).unwrap(); + let tiff = vectorcraft_format::base64_decode(tiff["dataBase64"].as_str().unwrap()).unwrap(); + let inks = vectorcraft_doc::ImageBlob::new("image/tiff", tiff).cmyk().expect("a CMYK TIFF"); + let at = ((30 * inks.width + 30) * 4) as usize; + assert!(near(&inks.data[at..at + 4]), "exported: {:?}", &inks.data[at..at + 4]); + // Transparent: the art's coverage is the image's opacity mask. + s.execute("edit.undo", &json!({})).unwrap(); + let masked = rasterize(&mut s, "transparent"); + let mask = masked.extras().mask.as_deref().expect("an opacity mask").clone(); + let d = &s.doc().unwrap().doc; + let NodeKind::Image(m) = &mask.art.kind else { panic!("the mask is an image") }; + let alpha = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_luma8(); + assert_eq!((alpha.get_pixel(1, 1).0, alpha.get_pixel(25, 25).0), ([0], [255])); + assert!(mask.clip); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index dcf21aa418..3daa404e82 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Export for Screens laid out as the reference app's, with Export PDFs As and sub-folders by scale or format) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Object › Rasterize with the CMYK colour model makes a CMYK image, #4882; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -19,6 +19,8 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Object › Rasterize in a CMYK document with its CMYK colour model makes a CMYK image of the art's ink amounts (as CMYK exports draw them), so the Properties panel says CMYK and CMYK exports keep its inks; a transparent background becomes the image's opacity mask (#4882); scores unchanged. | +| 2026-10-31 | minor | Export for Screens is laid out as Illustrator's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged. | | 2026-10-31 | minor | Export for Screens is laid out as the reference app's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged. | | 2026-10-31 | minor | Artwork Cleanup add-on: Join Point Text (`addon.cleanup.joinText`) joins stacked one-line point type into one object, a paragraph per line keeping its baseline (#4826); scores unchanged. | | 2026-10-31 | minor | Width tool: a stroke with a width profile keeps its shape while the view zooms out; the minimum visible width goes to its widest point instead of scaling the whole profile (#995); scores unchanged. | From 06043139e644e71d2f57353ee74ace7fe5b02362 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 22:07:51 +0700 Subject: [PATCH 093/260] Fix #4893: New Document saves a preset after More Settings --- crates/ui-egui/src/dialogs/new_document.rs | 75 +++++++++++++++++++--- docs/target-app-parity.md | 3 +- docs/ui-parity.md | 3 +- 3 files changed, 70 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index dde5c83fbd..5d53ebe73e 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -330,15 +330,7 @@ fn details(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, b: &mut ui.add_space(8.0); ui.horizontal(|ui| { form::text(ui, d, "name", DETAILS - 50.0); - if widgets::icon_button(ui, "save", tl!("Save Preset"), d.bool(SAVING), 26.0).clicked() { - let saving = !d.bool(SAVING); - d.fields.insert(SAVING.into(), json!(saving)); - if saving && d.str("presetName").is_empty() { - let template = "Preset {number}"; - let name = crate::i18n::fmt(tl!(template), &[("number", &(app.session.prefs.new_doc_presets.len() + 1).to_string())]); - d.fields.insert("presetName".into(), json!(name)); - } - } + save_button(app, ui, d); }); if d.bool(SAVING) { save_row(app, ui, d); @@ -388,6 +380,19 @@ fn details(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, b: &mut }); } +/// The Save Preset button beside the name: it shows or hides [`save_row`]. +fn save_button(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { + if widgets::icon_button(ui, "save", tl!("Save Preset"), d.bool(SAVING), 26.0).clicked() { + let saving = !d.bool(SAVING); + d.fields.insert(SAVING.into(), json!(saving)); + if saving && d.str("presetName").is_empty() { + let template = "Preset {number}"; + let name = crate::i18n::fmt(tl!(template), &[("number", &(app.session.prefs.new_doc_presets.len() + 1).to_string())]); + d.fields.insert("presetName".into(), json!(name)); + } + } +} + /// Save Preset: the preset's name, Save and Cancel. fn save_row(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { ui.add_space(4.0); @@ -520,7 +525,14 @@ fn show_more(app: &mut VectorcraftApp, ctx: &egui::Context) { ui.add_space(12.0); widgets::label_row(ui, tl!("Name:"), L, |ui| { form::text(ui, &mut d, "name", 300.0); + save_button(app, ui, &mut d); }); + if d.bool(SAVING) { + // Under the name, in the fields' column. + widgets::label_row(ui, "", L, |ui| { + ui.vertical(|ui| save_row(app, ui, &mut d)); + }); + } // Profile: the preset categories (the tabs); Size: the profile's presets. let profiles: Vec<&str> = newdoc::CATEGORIES.iter().map(|c| c.0).collect(); let profile = profiles.iter().find(|p| p.eq_ignore_ascii_case(&d.str("category"))).copied().unwrap_or("[Custom]"); @@ -894,4 +906,49 @@ mod tests { crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(app.session.prefs.recent_new_docs[0].name, "Zine"); } + + /// Save Preset works in More Settings too (#4893), saving its settings: the artboard layout + /// only More Settings shows among them. + #[test] + fn more_settings_saves_a_preset_of_its_settings() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().kind = super::MORE.into(); + set(&mut app, "artboards", json!(4)); + set(&mut app, "artboardLayout", json!({"layout": "column", "spacing": 30})); + set(&mut app, super::SAVING, json!(true)); + set(&mut app, "presetName", json!("Strip")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut time = 0.0; + let mut run = |app: &mut VectorcraftApp, events| { + time += 0.5; + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0))); + let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + out + }; + run(&mut app, vec![]); + let out = run(&mut app, vec![]); + fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Pos2)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect().center())), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let mut texts = vec![]; + out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts)); + assert!(texts.iter().any(|(t, _)| t == "Preset Name"), "the preset's name field shows"); + let at = texts.iter().find(|(t, _)| t == "Save").map(|(_, p)| *p).expect("a Save button"); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(&mut app, vec![egui::Event::PointerMoved(at), press(true)]); + run(&mut app, vec![press(false)]); + let saved = app.session.prefs.new_doc_presets.iter().find(|p| p.name == "Strip").expect("saved"); + assert_eq!(saved.artboards, 4); + assert_eq!((saved.layout, saved.spacing), (super::ArtboardLayout::Column, 30.0)); + assert_eq!((field(&app, "category"), field(&app, "preset"), field(&app, super::SAVING)), (json!("Saved"), json!("Strip"), json!(false))); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, super::MORE, "More Settings stays open"); + } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3daa404e82..e7e762140a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Object › Rasterize with the CMYK colour model makes a CMYK image, #4882; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (New Document: Save Preset in More Settings, #4893; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -19,6 +19,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | New Document: More Settings has the Save Preset button beside the name too, saving its settings (artboard layout included) as a preset (#4893); scores unchanged. | | 2026-10-31 | minor | Object › Rasterize in a CMYK document with its CMYK colour model makes a CMYK image of the art's ink amounts (as CMYK exports draw them), so the Properties panel says CMYK and CMYK exports keep its inks; a transparent background becomes the image's opacity mask (#4882); scores unchanged. | | 2026-10-31 | minor | Export for Screens is laid out as Illustrator's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged. | | 2026-10-31 | minor | Export for Screens is laid out as the reference app's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index df96d05276..3296cb3a5e 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Export for Screens laid out as the reference app's) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (New Document: Save Preset in More Settings, #4893; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -379,6 +379,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | New Document: More Settings has Save Preset beside the name, as Preset Details does, and saves its settings (#4893); scores and estimates unchanged | | 2026-10-31 | minor | Export for Screens is laid out as the reference app's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged | | 2026-10-31 | minor | Direct Selection: with Alt held at the press, a marquee selects every path it touches whole and keeps the Group Selection pointer while dragging (#4890); a click on a selected object's centre point (Show Center) selects the object whole, and a drag from it moves the object (#4891); scores unchanged | | 2026-10-31 | minor | Arrange Tools add-on (a VectorCraft addition): Object › Plug-ins › Arrange Tools; scores and estimates unchanged | From f0da383749be4d2def9f7b7e85e0158f796e0b3e Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 22:53:13 +0700 Subject: [PATCH 094/260] Smooth: the slider smooths bumps and jags into curves, and smooths only a direct-selected section --- crates/engine/src/cmd/draw2/freehand.rs | 5 +- crates/engine/src/cmd/draw2/smooth.rs | 8 +- crates/engine/src/cmd/pathops.rs | 38 +++++++--- crates/engine/src/tests/smooth_path.rs | 53 +++++++++++++ crates/pathops/src/edit.rs | 90 +++++++++++++++++++---- crates/pathops/src/lib.rs | 3 +- crates/pathops/tests/it/hostile_params.rs | 4 +- docs/mcp.md | 7 +- docs/target-app-parity.md | 3 +- docs/ui-parity.md | 3 +- 10 files changed, 179 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 56ff0f3a53..95a2cd94bb 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -45,7 +45,10 @@ fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath { if sp.anchors.len() < 3 { return sp; } - let fitted = po::simplify_with(&PathData::single(sp.clone()), &SimplifyOptions { tolerance: tol, corner_angle_deg: 60.0, straight_lines: false }); + let fitted = po::simplify_with( + &PathData::single(sp.clone()), + &SimplifyOptions { tolerance: tol, corner_angle_deg: 60.0, straight_lines: false, ..Default::default() }, + ); fitted.subpaths.into_iter().next().filter(|s| s.anchors.len() >= 2).unwrap_or(sp) } diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index fd783aa4f7..a4aa1f79a8 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -9,7 +9,7 @@ use super::{ /// Refit the anchors of an open run `a[lo..=hi]` keeping its end points and outer handles. fn refit_run(anchors: &[Anchor], tol: f64) -> Vec<Anchor> { let piece = PathData::single(SubPath::new(anchors.to_vec(), false)); - let fitted = po::simplify_with(&piece, &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false }); + let fitted = po::simplify_with(&piece, &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, ..Default::default() }); let Some(mut out) = fitted.subpaths.into_iter().next().map(|s| s.anchors).filter(|a| a.len() >= 2) else { return anchors.to_vec() }; let (f, l) = (anchors[0], anchors[anchors.len() - 1]); let last = out.len() - 1; @@ -32,8 +32,10 @@ fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Optio if sp.closed { let Some(k) = marked.iter().position(|m| !m) else { // Everything is in range: smooth the whole closed path. - let f = - po::simplify_with(&PathData::single(sp.clone()), &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false }); + let f = po::simplify_with( + &PathData::single(sp.clone()), + &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, ..Default::default() }, + ); return f.subpaths.into_iter().next(); }; // Rotate so an untouched anchor comes first, duplicate it at the end and treat as open. diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 56a223e133..66c01f4c55 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -161,7 +161,7 @@ pub fn specs() -> Vec<CommandSpec> { "Smooth…", ["Object", "Path"], None, - "{level?: 0..100 (50; the Smooth slider: 0 minimum smoothing, the path staying within 0.1% of its longer side, 100 maximum: refitted with curves within up to 2.5% of it, corners kept only where the path turns back, never with more anchor points), auto?: bool (Auto-Smooth: level 50), ids?: [id…] (default: the selection)} smooth each path under the objects, compound path members included, as one undo step → {ids, before, after} anchor counts, and the level used", + "{level?: 0..100 (50; the Smooth slider: 0 minimum smoothing, the path staying within 0.1% of its longer side, 100 maximum: smoothed along its length by up to 5% of it and refitted with curves within up to 2.5% of it, corners kept only where the path turns back, never with more anchor points), auto?: bool (Auto-Smooth: level 50), ids?: [id…] (default: the selection)} smooth each path under the objects, compound path members included, as one undo step; without ids, a path with anchor points or segments direct-selected smooths only the sections between them, which stay selected → {ids, before, after} anchor counts, and the level used", has_selection, smooth ), @@ -1089,6 +1089,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> { tolerance: tolerance.clamp(1e-4, 1e4), corner_angle_deg: num_param(p, "cornerAngle").unwrap_or(30.0).clamp(0.0, 180.0), straight_lines: bool_or(p, "straightLines", false), + smooth: 0.0, }; let whole = bool_or(p, "wholePaths", false); // A path with segments direct-selected simplifies only their runs, and keeps those runs (and the @@ -1099,13 +1100,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> { return (po::simplify_with(path, &opts), None); }; let part = po::simplify_part(path, &picked, &opts); - let mut kept: BTreeSet<AnchorRef> = anchors.into_iter().flatten().filter_map(|a| part.anchors.get(a).copied()).collect(); - for &(si, i) in &part.segments { - let m = part.path.subpaths.get(si).map_or(1, |sp| sp.anchors.len().max(1)); - kept.extend([(si, i), (si, (i + 1) % m)]); - } - let segs = segments.map(|_| part.segments.clone()); - (part.path, Some((kept, segs))) + refitted_part(part, anchors, segments) })?; let mut out = json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "before": before, "after": after }); if let Some(l) = level { @@ -1114,14 +1109,39 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> { Ok(out) } +/// A path with only the runs of `part` refitted, and what stays direct-selected: the anchors it had +/// selected that are still there, and the refitted runs (their anchors, and their segments when +/// segments were selected). +fn refitted_part( + part: po::SimplifiedPart, + anchors: Option<&BTreeSet<AnchorRef>>, + segments: Option<&BTreeSet<SegmentRef>>, +) -> (PathData, PartSelection) { + let mut kept: BTreeSet<AnchorRef> = anchors.into_iter().flatten().filter_map(|a| part.anchors.get(a).copied()).collect(); + for &(si, i) in &part.segments { + let m = part.path.subpaths.get(si).map_or(1, |sp| sp.anchors.len().max(1)); + kept.extend([(si, i), (si, (i + 1) % m)]); + } + let segs = segments.map(|_| part.segments.clone()); + (part.path, Some((kept, segs))) +} + /// Object › Path › Smooth (`object.path.smooth`): [`po::smooth_level`] on each path under the /// objects given or selected, as one undo step; Auto-Smooth (`auto`) uses [`po::SMOOTH_AUTO_LEVEL`]. +/// A path with anchor points or segments direct-selected (and no `ids` given) smooths only the runs +/// between them, which stay selected, as Simplify does. fn smooth(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "object.path.smooth"; let level = number_or(p, "level", po::SMOOTH_AUTO_LEVEL, C)?.round().clamp(0.0, 100.0); let level = if switch_or(p, "auto", false, C)? { po::SMOOTH_AUTO_LEVEL } else { level }; + let given = p.get("ids").is_some_and(|v| !v.is_null()); let roots = checked_ids_or_selection(s, p, C)?; - let (ids, before, after) = edit_paths(s, &roots, "Smooth", |path, _, _| (po::smooth_level(path, level), None))?; + let (ids, before, after) = edit_paths(s, &roots, "Smooth", |path, anchors, segments| { + let Some(picked) = selected_segments(path, anchors, segments).filter(|_| !given) else { + return (po::smooth_level(path, level), None); + }; + refitted_part(po::simplify_part(path, &picked, &po::smooth_options(path, level)), anchors, segments) + })?; Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "before": before, "after": after, "level": level })) } diff --git a/crates/engine/src/tests/smooth_path.rs b/crates/engine/src/tests/smooth_path.rs index cf946cbe4e..9ce6a21044 100644 --- a/crates/engine/src/tests/smooth_path.rs +++ b/crates/engine/src/tests/smooth_path.rs @@ -161,3 +161,56 @@ fn bad_params_are_refused_and_change_nothing() { // Levels past the ends count as the ends. assert_eq!(s.execute("object.path.smooth", &json!({"level": 250})).unwrap()["level"], json!(100.0)); } + +/// A wave 360 pt long with an anchor every 9 pt pushed up to 6 pt off it, as a shaky hand draws. +fn shaky_wave(s: &mut Session) -> NodeId { + let pts: Vec<(f64, f64)> = + (0..=40u32).map(|i| (20.0 + f64::from(i) * 9.0, 150.0 + 60.0 * (f64::from(i) / 6.0).sin() + f64::from((i * 37) % 13) - 6.0)).collect(); + polyline(s, &pts, false) +} + +/// The largest turn (degrees) at any anchor between two segments of `path`: a kink when large. +fn sharpest_turn(path: &PathData) -> f64 { + path.subpaths + .iter() + .flat_map(|sp| (1..sp.segment_count()).map(move |i| (sp.segment(i - 1), sp.segment(i)))) + .map(|(a, b)| { + let (out, inn) = ((a.p3 - a.p2).normalize(), (b.p1 - b.p0).normalize()); + out.dot(inn).clamp(-1.0, 1.0).acos().to_degrees() + }) + .fold(0.0, f64::max) +} + +/// Auto-Smooth takes a shaky line to one smooth curve: no kinks left at its anchors, far fewer of +/// them, and the wave still where it was. +#[test] +fn auto_smooth_leaves_no_jags_in_a_shaky_line() { + let mut s = session(); + let id = shaky_wave(&mut s); + let before = path_of(&s, id); + s.execute("object.path.smooth", &json!({"auto": true})).unwrap(); + let after = path_of(&s, id); + assert!(sharpest_turn(&after) < 12.0, "a kink of {}°", sharpest_turn(&after)); + assert!(after.anchor_count() <= before.anchor_count() / 3, "{} anchors", after.anchor_count()); + assert!(farthest(&after, &before) < 8.0, "{}", farthest(&after, &before)); +} + +/// With anchor points of a path direct-selected, Smooth changes only the section between them: the +/// anchors outside it stay exactly where they were, and the section is smoothed and stays selected. +#[test] +fn direct_selected_anchors_smooth_only_their_section() { + let mut s = session(); + let id = shaky_wave(&mut s); + let before = path_of(&s, id); + let anchors: Vec<Value> = (10..=30).map(|i| json!([0, i])).collect(); + s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors})).unwrap(); + s.execute("object.path.smooth", &json!({"level": 100})).unwrap(); + let after = path_of(&s, id); + let (a, b) = (&before.subpaths[0].anchors, &after.subpaths[0].anchors); + assert!(b.len() < a.len(), "{} → {}", a.len(), b.len()); + // Anchors 0..=10 and 30..=40 are untouched, the section between them refitted. + assert_eq!(a[..=10].iter().map(|x| x.p).collect::<Vec<_>>(), b[..=10].iter().map(|x| x.p).collect::<Vec<_>>()); + assert_eq!(a[30..].iter().map(|x| x.p).collect::<Vec<_>>(), b[b.len() - 11..].iter().map(|x| x.p).collect::<Vec<_>>()); + let sel = &s.doc().unwrap().selection; + assert!(sel.anchors.get(&id).is_some_and(|set| !set.is_empty()), "the section stays direct-selected"); +} diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index 520ff2bd3b..32b47b7b97 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -16,13 +16,16 @@ pub struct SimplifyOptions { pub tolerance: f64, /// Anchors where the path turns by more than this many degrees stay corners. pub corner_angle_deg: f64, - /// Produce only straight segments (Illustrator's "Convert to Straight Lines"). + /// Produce only straight segments ("Convert to Straight Lines"). pub straight_lines: bool, + /// How far (points, the spread of a Gaussian along the path) the path is smoothed before it is + /// refitted, so that bumps and jags come out as one curve ([`smooth_level`]); 0 for none. + pub smooth: f64, } impl Default for SimplifyOptions { fn default() -> Self { - Self { tolerance: 0.5, corner_angle_deg: 30.0, straight_lines: false } + Self { tolerance: 0.5, corner_angle_deg: 30.0, straight_lines: false, smooth: 0.0 } } } @@ -116,6 +119,9 @@ fn simplify_run(run: &[Seg], opts: &SimplifyOptions) -> Vec<Seg> { let m = ((len / (tol * 0.5)).ceil() as usize).clamp(4, 256); sample(&s.c, m, &mut pts, k == 0); } + if opts.smooth > 0.0 { + pts = smooth_points(&pts, opts.smooth); + } if opts.straight_lines { let keep = rdp(&pts, tol); result.extend(keep.windows(2).map(|p| Seg::line(p[0], p[1]))); @@ -131,6 +137,48 @@ fn simplify_run(run: &[Seg], opts: &SimplifyOptions) -> Vec<Seg> { result } +/// `pts` (a run's samples, in order) smoothed along the path: each point becomes the Gaussian-weighted +/// mean of the points around it, `sigma` points of arc length wide, the window narrowing towards the +/// ends so that the first and last points stay where they are. Most points looked at per point is +/// bounded by the samples within three spreads of it. +fn smooth_points(pts: &[Point], sigma: f64) -> Vec<Point> { + if pts.len() < 3 || !(sigma.is_finite() && sigma > 0.0) { + return pts.to_vec(); + } + let mut s = Vec::with_capacity(pts.len()); + let mut total = 0.0; + for (i, p) in pts.iter().enumerate() { + if let Some(prev) = i.checked_sub(1).and_then(|j| pts.get(j)) { + total += prev.distance(*p); + } + s.push(total); + } + let (mut lo, mut hi) = (0usize, 0usize); + pts.iter() + .zip(&s) + .map(|(&p, &si)| { + let reach = (3.0 * sigma).min(si).min(total - si); + if reach <= 1e-9 { + return p; + } + let spread = reach / 3.0; + while s.get(lo).is_some_and(|&v| v < si - reach) { + lo += 1; + } + while s.get(hi + 1).is_some_and(|&v| v <= si + reach) { + hi += 1; + } + let (mut sum, mut weight) = (Vec2::ZERO, 0.0); + for (q, &sj) in pts.iter().zip(&s).take(hi + 1).skip(lo) { + let w = (-(sj - si) * (sj - si) / (2.0 * spread * spread)).exp(); + sum += q.to_vec2() * w; + weight += w; + } + if weight > 0.0 { (sum / weight).to_point() } else { p } + }) + .collect() +} + /// What [`simplify_part`] made of a path. #[derive(Clone, Debug, PartialEq)] pub struct SimplifiedPart { @@ -320,22 +368,36 @@ pub fn smooth(path: &PathData, amount: f64) -> PathData { /// [`smooth_level`] already scales with each path's size, so one level suits every path. pub const SMOOTH_AUTO_LEVEL: f64 = 50.0; -/// Object › Path › Smooth at slider level `level`, from 0 (minimum smoothing: the path stays within -/// 0.1 % of its longer side of where it was) to 100 (maximum). The help page names only the two -/// ends; the rest is VectorCraft's own rule. Each subpath is refitted with curves as Simplify does, -/// but keeping a corner only where the path turns back on itself (so jags and kinks become curves), -/// within a tolerance from 0.1 % of the path's longer side at level 0 to 2.5 % at level 100. A refit -/// never has more anchor points than the subpath had: a shape whose corners the tolerance can't -/// round, such as a rectangle, stays as it is. Closed subpaths stay closed, with no kink left where -/// they start unless rounding it would pass the tolerance, and open ones keep their end points. A level outside 0..=100 counts as the nearer end, and one that is not a number as -/// [`SMOOTH_AUTO_LEVEL`]. -pub fn smooth_level(path: &PathData, level: f64) -> PathData { +/// The refit Object › Path › Smooth makes of `path` at slider level `level` ([`smooth_level`]): a +/// corner only where the path turns back on itself, the path smoothed along its length by up to 5 % +/// of its longer side (none at level 0) and refitted within 0.1 % (level 0) to 2.5 % (level 100) of +/// it. A level outside 0..=100 counts as the nearer end, and one that is not a number as +/// [`SMOOTH_AUTO_LEVEL`]; a path of no finite size gets no smoothing. +pub fn smooth_options(path: &PathData, level: f64) -> SimplifyOptions { let level = if level.is_finite() { level.clamp(0.0, 100.0) } else { SMOOTH_AUTO_LEVEL }; let size = path.bounds().map_or(0.0, |b| b.width().max(b.height())); - if !size.is_finite() { + let size = if size.is_finite() { size } else { 0.0 }; + SimplifyOptions { + tolerance: size * (0.001 + 0.024 * level / 100.0), + corner_angle_deg: SMOOTH_CORNER_DEG, + straight_lines: false, + smooth: size * 0.05 * level / 100.0, + } +} + +/// Object › Path › Smooth at slider level `level`, from 0 (minimum smoothing: the path stays within +/// 0.1 % of its longer side of where it was) to 100 (maximum). The help page names only the two +/// ends; the rest is VectorCraft's own rule ([`smooth_options`]). Each subpath is smoothed along its +/// length, so that bumps and jags give way to one curve, then refitted with curves as Simplify +/// does, keeping a corner only where the path turns back on itself. A refit never has more anchor +/// points than the subpath had: a shape whose corners it can't round, such as a rectangle, stays as +/// it is. Closed subpaths stay closed, with no kink left where they start unless rounding it would +/// pass the tolerance, and open ones keep their end points. +pub fn smooth_level(path: &PathData, level: f64) -> PathData { + let opts = smooth_options(path, level); + if opts.tolerance <= 0.0 { return path.clone(); } - let opts = SimplifyOptions { tolerance: size * (0.001 + 0.024 * level / 100.0), corner_angle_deg: SMOOTH_CORNER_DEG, straight_lines: false }; let smoothed = |sp: &SubPath| { let Some(mut fit) = simplify_subpath(sp, &opts).filter(|f| f != sp) else { return sp.clone() }; smooth_seam(&mut fit, sp, opts.tolerance); diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index d73d25fd00..980509a871 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -22,7 +22,8 @@ pub use boolean::{ }; pub use edit::{ AverageAxis, SIMPLIFY_LEVEL, SMOOTH_AUTO_LEVEL, SimplifiedPart, SimplifyOptions, add_anchor_points, auto_simplify_level, average, join, - remove_anchor, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, smooth_level, split_into_grid, + remove_anchor, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, smooth_level, smooth_options, + split_into_grid, }; pub use offset::{Cap, Join, offset_path, outline_stroke, stroke_region}; pub use pathfinder::{FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions}; diff --git a/crates/pathops/tests/it/hostile_params.rs b/crates/pathops/tests/it/hostile_params.rs index 108fe2b48b..f0eec5d4a7 100644 --- a/crates/pathops/tests/it/hostile_params.rs +++ b/crates/pathops/tests/it/hostile_params.rs @@ -19,8 +19,8 @@ fn edit_functions_survive_hostile_numbers() { for paths in [square(), zigzag()] { for &v in &HOSTILE { let _ = simplify(&paths, v); - let _ = simplify_with(&paths, &SimplifyOptions { tolerance: v, corner_angle_deg: v, straight_lines: false }); - let _ = simplify_with(&paths, &SimplifyOptions { tolerance: 0.5, corner_angle_deg: v, straight_lines: true }); + let _ = simplify_with(&paths, &SimplifyOptions { tolerance: v, corner_angle_deg: v, straight_lines: false, ..Default::default() }); + let _ = simplify_with(&paths, &SimplifyOptions { tolerance: 0.5, corner_angle_deg: v, straight_lines: true, ..Default::default() }); let _ = smooth(&paths, v); let _ = smooth_level(&paths, v); let _ = remove_redundant_points(&paths, v); diff --git a/docs/mcp.md b/docs/mcp.md index 09d114cf0b..35bf8314b2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2711,9 +2711,10 @@ the dialog on those settings next time. `object.path.smooth` smooths the selected paths (or the objects in `ids`), compound path members included, as one undo step. `level` is the Smooth slider's, a whole number from 0 (minimum smoothing: the path stays within 0.1% of its longer -side) to 100 (maximum smoothing); `auto: true` (Auto-Smooth) uses level 50, the default. Each path is refitted with -curves within 0.1% to 2.5% of its longer side, keeping a corner only where it turns back on itself, so jags and kinks -become curves; a refit never has more anchor points than the path had, so a shape whose corners the tolerance can't +side) to 100 (maximum smoothing); `auto: true` (Auto-Smooth) uses level 50, the default. Each path is smoothed along +its length (by up to 5% of its longer side; none at level 0) and refitted with curves within 0.1% to 2.5% of it, +keeping a corner only where it turns back on itself, so bumps, jags and kinks become one curve; with anchor points or +segments of a path direct-selected (and no `ids`), only the sections between them are smoothed, as Simplify does. A refit never has more anchor points than the path had, so a shape whose corners the tolerance can't round, such as a rectangle, stays as it is. Closed paths stay closed and open paths keep their end points. The reply has the anchor counts `before` and `after` and the `level` used: ```json diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e7e762140a..d852ff5bbb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -19,6 +19,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Object › Path › Smooth smooths a path along its length before refitting it, so Auto-Smooth takes a shaky line to one smooth curve instead of leaving its jags, and with anchor points direct-selected it smooths only that section; scores unchanged. | | 2026-10-31 | minor | New Document: More Settings has the Save Preset button beside the name too, saving its settings (artboard layout included) as a preset (#4893); scores unchanged. | | 2026-10-31 | minor | Object › Rasterize in a CMYK document with its CMYK colour model makes a CMYK image of the art's ink amounts (as CMYK exports draw them), so the Properties panel says CMYK and CMYK exports keep its inks; a transparent background becomes the image's opacity mask (#4882); scores unchanged. | | 2026-10-31 | minor | Export for Screens is laid out as Illustrator's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged. | @@ -831,7 +832,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Simplify dialog also has Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path. The threshold is a slider from 0° to 180° and opens at 150°: an anchor whose corner is sharper than the threshold stays a corner, so moving the slider right keeps more corners, and the dialog sends `cornerAngle` as 180° less the threshold. While Preview is on, Show Original Path draws the paths as they were before the preview in a wide, faint band of their layer's color under the selection's outlines. Object › Path › Simplify opens a slider under the selection ([Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html), [Auto simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/auto-simplify-paths.html)) with Auto-Simplify, a rail from the fewest anchor points to the closest fit, and More Options, which opens the dialog at the slider's tolerance. The rail's levels are VectorCraft's own scale (`object.path.simplify {level}`): level 50 is 1 pt, and every 10 levels halve or double the tolerance, from 32 pt at 0 to 1/32 pt at 100. Auto-Simplify picks the lowest level whose tolerance is at most 1/400 of the selection's longer side, or level 100 when that side is under 12.5 pt; the slider opens at that level, with its result previewed, as the manual-simplify page describes. The dialog's "Open this dialog with these settings next time" makes the menu item open the dialog on the settings of its last OK. With anchors or segments of a path selected with Direct Selection, Simplify acts on just that part of the path, as the [Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html) page puts it: the slider, Auto-Simplify and the dialog refit only each run of selected segments, between its end anchors, which keep their place and their handles on the side away from the run. The anchors and segments outside the runs stay exactly as they were, a closed path's run may cross its start point, separate runs on one path are refitted independently in one undo step, and the runs stay selected. A path with only lone anchors selected is still simplified whole, and `object.path.simplify {wholePaths: true}` simplifies partly selected paths whole. Tests: `crates/engine/src/tests/simplify_part.rs` and `simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path`. - Object › Path › Smooth… (#4115) opens a slider under the selection from Minimum to Maximum smoothing with an Auto-Smooth button, as the [Smooth slider](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-path-segments-with-the-smooth-slider.html) page describes; the canvas previews it and Enter or a click outside keeps it as one undo step (`object.path.smooth {level, auto, ids}`). The page names only the ends, so the rest is VectorCraft's own rule: each selected path, compound path members included, is refitted with curves within 0.1% (level 0) to 2.5% (level 100) of its longer side, corners kept only where it turns back and never with more anchors (a rectangle stays as it is); Auto-Smooth is level 50. Closed paths stay closed and open ones keep their end points. Tests: `crates/engine/src/tests/smooth_path.rs` and `smooth_slider_previews_auto_smooth_and_keeps_the_result`. + Object › Path › Smooth… (#4115) opens a slider under the selection from Minimum to Maximum smoothing with an Auto-Smooth button, as the [Smooth slider](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-path-segments-with-the-smooth-slider.html) page describes; the canvas previews it and Enter or a click outside keeps it as one undo step (`object.path.smooth {level, auto, ids}`). The page names only the ends, so the rest is VectorCraft's own rule: each selected path, compound path members included, is smoothed along its length (by up to 5% of its longer side, so a shaky line comes out as one curve at Auto-Smooth) and refitted with curves within 0.1% (level 0) to 2.5% (level 100) of it, corners kept only where it turns back and never with more anchors (a rectangle stays as it is); Auto-Smooth is level 50. With anchor points of a path direct-selected, only the section between them is smoothed. Closed paths stay closed and open ones keep their end points. Tests: `crates/engine/src/tests/smooth_path.rs` and `smooth_slider_previews_auto_smooth_and_keeps_the_result`. - **Devanagari shaping:** with an OpenType Devanagari font, Ka, virama and Ssa (क्ष) form one conjunct glyph, Ra and virama before a consonant (र्क) become a reph drawn after it, the i matra (कि) is drawn before its consonant, and Ka with a nukta is drawn like the precomposed क़ (U+0958), as [Microsoft's Devanagari shaping specification](https://learn.microsoft.com/en-us/typography/script-development/devanagari) describes. Each syllable is one cluster of its source bytes, and the arrow keys stop at its ends. A click inside a syllable drawn with several glyphs puts the caret at the syllable's nearer end, in point, area and path type. Tests: `crates/text/src/tests/devanagari.rs`; they print SKIPPED when no such font is installed. - **Vertical type spacing shortcuts:** The [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page gives Alt+Down/Up for kerning at a caret or tracking of selected text, Alt+Left/Right for leading, and Alt+Shift+Right/Left for baseline shift. Alt+Shift+Down/Up also steps kerning or tracking. Down increases kerning or tracking, Left increases leading, and Shift+Right increases baseline shift; the opposite arrows decrease them. Cmd/Ctrl makes five steps. Horizontal type keeps its existing mapping; mixed horizontal and vertical text-object selections take the horizontal mapping for both objects in one undo step. Selected vertical point, area and path type use the same directions. Tests: `spacing_arrows_follow_each_text_objects_orientation`, `alt_arrows_rotate_for_selected_vertical_type`, `mixed_type_objects_take_horizontal_spacing_chords_in_both_orders`, and `selected_vertical_area_and_path_type_use_vertical_spacing_chords`. - **Vertical punctuation:** fullwidth `!` (U+FF01) and `?` (U+FF1F) use their nominal glyph upright when no vertical alternate is present, following the Tu fallback in [Unicode UAX #50 §3.1](https://www.unicode.org/reports/tr50/#vo). Code-built test fonts cover point and area type with and without `vert` alternates, retain the rotated fallback for a bracket and long vowel mark, and leave horizontal type unchanged. Tests: `crates/text/src/tests/vertical.rs`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3296cb3a5e..760cf95c24 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -99,7 +99,7 @@ tools, never checked side by side) isn't captured row by row. | Smooth tool smooths only the stretch of path under the drag | done | #1512 | | Drawing modes apply to pastes: Draw Inside takes Paste, Paste in Place and Paste on All Artboards inside the object; Draw Behind puts Paste in Place and Paste on All Artboards behind the selection; Shift+D cycles past Draw Behind with any selection ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) | done | #3705; `pasting_in_draw_inside_puts_the_copies_inside_the_object`, `paste_in_place_in_draw_behind_goes_behind_the_selection`, `shift_d_goes_past_draw_behind_whatever_is_selected` | | Simplify (slider, auto, corner angle threshold), of a whole path or of the part of it selected with Direct Selection ([manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html)) | done | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; the slider under the selection with Auto-Simplify and More Options, opening at the Auto-Simplify level for the selection with that result previewed, and the dialog's option to open it directly with its last settings. With anchors or segments direct-selected, the slider, Auto-Simplify and the dialog refit only each run of selected segments between its end anchors, a closed path's run across its start point included; the rest of the path stays exactly as it was (`tests/simplify_part.rs`, `simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path`) | -| Smooth (Object › Path › Smooth…: slider from minimum to maximum smoothing, Auto-Smooth) ([smooth slider](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-path-segments-with-the-smooth-slider.html)) | done | #4115: the slider under the selection previews `object.path.smooth {level}`, Auto-Smooth picks level 50, Enter or a click outside keeps one undo step and Escape restores; the smoothing rule beyond the two ends is VectorCraft's own (`tests/smooth_path.rs`, `smooth_slider_previews_auto_smooth_and_keeps_the_result`) | +| Smooth (Object › Path › Smooth…: slider from minimum to maximum smoothing, Auto-Smooth) ([smooth slider](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-path-segments-with-the-smooth-slider.html)) | done | #4115: the slider under the selection previews `object.path.smooth {level}`, Auto-Smooth picks level 50 and takes a shaky line to one smooth curve, direct-selected anchors smooth only their section, Enter or a click outside keeps one undo step and Escape restores; the smoothing rule beyond the two ends is VectorCraft's own (`tests/smooth_path.rs`, `smooth_slider_previews_auto_smooth_and_keeps_the_result`) | | Draw Inside in isolation mode: art drawn or pasted inside the isolated object takes isolation mode into its clip group, clickable and undimmed ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html), [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) | done | #3705; `drawing_inside_an_isolated_object_keeps_the_new_art_in_isolation_mode` | | Draw Inside marks the object it draws into: a dotted open rectangle round its corners, in its layer's colour, while the mode lasts, selected or not | done | #4319, `canvas::tests::draw_inside_marks_the_corners_of_its_object` ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) | | Simplify (slider, auto, corner angle threshold) | partial | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; the slider under the selection with Auto-Simplify and More Options, and the dialog's option to open it directly with its last settings; the slider opens at 1 pt rather than at the Auto-Simplify level, and simplifying only a Direct Selection part of a path remains missing | @@ -379,6 +379,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Object › Path › Smooth: Auto-Smooth takes a shaky line to one smooth curve, and direct-selected anchors smooth only their section; scores unchanged | | 2026-10-31 | minor | New Document: More Settings has Save Preset beside the name, as Preset Details does, and saves its settings (#4893); scores and estimates unchanged | | 2026-10-31 | minor | Export for Screens is laid out as the reference app's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged | | 2026-10-31 | minor | Direct Selection: with Alt held at the press, a marquee selects every path it touches whole and keeps the Group Selection pointer while dragging (#4890); a click on a selected object's centre point (Show Center) selects the object whole, and a drag from it moves the object (#4891); scores unchanged | From 9b17e38a5c7f34afc73304142a37f1be6f65ca92 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sat, 31 Oct 2026 22:30:40 +0700 Subject: [PATCH 095/260] Fix #4892: a file opened while VectorCraft runs opens in that window --- apps/vectorcraft/src/app.rs | 18 +- apps/vectorcraft/src/main.rs | 31 +- apps/vectorcraft/src/single_instance.rs | 386 ++++++++++++++++++++++++ docs/development.md | 6 + docs/ui-parity.md | 5 +- 5 files changed, 435 insertions(+), 11 deletions(-) create mode 100644 apps/vectorcraft/src/single_instance.rs diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index 05c756a0c0..affb234660 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -1,6 +1,8 @@ #[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))] use super::gpu; use super::prefs::{save_prefs, save_prefs_soon}; +#[cfg(not(target_os = "macos"))] +use super::single_instance; #[cfg(all(windows, not(target_vendor = "win7")))] use super::windows_stylus; use super::{App, VectorcraftApp, file_access, window}; @@ -105,11 +107,13 @@ impl App { vectorcraft_ui_egui::background::wait_all(&mut self.app); return; } - // Files from the Finder and the Dock wait while a file dialog is open: what asked for it runs - // again on its document when it answers. - #[cfg(target_os = "macos")] + // Files from the Finder and the Dock (macOS) or from later launches (#4892) wait while a file + // dialog is open: what asked for it runs again on its document when it answers. if !self.app.file_dialog_open() { + #[cfg(target_os = "macos")] let files = open_documents::take(); + #[cfg(not(target_os = "macos"))] + let files = single_instance::take(); if !files.is_empty() { bring_window_forward(ctx); } @@ -147,15 +151,15 @@ fn end_before_teardown(frames: u64) { } } -/// Show the window when files are opened from the Finder or the Dock: a minimized window comes back -/// out of the Dock and the app takes focus, as a document-based Mac app does (#3769). -#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +/// Show the window when files are opened from the Finder or the Dock, or handed over by a later +/// launch (#4892): a minimized window comes back and the app takes focus, as a document-based app +/// does (#3769). pub(crate) fn bring_window_forward(ctx: &egui::Context) { ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); ctx.send_viewport_cmd(egui::ViewportCommand::Focus); } -/// Open files handed to the app (command line, macOS Finder and Dock) as documents. A file that +/// Open files handed to the app (command line, macOS Finder and Dock, later launches) as documents. A file that /// can't be opened is reported to the user and on stderr; the others still open. pub(crate) fn open_files(app: &mut VectorcraftApp, files: Vec<String>) { for f in files { diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 1e2ab4fae6..33d27ab352 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -1,7 +1,10 @@ //! VectorCraft desktop app. //! //! Usage: `vectorcraft [--control <port> [--automation-read-root <dir>]... [--automation-write-root <dir>]...] -//! [--in-window-menus] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`) +//! [--in-window-menus] [--new-instance] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`) +//! +//! Files given while VectorCraft already runs open in that window, unless `--new-instance` is given +//! (Windows and Linux; `single_instance`). //! //! `--in-window-menus` (or `VECTORCRAFT_IN_WINDOW_MENUS=1`) keeps the menus inside the window on //! macOS instead of the macOS menu bar (`mac_menu`). @@ -45,6 +48,8 @@ mod open_documents; mod portal_save; mod prefs_dir; mod printing; +#[cfg(not(target_os = "macos"))] +mod single_instance; #[cfg(windows)] mod system_fonts; mod tablet; @@ -120,7 +125,9 @@ Options: (may be given more than once) --in-window-menus Keep the menus inside the window on macOS (or VECTORCRAFT_IN_WINDOW_MENUS=1) - --version Print the version and exit + --new-instance Open the files in a new window even when VectorCraft + already runs (Windows and Linux) + --version Print the version and exit -h, --help Print this help and exit Without a window (converting, scripting, the MCP server), use vectorcraft-cli: @@ -144,6 +151,7 @@ fn main() -> std::process::ExitCode { automation_args::AutomationArgs::new(root_env("VECTORCRAFT_AUTOMATION_READ_ROOT"), root_env("VECTORCRAFT_AUTOMATION_WRITE_ROOT")); let mut files = Vec::new(); let mut in_window_menus = std::env::var_os("VECTORCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0"); + let mut new_instance = false; let mut args = std::env::args().skip(1); while let Some(a) = args.next() { match roots_args.consume(&a, &mut args).and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) }) { @@ -156,6 +164,7 @@ fn main() -> std::process::ExitCode { } match a.as_str() { "--in-window-menus" => in_window_menus = true, + "--new-instance" => new_instance = true, "--version" => { println!("vectorcraft {}", env!("CARGO_PKG_VERSION")); return std::process::ExitCode::SUCCESS; @@ -185,6 +194,15 @@ fn main() -> std::process::ExitCode { }; // Before desktop services, so every start-up warning is recorded (`logging`). let logger = logging::install(); + // Files opened from the file manager while VectorCraft runs open in its window (#4892). Before + // the log file is attached: a launch that hands its files over leaves the running app's log be. + #[cfg(not(target_os = "macos"))] + let instance = match single_instance::start(control_port.is_some(), new_instance, &files) { + single_instance::Start::Forwarded => return std::process::ExitCode::SUCCESS, + single_instance::Start::Running(primary) => primary, + }; + #[cfg(target_os = "macos")] + let _ = new_instance; vectorcraft_ui_egui::i18n::detect_system_lang_in_background(); // Before the first render: the cores the process may run on. #[cfg(windows)] @@ -457,7 +475,10 @@ fn main() -> std::process::ExitCode { } } #[cfg(not(target_os = "macos"))] - let _ = in_window_menus; + { + let _ = in_window_menus; + single_instance::set_ui(&cc.egui_ctx); + } app.services.native_input_hook = native_input_hook(&app); file_access::unconfined(|| open_files(&mut app, files)); // The first frame is due from now (`gpu::watch_first_frame`). @@ -478,6 +499,10 @@ fn main() -> std::process::ExitCode { }), ) }); + // The window is gone: later launches start their own app, including the one a graphics + // failure starts again below. + #[cfg(not(target_os = "macos"))] + drop(instance); #[cfg(feature = "wgpu")] let outcome = gpu::finish(outcome, &startup); #[cfg(not(feature = "wgpu"))] diff --git a/apps/vectorcraft/src/single_instance.rs b/apps/vectorcraft/src/single_instance.rs new file mode 100644 index 0000000000..b8df2bb5a1 --- /dev/null +++ b/apps/vectorcraft/src/single_instance.rs @@ -0,0 +1,386 @@ +//! One app per user (#4892): a file opened from the file manager (double-click, Open With, a drop +//! on the executable) while VectorCraft runs opens as a new document tab in the running app, which +//! comes to the front, instead of in a second app. +//! +//! The running app (the primary) listens on a loopback port and records the port and two random +//! tokens in `instance.json` next to the preferences (owner-only on Unix; on Windows the settings +//! folder is the user's own). A later launch with files connects; the primary greets it with +//! `hello`, which only a process that could read the file (or talk to the primary) knows; only then +//! does the launch send `token` and the absolute paths of its files, one JSON line. The primary +//! checks the token, keeps the paths that are existing files, acknowledges and opens them; the +//! launch exits. Anything else (no file, no listener, a wrong greeting, no answer) starts the launch +//! as its own app, which replaces a stale file. Nothing received is ever run. +//! +//! Runs that start many apps side by side (`--control`, `VECTORCRAFT_NO_PREFS`) neither forward +//! nor listen, and `--new-instance` opens a launch's files in an app of its own. macOS hands files +//! opened from Finder to the running app itself (`open_documents`), so this is off there. + +use std::fs::{self, OpenOptions}; +use std::hash::{BuildHasher as _, RandomState}; +use std::io::{self, BufRead as _, BufReader, Read as _, Write as _}; +use std::net::{Ipv4Addr, TcpListener, TcpStream}; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock, PoisonError}; +use std::time::Duration; + +use serde_json::{Value, json}; + +use super::prefs::{prefs_enabled, prefs_path}; + +/// The endpoint file, next to the preferences. +const FILE_NAME: &str = "instance.json"; +/// The longest message either side reads, and the longest endpoint file. +const MAX_MESSAGE: u64 = 64 * 1024; +/// The most files one launch hands over. +const MAX_FILES: usize = 256; +/// A live primary's kernel accepts at once, even while its window is busy; a stale port on Windows +/// would otherwise retry for about two seconds. +const CONNECT_TIMEOUT: Duration = Duration::from_millis(500); +/// How long the primary waits on one launch; it serves launches one at a time. +const SERVER_TIMEOUT: Duration = Duration::from_secs(2); +/// How long a launch waits on the primary: longer than a launch served before it can take. +const CLIENT_TIMEOUT: Duration = Duration::from_secs(5); + +/// Paths handed over by later launches that the UI hasn't opened yet. +static PENDING: Mutex<Vec<String>> = Mutex::new(Vec::new()); +/// The UI to wake when files arrive (unset until the window exists; the first frame opens them). +static UI: OnceLock<egui::Context> = OnceLock::new(); + +/// What this launch does about an app already running. +pub enum Start { + /// The running app took the files: this launch exits. + Forwarded, + /// This launch runs; `Some` while it is the app later launches hand their files to. + Running(Option<Primary>), +} + +/// Hand `files` to the app already running, or become the app later launches hand theirs to. +/// `automation`: started with `--control`. +pub fn start(automation: bool, new_instance: bool, files: &[String]) -> Start { + if automation || !prefs_enabled() { + return Start::Running(None); + } + let Some(path) = prefs_path().and_then(|p| Some(p.parent()?.join(FILE_NAME))) else { return Start::Running(None) }; + // With nothing to hand over, the same exchange only asks whether an app is running. + let send: &[String] = if new_instance { &[] } else { files }; + match forward(&path, send) { + Ok(()) if send.is_empty() => Start::Running(None), + Ok(()) => Start::Forwarded, + Err(e) => { + log::debug!("no running VectorCraft to hand files to ({e})"); + Start::Running(listen(&path, queue)) + } + } +} + +/// Wake `ctx` when files arrive from later launches. +pub fn set_ui(ctx: &egui::Context) { + // Set once; a second call would hand over the same context. + let _ = UI.set(ctx.clone()); +} + +/// The paths later launches handed over since the last call. +pub fn take() -> Vec<String> { + std::mem::take(&mut *PENDING.lock().unwrap_or_else(PoisonError::into_inner)) +} + +fn queue(files: Vec<String>) { + PENDING.lock().unwrap_or_else(PoisonError::into_inner).extend(files); + if let Some(ctx) = UI.get() { + ctx.request_repaint(); + } +} + +/// This app is the one recorded in the endpoint file; dropping it removes the file, unless a later +/// app has replaced it since. +pub struct Primary { + path: PathBuf, + token: String, +} + +impl Drop for Primary { + fn drop(&mut self) { + if read_endpoint(&self.path).is_some_and(|e| e.token == self.token) { + // Best effort: a file left behind is stale, and the next launch replaces it. + let _ = fs::remove_file(&self.path); + } + } +} + +struct Endpoint { + port: u16, + token: String, + hello: String, +} + +fn invalid(why: &str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, why) +} + +fn read_endpoint(path: &Path) -> Option<Endpoint> { + let mut text = String::new(); + fs::File::open(path).ok()?.take(MAX_MESSAGE).read_to_string(&mut text).ok()?; + let v: Value = serde_json::from_str(&text).ok()?; + let port = u16::try_from(v.get("port")?.as_u64()?).ok().filter(|p| *p != 0)?; + Some(Endpoint { port, token: v.get("token")?.as_str()?.to_owned(), hello: v.get("hello")?.as_str()?.to_owned() }) +} + +/// Hand `files` (made absolute against this launch's folder) to the app recorded at `path`; `Ok` +/// once it acknowledged them. +fn forward(path: &Path, files: &[String]) -> io::Result<()> { + let endpoint = read_endpoint(path).ok_or_else(|| invalid("no endpoint file"))?; + let files = files.iter().map(|f| std::path::absolute(f).map(|p| p.to_string_lossy().into_owned())).collect::<io::Result<Vec<_>>>()?; + let stream = TcpStream::connect_timeout(&(Ipv4Addr::LOCALHOST, endpoint.port).into(), CONNECT_TIMEOUT)?; + stream.set_read_timeout(Some(CLIENT_TIMEOUT))?; + stream.set_write_timeout(Some(CLIENT_TIMEOUT))?; + // The token and the paths go only to a listener that knows the greeting. + if !same(read_message(&stream)?.get("hello"), &endpoint.hello) { + return Err(invalid("the listener isn't VectorCraft")); + } + write_message(&stream, &json!({ "token": endpoint.token, "files": files }))?; + match read_message(&stream)?.get("ok") { + Some(Value::Bool(true)) => Ok(()), + _ => Err(invalid("refused")), + } +} + +/// Listen for later launches and record this app at `path`; each launch's files go to `deliver`. +/// `None` when that fails (logged): the app then runs on its own, as before. +fn listen(path: &Path, deliver: impl Fn(Vec<String>) + Send + 'static) -> Option<Primary> { + try_listen(path, deliver).inspect_err(|e| log::warn!("files opened while VectorCraft runs will open in another window: {e}")).ok() +} + +fn try_listen(path: &Path, deliver: impl Fn(Vec<String>) + Send + 'static) -> io::Result<Primary> { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?; + let port = listener.local_addr()?.port(); + let (token, hello) = random_tokens(); + write_endpoint(path, &json!({ "port": port, "token": token, "hello": hello }))?; + // From here on a failure removes the file again. + let primary = Primary { path: path.to_path_buf(), token: token.clone() }; + std::thread::Builder::new().name("open-files-listener".into()).spawn(move || { + for stream in listener.incoming() { + match stream.and_then(|s| receive(&s, &hello, &token)) { + Ok(files) if files.is_empty() => {} + Ok(files) => deliver(files), + Err(e) => { + log::warn!("refused files from another launch: {e}"); + // An accept that keeps failing (out of handles) doesn't spin. + std::thread::sleep(Duration::from_millis(50)); + } + } + } + })?; + Ok(primary) +} + +/// Serve one launch: greet it, check its token, keep the paths that are existing files. +fn receive(stream: &TcpStream, hello: &str, token: &str) -> io::Result<Vec<String>> { + stream.set_read_timeout(Some(SERVER_TIMEOUT))?; + stream.set_write_timeout(Some(SERVER_TIMEOUT))?; + write_message(stream, &json!({ "hello": hello }))?; + let message = read_message(stream)?; + if !same(message.get("token"), token) { + return Err(invalid("wrong token")); + } + let files = message.get("files").and_then(Value::as_array).ok_or_else(|| invalid("no file list"))?; + if files.len() > MAX_FILES { + return Err(invalid("too many files")); + } + let files = files + .iter() + .filter_map(Value::as_str) + .filter(|f| { + let p = Path::new(f); + let ok = p.is_absolute() && p.is_file(); + if !ok { + log::warn!("another launch named {f}, which isn't a file"); + } + ok + }) + .map(str::to_owned) + .collect(); + write_message(stream, &json!({ "ok": true }))?; + Ok(files) +} + +/// One JSON line of at most [`MAX_MESSAGE`] bytes. Each side sends one line and waits for the +/// other's, so nothing read past it is lost. +fn read_message(stream: &TcpStream) -> io::Result<Value> { + let mut line = Vec::new(); + BufReader::new(stream.take(MAX_MESSAGE)).read_until(b'\n', &mut line)?; + if line.last() != Some(&b'\n') { + return Err(invalid("message too long or cut short")); + } + serde_json::from_slice(&line).map_err(|e| invalid(&e.to_string())) +} + +fn write_message(mut stream: &TcpStream, message: &Value) -> io::Result<()> { + let mut line = serde_json::to_vec(message).map_err(io::Error::other)?; + line.push(b'\n'); + stream.write_all(&line) +} + +/// `given` is the string `expected`, compared in constant time. +fn same(given: Option<&Value>, expected: &str) -> bool { + given + .and_then(Value::as_str) + .is_some_and(|g| g.len() == expected.len() && g.bytes().zip(expected.bytes()).fold(0, |acc, (a, b)| acc | (a ^ b)) == 0) +} + +/// Two unrelated 128-bit hex tokens. `RandomState` is keyed from the system's random numbers, and +/// its keyed hash of distinct values gives unpredictable, independent output (no crate needed). +fn random_tokens() -> (String, String) { + let keyed = RandomState::new(); + let token = |a: u8, b: u8| format!("{:016x}{:016x}", keyed.hash_one(a), keyed.hash_one(b)); + (token(1, 2), token(3, 4)) +} + +/// Replace `path` with `endpoint` at once (a temporary file renamed over it), readable only by the +/// user on Unix. +fn write_endpoint(path: &Path, endpoint: &Value) -> io::Result<()> { + if let Some(dir) = path.parent() { + fs::create_dir_all(dir)?; + } + let tmp = path.with_extension(format!("{}.tmp", std::process::id())); + // A leftover of an earlier app with the same process id; `create_new` sets the mode below. + let _ = fs::remove_file(&tmp); + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + let bytes = serde_json::to_vec(endpoint).map_err(io::Error::other)?; + let written = options.open(&tmp).and_then(|mut f| f.write_all(&bytes)).and_then(|()| fs::rename(&tmp, path)); + if written.is_err() { + // Best effort: the temporary file is all there is to clean up. + let _ = fs::remove_file(&tmp); + } + written +} + +#[cfg(test)] +mod tests { + use std::sync::mpsc; + + use super::*; + + /// A fresh folder for one test, with an existing file in it. + fn folder(name: &str) -> (PathBuf, PathBuf, String) { + let dir = std::env::temp_dir().join(format!("vc-single-instance-{}-{name}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + let file = dir.join("a b.svg"); + fs::write(&file, "<svg/>").unwrap(); + let file = file.to_string_lossy().into_owned(); + (dir.join(FILE_NAME), dir, file) + } + + fn primary(path: &Path) -> (Primary, mpsc::Receiver<Vec<String>>) { + let (tx, rx) = mpsc::channel(); + let primary = listen(path, move |files| tx.send(files).unwrap()).unwrap(); + (primary, rx) + } + + /// Connects as a launch would and sends `message` after the greeting; what came back. + fn send_raw(path: &Path, message: &[u8]) -> io::Result<Value> { + let endpoint = read_endpoint(path).unwrap(); + let stream = TcpStream::connect((Ipv4Addr::LOCALHOST, endpoint.port)).unwrap(); + stream.set_read_timeout(Some(CLIENT_TIMEOUT)).unwrap(); + assert!(same(read_message(&stream).unwrap().get("hello"), &endpoint.hello)); + (&stream).write_all(message)?; + read_message(&stream) + } + + #[test] + fn a_launch_hands_its_files_to_the_running_app() { + let (path, dir, file) = folder("forward"); + let (primary, rx) = primary(&path); + let missing = dir.join("missing.svg").to_string_lossy().into_owned(); + forward(&path, &[file.clone(), missing]).unwrap(); + assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file), "the missing file is left out"); + // An empty list only asks whether the app runs: nothing is delivered. + forward(&path, &[]).unwrap(); + forward(&path, std::slice::from_ref(&file)).unwrap(); + assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); + drop(primary); + assert!(!path.exists(), "the endpoint file goes with the app"); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn a_wrong_token_garbage_and_oversized_messages_are_refused() { + let (path, dir, file) = folder("refused"); + let (_primary, rx) = primary(&path); + let token = read_endpoint(&path).unwrap().token; + let wrong = format!("{}\n", json!({ "token": "0".repeat(token.len()), "files": [file] })); + assert!(send_raw(&path, wrong.as_bytes()).is_err()); + assert!(send_raw(&path, b"not json\n").is_err()); + assert!(send_raw(&path, &vec![b'a'; MAX_MESSAGE as usize + 10]).is_err()); + let many = format!("{}\n", json!({ "token": token, "files": vec![file.clone(); MAX_FILES + 1] })); + assert!(send_raw(&path, many.as_bytes()).is_err()); + let relative = format!("{}\n", json!({ "token": token, "files": ["a b.svg", 7] })); + assert_eq!(send_raw(&path, relative.as_bytes()).unwrap(), json!({ "ok": true })); + assert!(rx.try_recv().is_err(), "nothing was delivered"); + // The listener still serves a launch with the right token. + forward(&path, std::slice::from_ref(&file)).unwrap(); + assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn a_stale_endpoint_file_is_ignored_and_replaced() { + let (path, dir, file) = folder("stale"); + // No listener on the recorded port any more. + let port = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap().local_addr().unwrap().port(); + write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap(); + assert!(forward(&path, std::slice::from_ref(&file)).is_err()); + // A listener that doesn't know the greeting gets neither the token nor the paths. + let impostor = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); + let port = impostor.local_addr().unwrap().port(); + write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap(); + let heard = std::thread::spawn(move || { + let (stream, _) = impostor.accept().unwrap(); + write_message(&stream, &json!({ "hello": "x" })).unwrap(); + stream.set_read_timeout(Some(CLIENT_TIMEOUT)).unwrap(); + read_message(&stream).ok() + }); + assert!(forward(&path, std::slice::from_ref(&file)).is_err()); + assert!(heard.join().unwrap().is_none()); + // Garbage in the file is no endpoint either. + fs::write(&path, b"\xff not json").unwrap(); + assert!(forward(&path, std::slice::from_ref(&file)).is_err()); + // A new primary replaces the stale file. + let (_primary, rx) = primary(&path); + forward(&path, std::slice::from_ref(&file)).unwrap(); + assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn a_replaced_endpoint_file_stays_when_the_earlier_app_ends() { + let (path, dir, _) = folder("replaced"); + let (first, _rx1) = primary(&path); + let (_second, _rx2) = primary(&path); + let second_token = read_endpoint(&path).unwrap().token; + drop(first); + assert_eq!(read_endpoint(&path).map(|e| e.token), Some(second_token)); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn tokens_are_random_and_distinct() { + let (a, b) = random_tokens(); + let (c, _) = random_tokens(); + assert_eq!(a.len(), 32); + assert!(a != b && a != c); + } + + #[cfg(unix)] + #[test] + fn the_endpoint_file_is_the_users_alone() { + use std::os::unix::fs::PermissionsExt as _; + let (path, dir, _) = folder("mode"); + let _primary = primary(&path); + assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + let _ = fs::remove_dir_all(dir); + } +} diff --git a/docs/development.md b/docs/development.md index 6f4859d68d..2dfa4fea63 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,5 +1,6 @@ # Development +> **Last updated:** 2026-10-31 · **Change:** files opened while the app runs open in its window on Windows and Linux (#4892); `--new-instance`. > **Last updated:** 2026-10-29 · **Change:** Linux clipboard: the Flatpak on GNOME copies and pastes text through the core Wayland protocol. > **Last updated:** 2026-10-29 · **Change:** Linux clipboard: a clipboard that can't be opened is retried with a growing wait and logged once. > **Last updated:** 2026-10-25 · **Change:** Linux Wayland drag-and-drop note names eframe 0.37 (still on winit 0.30). @@ -109,6 +110,10 @@ On macOS the menus live in the system menu bar, not in the window's app bar (whi - **Keys stay with egui.** AppKit runs a menu's key equivalents before the window sees the key, so the item's key goes back to egui as the key press it was (⌘X/⌘C/⌘V as egui's Cut/Copy/Paste events), through `raw_input_hook`: `shortcuts::handle` runs it once, user shortcuts apply, and a focused text field keeps ⌘A, ⌘C, ⌘V and ⌘Z. A click runs the item like an in-window click. Bare keys and ⌥/⇧ chords are never key equivalents (they type). - Built and clippy-checked for `aarch64-apple-darwin` and `x86_64-apple-darwin` from any host: `cargo clippy -p vectorcraft --target aarch64-apple-darwin --all-targets -- -D warnings`. +## Files opened while the app runs (Windows and Linux) + +A file opened from the file manager (double-click, Open With, a drop on the executable) or given on the command line while VectorCraft already runs opens as a new document tab in that window, which comes to the front; the second launch exits (#4892). `apps/vectorcraft/src/single_instance.rs`: the running app listens on a loopback port and records the port and two random tokens in `instance.json` next to the preferences (owner-only on Unix). A launch with files reads it, connects, checks the app's greeting, sends the token and the absolute paths as one JSON line and waits for the acknowledgement; the app keeps only existing files (at most 256, 64 KiB per message). A stale file (no listener, a wrong greeting) is ignored and replaced; the app removes its file when its window closes. Launches with `--control` or `VECTORCRAFT_NO_PREFS` neither hand files over nor listen, so tests and agents start as many apps as before; `--new-instance` opens a launch's files in a window of its own. macOS hands Finder's files to the running app as open-document events (`open_documents.rs`). + ## Linux: Wayland and X11 On GNOME/Wayland, enable **Preferences › User Interface › System Title Bar** and restart to use winit's font-free Adwaita window controls (`wayland-csd-adwaita-notitle`); the existing custom title bar remains the Linux default. @@ -493,6 +498,7 @@ Scores and hour estimates are unchanged. | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Files opened while the app runs open in its window on Windows and Linux (#4892); `--new-instance` opts out. | | 2026-10-29 | minor | Linux clipboard: core Wayland protocol text fallback where arboard has neither data-control nor X11 (the Flatpak on GNOME).; its reads wait 2 s at most. | | 2026-10-29 | minor | Linux clipboard: a clipboard arboard can't open is retried after 1 s doubling to 60 s and logged once, instead of every 250 ms. | | 2026-10-28 | minor | Localisation: Catalan (`ca`) catalog and registry entry (every `ca-*` locale); complete under the catalog tests. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 760cf95c24..ecda87aae2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (New Document: Save Preset in More Settings, #4893; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (files opened from the file manager while VectorCraft runs open in its window on Windows and Linux, #4892) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -359,6 +359,8 @@ re-measure of the panels added since. Slider rails show on Medium Dark (#1808, # - [x] Compact Color Picker with a distinct header, stacked actions and aligned input groups. #2008; translated action widths, visible warnings, stable mode switching and vertical scrolling in narrow windows; real egui events and two UI scales covered; German and enlarged English renders reviewed locally. Scores unchanged +- [x] A file opened from the file manager (double-click, Open With, a drop on the executable) while VectorCraft runs opens as a new document tab in that window, which comes to the front, on Windows and Linux as on macOS; the second launch exits (#4892). `--new-instance` opts out; runs with `--control` or `VECTORCRAFT_NO_PREFS` start apps of their own as before. Protocol, token, stale-file and hand-over tests in `apps/vectorcraft/src/single_instance.rs`. + ## Highlighted-text Eyedropper (2026-10-21) Type/Eyedropper switches preserve highlighted characters; sampling changes only their enabled @@ -379,6 +381,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | A file opened from the file manager while VectorCraft runs opens as a new tab in that window, which comes to the front, on Windows and Linux (#4892); `--new-instance` opts out; scores unchanged | | 2026-10-31 | minor | Object › Path › Smooth: Auto-Smooth takes a shaky line to one smooth curve, and direct-selected anchors smooth only their section; scores unchanged | | 2026-10-31 | minor | New Document: More Settings has Save Preset beside the name, as Preset Details does, and saves its settings (#4893); scores and estimates unchanged | | 2026-10-31 | minor | Export for Screens is laid out as the reference app's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged | From 4c32032d345ba4d8254444425877a193f49dfd85 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 08:48:58 -0700 Subject: [PATCH 096/260] Part of #3602: a node thumbnail reports the size it is drawn at render_node_thumbnail_with draws into a context of size.clamp(1, MAX_CONTEXT_SIDE) pixels but reported width and height as the requested size, so a size of 0 gave a 0x0 image holding 4 bytes. The view was also built from the requested size, and the fit scale (size - 2) / extent was 0 or negative at sizes 1 and 2, so the art drew nothing or mirrored. The thumbnail now reports the side it draws, builds the view from it, and drops the 1-pixel margin when the side is too small to keep one. Test: node_thumbnail_reports_the_size_it_draws. --- crates/render/src/renderer.rs | 7 ++++--- crates/render/src/tests.rs | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 3593bf0413..218ef06205 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -347,9 +347,10 @@ impl Renderer { self.check_plugins(); self.check_symbols(doc); let b = brush_fx::cull_bounds(&doc.symbol_boxes(), n)?; - let s = (size as f64 - 2.0) / b.width().max(b.height()).max(1e-6); - let view = Affine::translate((size as f64 / 2.0, size as f64 / 2.0)) * Affine::scale(s) * Affine::translate(-b.center().to_vec2()); let w = size.clamp(1, MAX_CONTEXT_SIDE) as u16; + // A 1-pixel margin on each side, unless the thumbnail is too small to keep one. + let s = (w as f64 - 2.0).max(1.0) / b.width().max(b.height()).max(1e-6); + let view = Affine::translate((w as f64 / 2.0, w as f64 / 2.0)) * Affine::scale(s) * Affine::translate(-b.center().to_vec2()); let mut ctx = single_threaded_context(w, w); if let Some(bg) = background { ctx.set_paint(peniko::Color::from_rgba8(bg[0], bg[1], bg[2], bg[3])); @@ -364,6 +365,6 @@ impl Renderer { self.draw_forced_arc(&mut ctx, &frame, &Arc::new(n.clone())); let pm = self.finish(&mut ctx, vello_cpu::RasterizerSettings::default()); self.end_frame(); - Some(Rendered { width: size, height: size, pixels: pm.data_as_u8_slice().to_vec() }) + Some(Rendered { width: w as u32, height: w as u32, pixels: pm.data_as_u8_slice().to_vec() }) } } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 643701fc72..e7782b8132 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -869,6 +869,22 @@ fn node_thumbnail_applies_the_root_mask() { assert_eq!(img.pixel(75, 50), [255, 255, 255, 255]); } +/// #3602: a thumbnail reports the size it was drawn at, and one too small for its 1-pixel margin +/// still draws the art. +#[test] +fn node_thumbnail_reports_the_size_it_draws() { + let mut d = Document::new(100.0, 100.0); + let node = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let mut r = Renderer::new(); + for size in 0..4 { + let img = r.render_node_thumbnail(&d, &node, size, None).unwrap(); + assert_eq!(img.pixels.len(), img.width as usize * img.height as usize * 4, "size {size}"); + assert_eq!(img.width, size.max(1), "size {size}"); + assert_eq!(img.height, size.max(1), "size {size}"); + assert!(img.pixels.chunks(4).any(|p| p[3] > 0), "size {size}: the art is drawn"); + } +} + #[test] fn opacity_mask_with_undecodable_image_leaves_out_object() { use vectorcraft_doc::{Effect, ImageBlob, ImageObject, NodeKind, OpacityMask}; From a32d6364ec28a4728209ac5112c609803fa81f94 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 07:44:54 -0700 Subject: [PATCH 097/260] Appearance: paint, stroke and effect edits change the active row of the first selected object The Appearance panel's active row is a row of the first selected object's stack, but fill, stroke, gradient and effect edits matched it against the object that paints first. When the selection was made top object first and the objects' stacks differ, an edit changed another row: with the red fill of [red, white, Stroke] active above a [white, Stroke] object, Fill set the white row instead. These edits now match the active row against the first selected object (or the compound path holding it), as Add New Fill and Reduce to Basic Appearance already do. Gradient edits also read whether the active row is a fill or a stroke from that object. --- crates/engine/src/cmd/appearance.rs | 37 +++++++++++++++++++------ crates/engine/src/cmd/effectcmd.rs | 2 +- crates/engine/src/tests/appearance.rs | 40 +++++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 3da1cb56c1..66d6ab232a 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -27,7 +27,7 @@ use vectorcraft_doc::appearance::SharedStack; use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, FillLayer, Node, NodeKind, ParaStyle, StrokeLayer}; use vectorcraft_geom::Rect; -use super::edit::{outermost, selected_roots}; +use super::edit::{outermost, roots_of, selected_roots}; use super::opacitymask::percent; use super::paint::paint_from; use super::{AppearanceAttrs, EyedropperAttrs, FillAttrs, StrokeAttrs}; @@ -255,17 +255,36 @@ impl ItemTarget { if fits == Some(true) { self } else { ItemTarget::Top } } - /// This target for each of `ids` in `d` (in their order): an aligned item (a row of the first - /// target's stack) is, in each other target, the item equal to it there (see + /// This target for each of `ids` (in their order): an aligned item (a row of the first + /// target's stack, or for the active item of the first selected object's, see + /// [`ItemTarget::anchor`]) is, in each other target, the item equal to it there (see /// [`SharedStack`]); `None` for a target that has none, which the edit leaves alone. A row the /// targets don't share, and any other target, stands for itself in every target. - pub(crate) fn per_target(self, d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<Option<ItemTarget>> { + pub(crate) fn per_target(self, s: &Session, ids: &[NodeId]) -> Vec<Option<ItemTarget>> { let ItemTarget::Item { index, explicit, aligned: true } = self else { return vec![Some(self); ids.len()] }; - let Some(shared) = shared_stack(d, ids) else { return vec![Some(self); ids.len()] }; + let Some(st) = s.active() else { return vec![Some(self); ids.len()] }; + let k = self.anchor(s, ids); + let mut order = ids.to_vec(); + order.swap(0, k); + let Some(shared) = shared_stack(&st.doc, &order) else { return vec![Some(self); ids.len()] }; if !shared.has_item(index) { return vec![Some(self); ids.len()]; } - (0..ids.len()).map(|k| shared.item_in(index, k).map(|index| ItemTarget::Item { index, explicit, aligned: true })).collect() + let mut per: Vec<Option<ItemTarget>> = + (0..order.len()).map(|j| shared.item_in(index, j).map(|index| ItemTarget::Item { index, explicit, aligned: true })).collect(); + per.swap(0, k); + per + } + + /// Where among `ids` (the targets, in paint order) the object whose stack this item is a row of + /// is: the first selected object (or the compound path holding it) for the active item, which + /// need not paint first; the first target otherwise, or when that object is not among them. + pub(crate) fn anchor(self, s: &Session, ids: &[NodeId]) -> usize { + let ItemTarget::Item { explicit: false, .. } = self else { return 0 }; + let Some(st) = s.active() else { return 0 }; + let Some(first) = st.selection.subjects().first() else { return 0 }; + let root = roots_of(&st.doc, vec![*first]).first().copied().unwrap_or(*first); + ids.iter().position(|id| *id == root).unwrap_or(0) } /// The item of `ap` a fill (`fill`) or stroke edit changes; `None` = the topmost one. @@ -407,7 +426,7 @@ pub(crate) fn edit_items_then( return Ok(()); } let before = s.doc()?.doc.clone(); - let per = item.per_target(&before, ids); + let per = item.per_target(s, ids); super::overprint::edit_counted(s, label, |d| { let mut edited = Vec::new(); for (id, item) in ids.iter().zip(&per) { @@ -429,7 +448,7 @@ pub(crate) fn count_changed(d: &vectorcraft_doc::Document, before: &vectorcraft_ } /// Whether an edit aimed at `item` changes a stroke: the `stroke` param, else the kind of the -/// targeted item (on the first target object), else `default`. A `stroke` other than true, false or +/// targeted item (on the object whose row it is, see [`ItemTarget::anchor`]), else `default`. A `stroke` other than true, false or /// null is an error of command `cmd`. pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bool, cmd: &str) -> Result<bool> { check_switches(p, &["stroke"], cmd)?; @@ -439,7 +458,7 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo let ItemTarget::Item { index, .. } = item else { return Ok(default) }; let ids = appearance_targets(s, p)?; let d = &s.doc()?.doc; - Ok(ids.first().and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill())) + Ok(ids.get(item.anchor(s, &ids)).and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill())) } /// The whole number of 0 or more that `key` holds, read with [`index`]. diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index ec659abe8b..7ae1b72cc9 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -108,7 +108,7 @@ fn ids_json(ids: &[NodeId]) -> Value { pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: usize, cmd: &str) -> Result<Vec<(NodeId, Option<usize>, usize)>> { let roots = appearance_targets(s, p)?; let d = &s.doc()?.doc; - let per = item.per_target(d, &roots); + let per = item.per_target(s, &roots); let shared = if aligned(p) { shared_stack(d, &roots) } else { None }; let mut out = Vec::with_capacity(roots.len()); for (k, (id, item)) in roots.iter().zip(per).enumerate() { diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index 3a56ff7f18..d18de9e30f 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -463,6 +463,46 @@ fn reduce_to_basic_keeps_the_active_row_of_the_first_selected_object() { assert_eq!(fill_paint(&node(&s, a), 0).color().unwrap().to_hex(), "#0000ff"); } +/// b `[Fill red, Fill white, Stroke]` above a `[Fill white, Stroke]`, selected b first: b's rows 1 +/// and 2 equal a's rows 0 and 1. +fn reversed_pair(s: &mut Session) -> (NodeId, NodeId) { + let a = rect(s, 50.0); + let b = rect(s, 200.0); + run(s, "appearance.addFill", json!({})); + run(s, "appearance.moveItem", json!({"from": 2, "to": 0})); + run(s, "appearance.setItem", json!({"index": 0, "color": "#ff0000"})); + run(s, "select.set", json!({"ids": [b.0, a.0]})); + (a, b) +} + +/// The active row is a row of the first selected object also for paint, stroke and effect edits +/// when that object paints above the others. +#[test] +fn edits_change_the_active_row_of_the_first_selected_object() { + let mut s = session(); + let (a, b) = reversed_pair(&mut s); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); // b's red fill + run(&mut s, "paint.setFill", json!({"color": "#00ff00"})); + let (na, nb) = (node(&s, a), node(&s, b)); + assert_eq!(fill_paint(&nb, 0).color().unwrap().to_hex(), "#00ff00"); + assert_eq!(*fill_paint(&nb, 1), Paint::solid(Color::WHITE)); + // a shares no red row, so its fill row 0 changes, as for an active row the objects don't share. + assert_eq!(fill_paint(&na, 0).color().unwrap().to_hex(), "#00ff00"); + run(&mut s, "effect.apply", json!({"effect": "distort.twist"})); + let nb = node(&s, b); + assert_eq!((nb.appearance.items[0].effects().len(), nb.appearance.items[1].effects().len()), (1, 0)); + + let mut s = session(); + let (a, b) = reversed_pair(&mut s); + run(&mut s, "appearance.setActiveItem", json!({"index": 1})); // b's white fill, a's row 0 + run(&mut s, "paint.editGradient", json!({"kind": "radial"})); + let (na, nb) = (node(&s, a), node(&s, b)); + assert!(matches!(fill_paint(&nb, 1), Paint::Gradient(_)), "b's white fill takes the gradient"); + assert!(matches!(fill_paint(&na, 0), Paint::Gradient(_)), "so does a's equal fill"); + assert_eq!(fill_paint(&nb, 0).color().unwrap().to_hex(), "#ff0000"); + assert!(!matches!(stroke(&nb, 2).paint, Paint::Gradient(_)) && !matches!(stroke(&na, 1).paint, Paint::Gradient(_))); +} + /// How many steps there are to undo and to redo, and whether the document has unsaved changes. fn history(s: &Session) -> (usize, usize, bool) { let st = s.doc().unwrap(); From f9e78eb144312c68df6594e039f7806ecf063e02 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 08:44:05 -0700 Subject: [PATCH 098/260] Appearance: effect.apply reports the active row's object, and an empty aligned target list is an error effect.apply now reports the item of the first selected object, whose row the active item is. With nothing selected, an explicit aligned item returns the command's error instead of an internal error. --- crates/engine/src/cmd/appearance.rs | 2 +- crates/engine/src/cmd/effectcmd.rs | 5 +++-- crates/engine/src/tests/appearance.rs | 10 ++++++++++ 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 66d6ab232a..33379e752e 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -262,7 +262,7 @@ impl ItemTarget { /// targets don't share, and any other target, stands for itself in every target. pub(crate) fn per_target(self, s: &Session, ids: &[NodeId]) -> Vec<Option<ItemTarget>> { let ItemTarget::Item { index, explicit, aligned: true } = self else { return vec![Some(self); ids.len()] }; - let Some(st) = s.active() else { return vec![Some(self); ids.len()] }; + let Some(st) = s.active().filter(|_| ids.len() >= 2) else { return vec![Some(self); ids.len()] }; let k = self.anchor(s, ids); let mut order = ids.to_vec(); order.swap(0, k); diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 7ae1b72cc9..25a5ff004d 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -219,8 +219,9 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> { index = fx.len() - 1; true })?; - // The item the effect landed on in the first object (the active item applies where it fits). - let first = ids.first().and_then(|id| s.doc().ok()?.doc.node(*id)); + // The item the effect landed on in the object whose row the item is (the first selected object + // for the active item, which applies where it fits). + let first = ids.get(item.anchor(s, &ids)).and_then(|id| s.doc().ok()?.doc.node(*id)); let landed = first.and_then(|n| item.effects_item(&n.appearance, C).ok().flatten()); Ok(json!({ "ids": ids_json(&ids), "index": index, "item": landed })) } diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index d18de9e30f..e368711889 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -501,6 +501,16 @@ fn edits_change_the_active_row_of_the_first_selected_object() { assert!(matches!(fill_paint(&na, 0), Paint::Gradient(_)), "so does a's equal fill"); assert_eq!(fill_paint(&nb, 0).color().unwrap().to_hex(), "#ff0000"); assert!(!matches!(stroke(&nb, 2).paint, Paint::Gradient(_)) && !matches!(stroke(&na, 1).paint, Paint::Gradient(_))); + // The effect goes on the equal rows, and the reply names the active row of b. + run(&mut s, "appearance.setActiveItem", json!({"index": 2})); // b's stroke, a's row 1 + let r = run(&mut s, "effect.apply", json!({"effect": "distort.twist"})); + assert_eq!(r["item"], 2); + let (na, nb) = (node(&s, a), node(&s, b)); + assert_eq!((stroke(&nb, 2).effects.len(), stroke(&na, 1).effects.len()), (1, 1)); + // With nothing selected an aligned item is an error, not a crash. + run(&mut s, "select.set", json!({"ids": []})); + let e = s.execute("effect.remove", &json!({"index": 0, "item": 0, "aligned": true})).unwrap_err().to_string(); + assert!(!e.contains("internal error"), "{e}"); } /// How many steps there are to undo and to redo, and whether the document has unsaved changes. From 77bdf478e41dd4ae39b63baa72bd737efb556059 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 08:17:21 -0700 Subject: [PATCH 099/260] Perspective: a homography product that overflows is refused instead of stored or drawn Homography::then_after returned products whose entries could overflow to infinity or become NaN. A move, transform or grid reproject of type or a symbol instance whose stored projection has large finite entries stored such a product, and the type was then drawn flat, since a projection that is not finite reads as none. - Homography::checked_then_after returns None when an entry of the product is not finite. - project_node composes each type and symbol instance projection with it and returns false, leaving the object as it is, when one would not be finite; moves and transforms in perspective and Define Perspective Grid with reproject then return the horizon error and leave the document unchanged. - transform_map, attach_homography and size_homography return None for such a product. - Edit Text returns the horizon error, and does not enter isolation mode, when the type cannot be shown flat where it is drawn. --- .../engine/src/cmd/distortcmds/perspective.rs | 17 ++--- crates/engine/src/tests/persp_text.rs | 64 +++++++++++++++++++ crates/geom/src/projective.rs | 20 ++++++ crates/tools/src/distort.rs | 30 ++++++++- crates/tools/src/distort/perspective.rs | 6 +- docs/target-app-parity.md | 1 + 6 files changed, 124 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index 54cac360d5..eda17fee88 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -52,8 +52,8 @@ pub(super) fn grid_set(s: &mut Session, p: &Value) -> Result<Value> { old.adopt_stored_attachments(d); for (id, plane, depth) in persp::attached_roots(d) { let h = old.homography_at(plane, depth).and_then(|h| h.inverse()).zip(g.homography_at(plane, depth)); - let (hi, h) = h.ok_or_else(|| EngineError::Other("an object in perspective would leave the edited grid".into()))?; - let m = h.then_after(&hi); + let m = h.and_then(|(hi, h)| h.checked_then_after(&hi)); + let m = m.ok_or_else(|| EngineError::Other("an object in perspective would leave the edited grid".into()))?; warp_checked(d, id, &m)?; } } @@ -98,17 +98,15 @@ pub(super) fn roots(s: &Session, p: &Value) -> Result<Vec<NodeId>> { } } -/// Map `n` with `f`, failing if any point would leave the plane's visible side. /// Map `n` with `h` (type and symbols in perspective keep their art and are drawn through it), -/// failing if any point would leave the plane's visible side. +/// failing if any point would leave the plane's visible side or a projection would not be finite. fn warp_checked(d: &mut Document, id: NodeId, h: &Homography) -> Result<()> { let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; let mut pts = vec![]; collect_points(n, &mut pts); - if pts.iter().any(|q| h.apply(*q).is_none()) { + if pts.iter().any(|q| h.apply(*q).is_none()) || !project_node(n, h) { return Err(EngineError::Other("the object would cross the horizon of the perspective plane".into())); } - project_node(n, h); Ok(()) } @@ -599,11 +597,14 @@ pub(super) fn edit_text(s: &mut Session, p: &Value) -> Result<Value> { let NodeKind::Text(t) = &mut n.kind else { return Err(EngineError::Other("select type in perspective".into())) }; // Shown flat where it is drawn: the type moves there and the projection moves the other // way, so the picture stays. - let (Some(flat), Some(drawn)) = (t.bounds(), t.bounds().and_then(|b| h.map_rect_bbox(b))) else { return Ok(()) }; + let Some(flat) = t.bounds() else { return Ok(()) }; + let cross = || EngineError::Other("the object would cross the horizon of the perspective plane".into()); + let drawn = h.map_rect_bbox(flat).ok_or_else(cross)?; let shift = vectorcraft_geom::Affine::translate(drawn.center() - flat.center()); + let moved = h.checked_then_after(&Homography::from_affine(shift.inverse())).ok_or_else(cross)?; t.transform(shift); if let Some(rec) = n.extras_if_any().and_then(|e| e.perspective.as_deref_mut()) { - rec.projection = Some(h.then_after(&Homography::from_affine(shift.inverse())).to_array()); + rec.projection = Some(moved.to_array()); rec.editing = true; } Ok(()) diff --git a/crates/engine/src/tests/persp_text.rs b/crates/engine/src/tests/persp_text.rs index 9de16c451b..ae447915f6 100644 --- a/crates/engine/src/tests/persp_text.rs +++ b/crates/engine/src/tests/persp_text.rs @@ -113,6 +113,39 @@ fn moving_type_in_perspective_moves_its_projection() { let _ = rect; } +#[test] +fn moving_type_whose_projection_would_overflow_is_refused() { + let (mut s, _) = persp_session(); + let id = persp_text(&mut s); + let NodeKind::Text(t) = &node(&s, id).kind else { panic!("type") }; + let flat = t.bounds().unwrap(); + // A stored projection that draws the type flat where it is, with every entry scaled by `k`: a + // document can hold it (its entries are finite) and the type draws, but its product with a + // scale by 2 in perspective overflows. + let step = grid(&s).transform_map(Plane::Right, 0.0, vectorcraft_geom::Affine::scale(2.0), 0.0).unwrap(); + let scaled = |e: i32| { + let k = 2f64.powf(f64::from(e) / 16.0); + vectorcraft_geom::Homography([[k, 0.0, 0.0], [0.0, k, 0.0], [0.0, 0.0, k]]) + }; + let finite = |m: &vectorcraft_geom::Homography| m.to_array().iter().all(|v| v.is_finite()); + let draws = |m: &vectorcraft_geom::Homography| { + let drawn = m.map_rect_bbox(flat); + drawn.is_some_and(|b| step.map_rect_bbox(b).is_some()) && vectorcraft_geom::Homography::from_array(m.to_array()) == Some(*m) + }; + let e = (0..16 * 1024).find(|e| draws(&scaled(*e)) && !finite(&step.then_after(&scaled(*e)))).unwrap_or_else(|| panic!("{step:?} {flat:?}")); + let big = scaled(e); + let mut doc = s.doc().unwrap().doc.clone(); + let mut extras = std::sync::Arc::make_mut(&mut doc).node_mut(id).unwrap().extras_mut(); + extras.perspective.as_deref_mut().unwrap().projection = Some(big.to_array()); + drop(extras); + s.doc_mut().unwrap().doc = doc; + let before = (node(&s, id), undo_len(&s)); + assert!(s.execute("perspective.transform", &json!({"ids": [id.0], "matrix": [2, 0, 0, 2, 0, 0]})).is_err()); + assert_eq!((node(&s, id), undo_len(&s)), before, "the document is unchanged"); + let stored = node(&s, id).extras().perspective.as_deref().and_then(|p| p.projection).unwrap(); + assert!(stored.iter().all(|v| v.is_finite())); +} + #[test] fn edit_text_shows_it_flat_in_isolation_then_projects_it_again() { let (mut s, _) = persp_session(); @@ -141,6 +174,37 @@ fn edit_text_shows_it_flat_in_isolation_then_projects_it_again() { assert!(s2.execute("perspective.editText", &json!({"id": rect.0})).is_err()); } +#[test] +fn edit_text_whose_flat_view_would_overflow_is_refused() { + let (mut s, _) = persp_session(); + let id = persp_text(&mut s); + let NodeKind::Text(t) = &node(&s, id).kind else { panic!("type") }; + let flat = t.bounds().unwrap(); + // A stored projection that draws the type 4 times its size, with every entry scaled by `k`: a + // document can hold it and the type draws, but the projection that shows it flat where it is + // drawn overflows. + let scaled = |e: i32| { + let k = 2f64.powf(f64::from(e) / 16.0); + vectorcraft_geom::Homography([[4.0 * k, 0.0, 0.0], [0.0, 4.0 * k, 0.0], [0.0, 0.0, k]]) + }; + let overflows = |m: &vectorcraft_geom::Homography| { + let Some(drawn) = m.map_rect_bbox(flat) else { return false }; + let shift = vectorcraft_geom::Affine::translate(drawn.center() - flat.center()); + let moved = m.then_after(&vectorcraft_geom::Homography::from_affine(shift.inverse())); + vectorcraft_geom::Homography::from_array(m.to_array()) == Some(*m) && moved.to_array().iter().any(|v| !v.is_finite()) + }; + let e = (0..16 * 1024).find(|e| overflows(&scaled(*e))).unwrap_or_else(|| panic!("{flat:?}")); + let mut doc = s.doc().unwrap().doc.clone(); + let mut extras = std::sync::Arc::make_mut(&mut doc).node_mut(id).unwrap().extras_mut(); + extras.perspective.as_deref_mut().unwrap().projection = Some(scaled(e).to_array()); + drop(extras); + s.doc_mut().unwrap().doc = doc; + let before = (node(&s, id), undo_len(&s)); + assert!(s.execute("perspective.editText", &json!({"id": id.0})).is_err()); + assert_eq!((node(&s, id), undo_len(&s)), before, "the document is unchanged"); + assert_eq!(s.doc().unwrap().isolation, None, "not in isolation mode"); +} + /// Edit Text, which shows the type in isolation mode, is off while an opacity mask is edited. #[test] fn edit_text_is_off_while_an_opacity_mask_is_edited() { diff --git a/crates/geom/src/projective.rs b/crates/geom/src/projective.rs index ddf836a23f..77bb513b45 100644 --- a/crates/geom/src/projective.rs +++ b/crates/geom/src/projective.rs @@ -99,6 +99,13 @@ impl Homography { Self(out) } + /// [`Self::then_after`]; `None` when an entry of the product is not finite (an entry + /// overflows, or a factor has one that is not finite). + pub fn checked_then_after(&self, other: &Self) -> Option<Self> { + let c = self.then_after(other); + c.is_finite().then_some(c) + } + /// `self` seen through `a`: the map `a ∘ self ∘ a⁻¹` (what `self` becomes when everything it /// maps from and to is moved by `a`). When the product overflows, every entry is formed with /// its powers of two kept apart, and the product is returned divided by the largest magnitude @@ -267,6 +274,19 @@ mod tests { assert!(h().inverse().is_some()); } + #[test] + fn a_product_that_overflows_is_none() { + // Each factor is finite and invertible, but the product's first entry is 1e400. + let big = Homography([[1e200, 0.0, 0.0], [0.0, 1e200, 0.0], [0.0, 0.0, 1e200]]); + assert!(Homography::from_array(big.to_array()).is_some()); + assert_eq!(big.checked_then_after(&big), None); + let nan = Homography([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, f64::NAN]]); + assert_eq!(h().checked_then_after(&nan), None); + assert_eq!(h().checked_then_after(&Homography::IDENTITY), Some(h())); + let inv = h().inverse().unwrap(); + assert_eq!(h().checked_then_after(&inv), Some(h().then_after(&inv))); + } + #[test] fn a_derivative_that_overflows_is_none() { // The point maps to 1e300, but the derivative there is 1e302 / 1e-8. diff --git a/crates/tools/src/distort.rs b/crates/tools/src/distort.rs index 55fa9a9b9c..30cb1cd4c5 100644 --- a/crates/tools/src/distort.rs +++ b/crates/tools/src/distort.rs @@ -50,9 +50,31 @@ pub fn warp_node_with(n: &mut Node, f: &dyn Fn(Point) -> Point) { } /// [`warp_node_with`] for the projective map `h` (perspective): type and symbol instances keep -/// their flat art and are drawn through `h` (composed with the projection they had). -pub fn project_node(n: &mut Node, h: &Homography) { +/// their flat art and are drawn through `h` (composed with the projection they had). Returns +/// `false`, and leaves `n` as it is, when the projection of a type or symbol instance in `n` would +/// have an entry that is not finite. +pub fn project_node(n: &mut Node, h: &Homography) -> bool { + if !projects_finitely(n, h) { + return false; + } warp_node(n, &|p| h.apply(p).unwrap_or(p), Some(h)); + true +} + +/// Whether every type and symbol instance that [`project_node`] reaches in `n` keeps a projection +/// whose entries are all finite. +fn projects_finitely(n: &Node, h: &Homography) -> bool { + match &n.kind { + NodeKind::Text(_) | NodeKind::SymbolInstance { .. } => { + let had = n.extras().perspective.as_deref().and_then(|p| p.homography()).unwrap_or(Homography::IDENTITY); + h.checked_then_after(&had).is_some() + } + NodeKind::Layer { children, .. } + | NodeKind::Group { children, .. } + | NodeKind::Compound { children, .. } + | NodeKind::Blend { children, .. } => children.iter().all(|c| projects_finitely(c, h)), + _ => true, + } } fn warp_node(n: &mut Node, f: &dyn Fn(Point) -> Point, h: Option<&Homography>) { @@ -62,7 +84,9 @@ fn warp_node(n: &mut Node, f: &dyn Fn(Point) -> Point, h: Option<&Homography>) { let mut extras = n.extras_mut(); let rec = extras.perspective.get_or_insert_with(Default::default); let had = rec.homography().unwrap_or(Homography::IDENTITY); - rec.projection = Some(h.then_after(&had).to_array()); + if let Some(c) = h.checked_then_after(&had) { + rec.projection = Some(c.to_array()); + } return; } let bounds = n.geometric_bounds(); diff --git a/crates/tools/src/distort/perspective.rs b/crates/tools/src/distort/perspective.rs index 7f3f374055..2e9ecb558b 100644 --- a/crates/tools/src/distort/perspective.rs +++ b/crates/tools/src/distort/perspective.rs @@ -449,7 +449,7 @@ impl PerspectiveGrid { pub fn transform_map(&self, plane: Plane, depth: f64, m: Affine, dz: f64) -> Option<Homography> { let h = self.homography_at(plane, depth)?; let to = self.homography_at(plane, depth + dz)?; - Some(to.then_after(&Homography::from_affine(m)).then_after(&h.inverse()?)) + to.checked_then_after(&Homography::from_affine(m))?.checked_then_after(&h.inverse()?) } /// Where object `id` is attached (plane, depth): its own record, else the one a grid stored @@ -529,7 +529,7 @@ impl PerspectiveGrid { let sy = if b.height().abs() > 1e-9 { (c.y - a.y) / b.height() } else { sx.abs() * if c.y < a.y { -1.0 } else { 1.0 } }; let sx = if b.width().abs() > 1e-9 { sx } else { sy.abs() }; let m = Affine::new([sx, 0.0, 0.0, sy, a.x - b.x0 * sx, a.y - b.y0 * sy]); - Some(h.then_after(&Homography::from_affine(m))) + h.checked_then_after(&Homography::from_affine(m)) } /// The map that puts flat art drawn at `at` onto `plane` keeping its sizes in plane units (a @@ -544,7 +544,7 @@ impl PerspectiveGrid { let sx = if h.apply(q + Vec2::new(1.0, 0.0))?.x < at.x { -1.0 } else { 1.0 }; let sy = if h.apply(q + Vec2::new(0.0, 1.0))?.y < at.y { -1.0 } else { 1.0 }; let m = Affine::new([sx, 0.0, 0.0, sy, q.x - sx * at.x, q.y - sy * at.y]); - Some(h.then_after(&Homography::from_affine(m))) + h.checked_then_after(&Homography::from_affine(m)) } /// The map that slides art lying on `plane` by the plane-space offset between `from` and `to`. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d852ff5bbb..0a699babf4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -991,6 +991,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Lock Grid, Lock Station Point, Snap to Grid and Show Rulers (View › Perspective Grid) and Import Perspective Grid Presets (its choice to replace saved presets of the same names) refuse a value other than true, false or null, such as "true", and leave the grid and the saved presets as they were. All Artwork Above and Other Layers (Object › Lock and Object › Hide), Transform Each, Rearrange All Artboards, the width point and width profile commands, Liquify, Puppet Warp, Define Perspective Grid, Attach to Active Plane, Release with Perspective, moves and transforms in perspective, Move Plane and Move Plane to Match Object record no undo step when they change nothing. Move in Perspective (its copy, perpendicular and Snap to Grid choices), Transform in Perspective (its copy), Nudge in Perspective (its ×10 and copy), Draw in Perspective (Snap to Grid), Define Perspective Grid (its reproject choice), Show Perspective Grid, Width Point (Adjust Adjoining Width Points), Liquify (its pen pressure, Simplify and Affect choices) and Puppet Warp (its pins' rest shape) refuse a value other than true, false or null, such as "true", and leave the document and its undo history as they were. + Moves and transforms in perspective and Define Perspective Grid with reproject return an error, and leave the document and its undo history as they were, when the projection they would give type or a symbol instance in perspective has a number too large to store. Object › Perspective › Edit Text returns an error, and does not enter isolation mode, when the type cannot be shown flat where it is drawn: when part of it crosses the horizon, or when that view's projection has a number too large to store. Regressions: `a_product_that_overflows_is_none` in `crates/geom/src/projective.rs`, and `moving_type_whose_projection_would_overflow_is_refused` and `edit_text_whose_flat_view_would_overflow_is_refused` in `crates/engine/src/tests/persp_text.rs`. Create Object Mosaic (its columns and rows), Transform Each (its reference point and Random seed) and Rearrange All Artboards (its columns) refuse a fraction, a negative number or a string, such as 2.5, -1 or "4"; 4.0 counts as 4. Move, Rotate, Scale, Reflect, Shear, Transform Again, Nudge and the Transform panel's values (their copy, Scale Strokes & Effects, Scale Corners, Transform Patterns, Transform Objects and area type options), Align, Distribute and Distribute Spacing (Transform Patterns), Object Properties (visible, locked, Isolate Blending and Opacity & Mask Define Knockout Shape) and Live Shape Properties (Invert Pie, Make Sides Equal and relative rounding) refuse a value other than true, false or null, such as "false", and leave the document as it was. Object Properties (its opacity), Live Shape Properties (corner radius and polygon sides), the Transform panel's reference point and Align, Distribute and Distribute Spacing to an artboard (the artboard's number) refuse a value other than a number or null, such as "50", and leave the document as it was. From a48ab7f8c6377f938bae4ee91212eb122a4360b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 08:20:33 -0700 Subject: [PATCH 100/260] Fix #3325: art nested in Affinity text is clipped to the characters An Affinity text object whose children are nested in it (an image dragged into artistic text, for example) opened as a plain group, so the image was drawn over the text. The text now becomes a clip group whose clipping path is the type, as a shape with children already does: the nested art shows only inside the characters, with the characters' fill behind it and their stroke over it. --- crates/affinity/README.md | 2 +- crates/affinity/tests/support/text_fixture.rs | 32 +++++++++++-------- .../engine/src/cmd/fileio/affinity/nodes.rs | 17 ++++++---- crates/engine/tests/affinity_text.rs | 28 ++++++++++++++++ 4 files changed, 59 insertions(+), 20 deletions(-) diff --git a/crates/affinity/README.md b/crates/affinity/README.md index 62e2974d26..f0339d6985 100644 --- a/crates/affinity/README.md +++ b/crates/affinity/README.md @@ -17,7 +17,7 @@ Affinity files. | Curves (`PCrv`): cubic subpaths, closed flags, live corners (`CnrD`) | paths (multi-subpath curves fill even-odd) | | Rectangles with corner radii (relative or absolute, locked or per corner) and round or straight corners, ellipses, polygons (smooth too), stars, square stars, pies, triangles, trapezoids | paths | | Compound shapes (`Comp`, add and subtract) | one even-odd path | -| A shape or curve with children clips them | clip group whose clipping path keeps its fill (behind) and stroke (over) | +| A shape, curve or text with children clips them | clip group whose clipping path keeps its fill (behind) and stroke (over) | | Vector masks (`AdCh` curves and shapes) | clip group | | Pixel masks (`MRst`, attached or as a layer in a group) | opacity mask | | Solid fills: RGBA, HSLA, CMYK, grey, Lab (D50) | fill appearance (alpha as fill opacity) | diff --git a/crates/affinity/tests/support/text_fixture.rs b/crates/affinity/tests/support/text_fixture.rs index 574a0ca38a..01baa067e8 100644 --- a/crates/affinity/tests/support/text_fixture.rs +++ b/crates/affinity/tests/support/text_fixture.rs @@ -98,20 +98,26 @@ pub fn utf8(text: &str) -> F { } pub fn document(blocks: Vec<F>, frame: bool, dpi: f64, transform: [f64; 6]) -> Vec<u8> { - let text = F::Obj( - tag(if frame { b"TxtF" } else { b"TxtA" }), - vec![ - (tag(b"StSt"), F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(blocks))])), - ( - tag(b"TxtH"), - F::Obj( - tag(if frame { b"FrFr" } else { b"ArFr" }), - vec![(tag(b"FrmB"), F::F64s(vec![10.0, 20.0, 210.0, 120.0])), (tag(b"ArtV"), F::F64(18.0))], - ), + document_with_children(blocks, frame, dpi, transform, vec![]) +} + +/// [`document`] whose text holds `children` (objects nested inside the text). +pub fn document_with_children(blocks: Vec<F>, frame: bool, dpi: f64, transform: [f64; 6], children: Vec<F>) -> Vec<u8> { + let mut fields = vec![ + (tag(b"StSt"), F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(blocks))])), + ( + tag(b"TxtH"), + F::Obj( + tag(if frame { b"FrFr" } else { b"ArFr" }), + vec![(tag(b"FrmB"), F::F64s(vec![10.0, 20.0, 210.0, 120.0])), (tag(b"ArtV"), F::F64(18.0))], ), - (tag(b"Xfrm"), F::F64s(transform.to_vec())), - ], - ); + ), + (tag(b"Xfrm"), F::F64s(transform.to_vec())), + ]; + if !children.is_empty() { + fields.push((tag(b"Chld"), F::Shared(children))); + } + let text = F::Obj(tag(if frame { b"TxtF" } else { b"TxtA" }), fields); let mut root = vec![ (tag(b"UVCn"), F::Obj(tag(b"UVCn"), vec![(tag(b"UPPI"), F::F64(dpi))])), ( diff --git a/crates/engine/src/cmd/fileio/affinity/nodes.rs b/crates/engine/src/cmd/fileio/affinity/nodes.rs index 0375ff39e4..2e93342279 100644 --- a/crates/engine/src/cmd/fileio/affinity/nodes.rs +++ b/crates/engine/src/cmd/fileio/affinity/nodes.rs @@ -186,14 +186,19 @@ impl Builder { return Some(Arc::new(g)); }; self.outline_text(&n.effects, &mut text); - let mut node = self.base(n, NodeKind::Text(Box::new(text))); - node.opacity *= alpha; - if !children.is_empty() { - let mut kids = vec![Arc::new(node)]; + if children.is_empty() { + let mut node = self.base(n, NodeKind::Text(Box::new(text))); + node.opacity *= alpha; + node + } else { + // Text clips its children as a shape does: the type is the clipping path, its + // characters' fill behind the clipped art and their stroke over it. + let mut clip = Node::new(self.doc.alloc_id(), NodeKind::Text(Box::new(text))); + clip.opacity = alpha; + let mut kids = vec![Arc::new(clip)]; kids.extend(children); - node = Node::group(self.doc.alloc_id(), kids); + self.base(n, NodeKind::Group { children: kids, clip: true }) } - node } Kind::Table(t) => { let mut kids = self.table(t, to_doc); diff --git a/crates/engine/tests/affinity_text.rs b/crates/engine/tests/affinity_text.rs index 42224bfcb8..d9530b652b 100644 --- a/crates/engine/tests/affinity_text.rs +++ b/crates/engine/tests/affinity_text.rs @@ -88,6 +88,34 @@ fn frame_type_keeps_dimensions_alignment_and_unit_conversion() { assert_eq!(frame.bounds().unwrap().height(), 50.0); } +#[test] +fn objects_nested_in_text_are_clipped_by_the_type() { + let ellipse = F::Obj( + tag(b"ShpN"), + vec![ + (tag(b"Desc"), F::Str("Inside".into())), + (tag(b"Shpe"), F::Obj(tag(b"ShpE"), vec![])), + (tag(b"ShpB"), F::F64s(vec![10.0, 20.0, 110.0, 70.0])), + (tag(b"BFFl"), F::Shared(vec![F::Obj(tag(b"FDsc"), vec![(tag(b"FDeF"), solid(1.0))])])), + ], + ); + let bytes = document_with_children( + vec![block(utf8("TEXT"), vec![run(4, Some(attrs("Clip", "", 400, false, 40.0)))], &[])], + false, + 72.0, + IDENTITY, + vec![ellipse], + ); + let loaded = fileio::load("nested.af", &bytes).unwrap(); + let NodeKind::Layer { children, .. } = &loaded.doc.layers[0].kind else { panic!("{:?}", loaded.doc.layers[0].kind) }; + let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("{:?}", children[0].kind) }; + let [text, inside] = clipped.as_slice() else { panic!("{clipped:?}") }; + let NodeKind::Text(t) = &text.kind else { panic!("{:?}", text.kind) }; + assert_eq!(t.runs[0].text, "TEXT"); + assert_eq!(inside.name.as_deref(), Some("Inside")); + assert!(matches!(inside.kind, NodeKind::Path { clipping: false, .. }), "{:?}", inside.kind); +} + #[test] fn a_frame_too_short_for_its_first_line_is_made_taller_with_a_warning() { // #1423: a title taller than its frame (60 pt type in a 50 pt frame) drew nothing. From e8b1f1187d08f6e5d129c10ce583e4b1fd7fee6c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 09:20:19 -0700 Subject: [PATCH 101/260] Tests: a pixel layer nested in Affinity text stays an image inside the clip objects_nested_in_text_are_clipped_by_the_type now also nests a 4 x 4 Rstr pixel layer under the TxtA and checks that it is read as an image in the clipping group, next to the shape. --- crates/engine/tests/affinity_text.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/affinity_text.rs b/crates/engine/tests/affinity_text.rs index d9530b652b..104625c7cb 100644 --- a/crates/engine/tests/affinity_text.rs +++ b/crates/engine/tests/affinity_text.rs @@ -99,21 +99,32 @@ fn objects_nested_in_text_are_clipped_by_the_type() { (tag(b"BFFl"), F::Shared(vec![F::Obj(tag(b"FDsc"), vec![(tag(b"FDeF"), solid(1.0))])])), ], ); + // A 4 × 4 RGBA pixel layer of one flat colour (tile state 2: every sample 255). + let mut bitmap = vec![(tag(b"Frmt"), F::Enum(0, 0)), (tag(b"BmpW"), F::I32(4)), (tag(b"BmpH"), F::I32(4))]; + for c in 1..=4 { + bitmap.push((tag(&[b'T', b'W', b'i', b'0' + c]), F::I32(1))); + bitmap.push((tag(&[b'T', b'H', b'i', b'0' + c]), F::I32(1))); + bitmap.push((tag(&[b'S', b't', b'a', b'0' + c]), F::U8s(vec![2]))); + } + let pixels = F::Obj(tag(b"Rstr"), vec![(tag(b"Bitm"), F::Obj(tag(b"DyBm"), bitmap)), (tag(b"Desc"), F::Str("Photo".into()))]); let bytes = document_with_children( vec![block(utf8("TEXT"), vec![run(4, Some(attrs("Clip", "", 400, false, 40.0)))], &[])], false, 72.0, IDENTITY, - vec![ellipse], + vec![ellipse, pixels], ); let loaded = fileio::load("nested.af", &bytes).unwrap(); let NodeKind::Layer { children, .. } = &loaded.doc.layers[0].kind else { panic!("{:?}", loaded.doc.layers[0].kind) }; let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("{:?}", children[0].kind) }; - let [text, inside] = clipped.as_slice() else { panic!("{clipped:?}") }; + let [text, inside, photo] = clipped.as_slice() else { panic!("{clipped:?}") }; let NodeKind::Text(t) = &text.kind else { panic!("{:?}", text.kind) }; assert_eq!(t.runs[0].text, "TEXT"); assert_eq!(inside.name.as_deref(), Some("Inside")); assert!(matches!(inside.kind, NodeKind::Path { clipping: false, .. }), "{:?}", inside.kind); + assert_eq!(photo.name.as_deref(), Some("Photo")); + let NodeKind::Image(image) = &photo.kind else { panic!("{:?}", photo.kind) }; + assert_eq!((image.width, image.height), (4, 4)); } #[test] From 5751dcc293cf0436c7241bb006932d124ec570d0 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 07:56:25 -0700 Subject: [PATCH 102/260] Blob Brush: the tip preview is a named Angle slider with arrow keys The tip preview square in the Blob Brush Tool Options set the Angle by a drag but had no accessible name, no value and no keyboard control. Screen readers now get it as the Angle slider with the Angle in degrees as its value. A click or a drag gives it the keyboard focus, and the arrow keys, Shift with an arrow, Page Up and Page Down, Home and End step the Angle within -180 to 180 degrees, as the dialog sliders built on color_slider_stepped do (crates/ui-egui/src/widgets/color.rs). The new widgets::stepped_area gives a caller-drawn control that slider's screen-reader node, focus, keys and focus outline. --- crates/ui-egui/src/dialogs/freehand.rs | 17 ++++++--- crates/ui-egui/src/dialogs/tests.rs | 53 ++++++++++++++++++++++++++ crates/ui-egui/src/widgets.rs | 2 +- crates/ui-egui/src/widgets/color.rs | 20 +++++++++- docs/target-app-parity.md | 1 + 5 files changed, 85 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index bd6068638c..7660287753 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -253,16 +253,16 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { const TIP_PREVIEW: f32 = 64.0; /// The Blob Brush's tip preview: a square with the tip at its Angle and Roundness and a line along -/// its long axis (a drag in the square sets the Angle), and beside it three dabs of the tip, the -/// middle one darker. +/// its long axis, and beside it three dabs of the tip, the middle one darker. A click or a drag in +/// the square points the Angle at the pointer and gives the square the keyboard focus; screen +/// readers get it as the Angle slider, and its keys step the Angle as a dialog slider's do +/// ([`widgets::stepped_area`]) within -180° to 180°. fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(egui::vec2(CONTENT_W, TIP_PREVIEW), egui::Sense::hover()); let square = egui::Rect::from_min_size(rect.min, egui::vec2(TIP_PREVIEW, TIP_PREVIEW)); - let response = ui.interact(square, ui.scope_id().with("freehand-tip-angle"), egui::Sense::drag()); - if response.dragged() - && let Some(p) = response.interact_pointer_pos() - { + let response = ui.interact(square, ui.scope_id().with("freehand-tip-angle"), egui::Sense::click_and_drag()); + if let Some((p, _)) = widgets::pointer_phase(&response) { let delta = p - square.center(); if delta.length_sq() > 1.0 { d.fields.insert("angle".into(), json!(f64::from((-delta.y).atan2(delta.x)).to_degrees().round())); @@ -271,6 +271,11 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { let painter = ui.painter_at(rect); painter.rect_filled(square, 2.0, t.input); painter.rect_stroke(square, 2.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); + // After the square's frame, so the focus outline draws over it. + let shown = widgets::SliderValue::field(d.f64("angle", 0.0), -180.0..=180.0, "°", 0); + if let Some(a) = widgets::stepped_area(ui, &response, tl!("Angle"), Some(shown)) { + d.fields.insert("angle".into(), json!(a)); + } let a = d.f64("angle", 0.0).clamp(-180.0, 180.0).to_radians(); // The long axis on screen (y down: a positive angle tilts it up to the right) and the short one. let u = egui::vec2(a.cos() as f32, -a.sin() as f32); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index d4b6698a8b..ee870e4a8f 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1900,6 +1900,59 @@ fn the_flattener_and_3d_sliders_step_with_the_arrow_keys() { } } +/// The Blob Brush Tool Options' tip preview is the Angle slider for screen readers, with the Angle +/// as its value. A click in it points the Angle at the pointer and gives it the focus, its arrow +/// keys then step the Angle by one degree (ten with Shift) within -180° to 180°, Shift+Tab leaves +/// it for the Roundness field and Tab comes back to it, and a drag still sets the Angle. +#[test] +fn the_blob_brush_tip_preview_is_a_named_slider_with_arrow_keys() { + use egui::Key::{ArrowDown, ArrowLeft, ArrowRight, ArrowUp, End, Home, Tab}; + use egui::Modifiers as M; + let mut app = app(); + app.run("tool.options", json!({"tool": "blobBrush"})).unwrap(); + let angle = |app: &VectorcraftApp| app.ui.dialog.as_ref().expect("Blob Brush Tool Options is open").f64("angle", f64::NAN); + let mut f = Frames::new(); + f.run(&mut app, vec![]); + let out = f.run(&mut app, vec![]); + let (_, value, text) = slider_node(&out, "Angle"); + assert_eq!((value, text.as_deref()), (Some(0.0), Some("0°"))); + let center = f.control(&mut app, "Angle", egui::accesskit::Role::Slider); + let up_right = center + egui::vec2(20.0, -20.0); + f.press(&mut app, up_right, true); + f.press(&mut app, up_right, false); + assert_eq!(angle(&app), 45.0, "the click points the Angle up to the right"); + let mut seen = vec![]; + for (key, mods, want) in [ + (ArrowRight, M::NONE, 46.0), + (ArrowUp, M::NONE, 47.0), + (ArrowLeft, M::NONE, 46.0), + (ArrowDown, M::NONE, 45.0), + (ArrowRight, M::SHIFT, 55.0), + (End, M::NONE, 180.0), + (ArrowRight, M::NONE, 180.0), + (Home, M::NONE, -180.0), + (ArrowLeft, M::SHIFT, -180.0), + (ArrowRight, M::NONE, -179.0), + ] { + f.key(&mut app, key, mods); + seen.push((key, mods.shift, angle(&app))); + assert_eq!(angle(&app), want, "{seen:?}"); + } + let out = f.run(&mut app, vec![]); + let (_, value, text) = slider_node(&out, "Angle"); + assert_eq!((value, text.as_deref()), (Some(-179.0), Some("-179°"))); + f.key(&mut app, Tab, M::SHIFT); + f.key(&mut app, ArrowRight, M::NONE); + assert_eq!(angle(&app), -179.0, "the Roundness field has the focus"); + // Tab goes from the Roundness field to the scrub area on its label, then to the preview. + f.key(&mut app, Tab, M::NONE); + f.key(&mut app, Tab, M::NONE); + f.key(&mut app, ArrowRight, M::NONE); + assert_eq!(angle(&app), -178.0, "Tab comes back to the preview"); + f.drag(&mut app, center + egui::vec2(20.0, 0.0), egui::vec2(0.0, 20.0)); + assert_eq!(angle(&app), -45.0, "the drag ends down to the right"); +} + #[test] fn polar_grid_shared_canvas_click_defaults_units_counts_and_history() { use vectorcraft_doc::NodeId; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 87fa6ac84b..107350b749 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -35,7 +35,7 @@ pub use chips::{ProxyClicks, chip_button, chip_button_named, fill_stroke_proxy, pub(crate) use color::pointer_phase; pub use color::{ Live, SliderValue, WheelResponse, channel_slider, channel_slider_named, channel_slider_valued, color_field, color_mesh, color_slider, - color_slider_named, color_slider_stepped, color_slider_valued, harmony_wheel, hex_field, hex_field_named, region_texture, + color_slider_named, color_slider_stepped, color_slider_valued, harmony_wheel, hex_field, hex_field_named, region_texture, stepped_area, }; pub use drag::{PanelDrag, SwatchRows, art_drop, doc_preview, drag_source}; #[cfg(test)] diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index a73b6ae2bd..1433cbd4cc 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -135,6 +135,24 @@ pub fn color_slider_stepped( ) -> (Option<f32>, Live, Option<f64>) { let id = id_with(ui.scope_id(), id); let (resp, picked, phase) = color_rail(ui, id, name, shown.clone(), value, width, track); + let stepped = slider_keys(ui, &resp, shown); + (picked, phase, stepped.filter(|_| picked.is_none())) +} + +/// A control that its caller draws and reads the pointer on (`resp`, from a click-and-drag +/// [`Ui::interact`]), which screen readers get as a slider named `name` (already translated) with +/// `shown`, and which takes the focus, the keys and the screen readers' actions as the rail of +/// [`color_slider_stepped`] does, with the focus outline around `resp.rect`. Returns the number in +/// `shown`'s units that a key or an action gives. +pub fn stepped_area(ui: &Ui, resp: &Response, name: &str, shown: Option<SliderValue>) -> Option<f64> { + slider_info(ui, resp, name, shown.clone()); + slider_keys(ui, resp, shown) +} + +/// The focus, keys, actions and focus outline of [`color_slider_stepped`] on the control `resp`: +/// the number a key or an action gives. +fn slider_keys(ui: &Ui, resp: &Response, shown: Option<SliderValue>) -> Option<f64> { + let id = resp.id; // Focus a click or a drag gave shows no outline until a key steps the rail: the outline tells // a keyboard user where the focus is, and after a drag it only framed the rail. let by_pointer = id.with("focused-by-pointer"); @@ -161,7 +179,7 @@ pub fn color_slider_stepped( let t = Tokens::get(ui.ctx()); ui.painter().rect_stroke(resp.rect, 2.0, Stroke::new(1.0, t.accent), StrokeKind::Inside); } - (picked, phase, stepped.filter(|_| picked.is_none())) + stepped } /// The number of slider `id` (`s`) after this frame's keys while it is `focused`, and after screen diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0a699babf4..0699ef5bc6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -751,6 +751,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The planar map's edge-source grid stays linear in memory on any input: a segment is filed once per cell it crosses, and the grid holds at most a budget of cell references (a few dozen per item plus a few rows' worth), past which the remaining items go to a short scanned list and are still found, so thousands of coincident segments cannot make the index quadratic (`crates/pathops/src/planar.rs` test `rect_index_holds_a_bounded_number_of_references`). The Blob Brush Tool Options have Keep selected and Merge only with selection, both off by default: while Keep selected is off, the blob a stroke draws or merges into is not selected afterwards, and while Merge only with selection is on, a stroke merges only with selected blobs of its color that it touches (`path.blob` `keepSelected` and `mergeOnlySelection`). The Blob Brush Tool Options also have Angle and Roundness, as the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list them: Angle from −180° to 180° (0° by default) and Roundness from 0% to 100% (100%, a round tip, by default). The elliptical tip keeps its angle on the page along a stroke, a 0% tip is drawn 0.1% as wide as it is long, and the dialog shows the tip and three dabs of it. The values are kept with the tool's options (`path.blob` `angle` and `roundness`). Not done: the Random and pen-driven variations of Angle and Roundness. + The Blob Brush Tool Options' tip preview is the Angle slider for screen readers, with the Angle in degrees as its value: a click or a drag in it points the Angle at the pointer and gives it the keyboard focus, Tab reaches it after the Roundness field, and the arrow keys step the Angle by 1° (10° with Shift, Home and End to −180° and 180°). The Blob Brush Tool Options also have Fidelity, as the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list it: the Pencil's logarithmic slider from Accurate (0.01 pt) to Smooth (20 pt) and its field (up to 100 pt), 1.5 pt by default and kept with the tool's options. The brush follows the stroke fitted at the Fidelity, as a Pencil stroke is fitted: a low value follows the drag closely, jitter included, and a higher one gives smoother curves (`path.blob` `fidelity`). A Blob Brush stroke merges with the topmost path of its fill color and no stroke that it touches, and with the other such paths it touches in the same group or layer that are next to that path in stacking order with no other kind of object between them; matching paths in other groups or layers are left alone, as the Blob Brush tool guidelines in [Paint with fills and strokes](https://web.archive.org/web/20241219085603/https://helpx.adobe.com/illustrator/using/painting-fills-strokes.html) describe (`path.blob`). - **Ruler guides as layer objects:** a guide goes on the current layer, shows, hides, locks and is deleted with it, is listed in the Layers panel (its row selects it) and moves to another layer (`guide.setLayer`, or its row dragged onto that layer's rows); guides on a hidden or locked layer can't be selected, moved or deleted, Duplicate copies a layer's guides and Merge Selected and Flatten Artwork keep them on the merged layer; guides from files saved before guides had layers go on the top visible, unlocked layer when the document opens. Not done: guides stacked among the art of their layer (they are listed above it), a guide row's own eye and lock. Lock Guides also locks the objects made into guides: they can't be selected, moved or deleted (#1543); they are drawn in the guide colour and style of Preferences, and a dragged selection snaps to ruler guides with Smart Guides on (#1583, fixes #1534). The Transform panel shows a selected ruler guide's X or Y, and typing a value moves it (#1659, part of #1597). This is not established by the documentation we could find: the public help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) describe selecting and dragging unlocked guides and the panels' X and Y for a selection, not a guide's position in a panel, and the one public statement of it is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. It is kept as a convenience pending the owner's decision, with no parity claim and nothing counted towards a score. From 6fb9152fa7d66b829a1a93c920e50d09f41d0918 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 09:31:13 -0700 Subject: [PATCH 103/260] Blob Brush: the tip preview test checks that a drag gives it the focus The test moves the focus to the Roundness field before the drag and steps the Angle with an arrow key after it, so it fails if a drag stops giving the preview the keyboard focus. --- crates/ui-egui/src/dialogs/tests.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index ee870e4a8f..6c65ea6d23 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1903,7 +1903,8 @@ fn the_flattener_and_3d_sliders_step_with_the_arrow_keys() { /// The Blob Brush Tool Options' tip preview is the Angle slider for screen readers, with the Angle /// as its value. A click in it points the Angle at the pointer and gives it the focus, its arrow /// keys then step the Angle by one degree (ten with Shift) within -180° to 180°, Shift+Tab leaves -/// it for the Roundness field and Tab comes back to it, and a drag still sets the Angle. +/// it for the Roundness field and Tab comes back to it, and a drag still sets the Angle and gives +/// it the focus. #[test] fn the_blob_brush_tip_preview_is_a_named_slider_with_arrow_keys() { use egui::Key::{ArrowDown, ArrowLeft, ArrowRight, ArrowUp, End, Home, Tab}; @@ -1949,8 +1950,11 @@ fn the_blob_brush_tip_preview_is_a_named_slider_with_arrow_keys() { f.key(&mut app, Tab, M::NONE); f.key(&mut app, ArrowRight, M::NONE); assert_eq!(angle(&app), -178.0, "Tab comes back to the preview"); + f.key(&mut app, Tab, M::SHIFT); f.drag(&mut app, center + egui::vec2(20.0, 0.0), egui::vec2(0.0, 20.0)); assert_eq!(angle(&app), -45.0, "the drag ends down to the right"); + f.key(&mut app, ArrowRight, M::NONE); + assert_eq!(angle(&app), -44.0, "the drag gives the preview the focus"); } #[test] From 6eea3a5178c069d31878399f117dab7f42ffb6ab Mon Sep 17 00:00:00 2001 From: Wadah Badawi <350738630+WadahBadawi@users.noreply.github.com> Date: Sat, 31 Oct 2026 23:30:05 +0700 Subject: [PATCH 104/260] Pathfinder: Crop works on a selected group of shapes --- contributors/people.toml | 4 ++++ crates/engine/src/cmd/pathops.rs | 6 +++--- crates/engine/src/tests/pathops.rs | 15 +++++++++++++++ 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/contributors/people.toml b/contributors/people.toml index 55b5b38609..f3c8629b71 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -185,3 +185,7 @@ sync_github_name = true display_name = "Arshiya" real_name = "Arshiya Rahgozar" sync_github_name = false + +[people.WadahBadawi] +display_name = "Wadah Badawi" +sync_github_name = true diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 66c01f4c55..f002dd7ba7 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -15,8 +15,8 @@ use vectorcraft_pathops::{BoolOp, PathfinderOp}; use super::edit::selected_roots; use super::{ - CommandSpec, EngineError, Result, Session, always, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_multi, has_selection, number_or, - str_param, switch_or, + CommandSpec, EngineError, Result, Session, always, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selection, number_or, str_param, + switch_or, }; pub fn specs() -> Vec<CommandSpec> { @@ -90,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> { ["Window", "Pathfinder"], None, "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", - has_multi, + has_selection, |s, p| run_pf(s, p, PathfinderOp::Crop) ), cmd!( diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 8b93c4e89a..2eaeeb594c 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1293,3 +1293,18 @@ fn pathfinder_journal_entries_replay_with_the_options_they_used() { // Options given as params are checked as object.pathfinder.options checks them. assert!(s.execute("object.pathfinder.divide", &json!({"precision": 20})).is_err()); } + +/// A single group containing multiple overlapping paths is accepted by Crop. +#[test] +fn crop_operates_on_a_single_selected_group_of_paths() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 50.0, 50.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + assert_eq!(s.doc().unwrap().selection.len(), 1); + let out = s.execute("object.pathfinder.crop", &json!({})).unwrap(); + let cropped_ids = ids(&out); + assert!(!cropped_ids.is_empty()); +} From c35b51eb0f8ee99fcb864ca400f377a9e0f332fc Mon Sep 17 00:00:00 2001 From: Wadah Badawi <350738630+WadahBadawi@users.noreply.github.com> Date: Sat, 31 Oct 2026 23:30:06 +0700 Subject: [PATCH 105/260] Intertwine: object.intertwine.arrange takes an id without a selection --- crates/engine/src/cmd/intertwine.rs | 4 ++-- crates/engine/src/tests/intertwine.rs | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/intertwine.rs b/crates/engine/src/cmd/intertwine.rs index 41e4a467d4..27f1080e1f 100644 --- a/crates/engine/src/cmd/intertwine.rs +++ b/crates/engine/src/cmd/intertwine.rs @@ -26,7 +26,7 @@ use vectorcraft_tools::intertwine::{Face, drawn_order, face_at, faces, faces_in, use super::edit::selected_roots; use super::pathops::Beside; -use super::{CommandSpec, EngineError, Result, Session, bad, checked_id, checked_ids_param, cmd, has_selection, point_param, str_param}; +use super::{CommandSpec, EngineError, Result, Session, bad, checked_id, checked_ids_param, cmd, has_doc, has_selection, point_param, str_param}; pub fn specs() -> Vec<CommandSpec> { vec![ @@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> { [], None, "{id?: Intertwine group (default: the selected one), at?: [x,y] (the overlap area under this point, as a click picks it) | area?: [[x,y]…] (a closed polygon drawn around overlap areas: every area whose inside it encloses), order?: toggle|front|back (toggle: the object drawn right below the top comes to the front, so two objects swap), member?: id (front and back: the object to move; default: front brings the object right below the top, back sends the top one)} → {count: areas changed, top: [id of the object now on top in each area]}", - has_intertwine, + has_doc, arrange ), ] diff --git a/crates/engine/src/tests/intertwine.rs b/crates/engine/src/tests/intertwine.rs index 02a279447f..bdd3455f7f 100644 --- a/crates/engine/src/tests/intertwine.rs +++ b/crates/engine/src/tests/intertwine.rs @@ -329,3 +329,13 @@ fn edit_chooses_the_tool_for_the_group_of_a_selected_member() { assert_eq!(s.tool_id(), "intertwine"); assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [g]); } + +#[test] +fn arrange_with_explicit_id_works_without_active_selection() { + let mut s = session(); + let (g, _, _) = intertwined(&mut s); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.doc().unwrap().selection.is_empty()); + let out = s.execute("object.intertwine.arrange", &json!({"id": g.0, "at": [50.0, 30.0]})).unwrap(); + assert_eq!(out["count"], 1); +} From 33ab5adbc2102ed46063fa6a23013bf27bcd195e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 18:09:45 -0700 Subject: [PATCH 106/260] PDF/EPS export: flatten see-through and colorized pattern tile images PDF 1.3, PDF/X-1a, PDF/X-3, EPS and PostScript printing flatten transparency with `flatten_document`, which only looked at art in the layers. An image with see-through pixels, a colorize paint, opacity or a blending mode drawn only through a pattern fill stayed in the pattern definition, so the flattener returned early and the writer drew the tile opaque and uncolorized (PDF 1.3 export failed on the transparency left). `flatten_document` now first expands pattern fills whose tile image needs flattening into their tiles, as legacy .ai save does. See-through tile pixels count only where the caller counts see-through images (PDF 1.3); EPS level 3 already masks them out. The EPS and PostScript print transparency warnings now see those tile images too. --- crates/engine/src/cmd/expand.rs | 30 +++++--- crates/engine/src/cmd/fileio/eps.rs | 12 ++-- crates/engine/src/cmd/fileio/pdf.rs | 6 +- crates/engine/src/cmd/flatten.rs | 2 +- crates/engine/src/cmd/flatten/apply.rs | 28 +++++++- crates/engine/src/cmd/print.rs | 10 ++- crates/engine/src/tests/legacy_ai.rs | 97 ++++++++++++++++++++++++++ 7 files changed, 164 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 5ad8054fae..e536d0374a 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -456,18 +456,32 @@ pub(crate) fn expand_transparent_image_patterns(d: &mut Document, root: NodeId, if !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { return None; } - let shape = d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(blended); - let transparent = |d: &Document, i: &AppearanceItem| { - pattern_fill(d, i).is_some_and(|(f, def, _)| { - let on = shape || f.opacity < 1.0 || f.blend != BlendMode::Normal; - def.art.iter().any(|a| transparent_image(a, see_through, on)) - }) - }; - expand_patterns_where(d, l, transparent) + expand_patterns_where(d, l, |d, i| transparent_pattern_fill(d, l, i, see_through)) })?; Ok(n) } +/// Whether a path or compound path of `d` has a pattern fill that +/// [`expand_transparent_image_patterns`] would expand with `see_through`. +pub(crate) fn has_transparent_image_patterns(d: &Document, see_through: &BTreeSet<String>) -> bool { + let mut found = false; + d.walk(|n| { + if !found && matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) { + found = n.appearance.items.iter().any(|i| transparent_pattern_fill(d, n, i, see_through)); + } + }); + found +} + +/// Whether `i`, an item of leaf `l`, is a pattern fill whose tile art holds a transparent image +/// ([`transparent_image`]), counting the fill's and the shape's opacity and blending mode. +fn transparent_pattern_fill(d: &Document, l: &Node, i: &AppearanceItem, see_through: &BTreeSet<String>) -> bool { + let Some((f, def, _)) = pattern_fill(d, i) else { return false }; + let shape = d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(blended); + let on = shape || f.opacity < 1.0 || f.blend != BlendMode::Normal; + def.art.iter().any(|a| transparent_image(a, see_through, on)) +} + /// Whether `n` has opacity or a blending mode of its own. fn blended(n: &Node) -> bool { n.opacity < 1.0 || n.blend != BlendMode::Normal diff --git a/crates/engine/src/cmd/fileio/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index a05cc08248..a999b31ce3 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -12,7 +12,7 @@ use vectorcraft_doc::Document; use vectorcraft_eps::{EpsOptions, Level, Overprint, Preview, Raster}; use vectorcraft_geom::{Point, Rect}; -use super::super::flatten::{FlattenOptions, flatten_document}; +use super::super::flatten::{FlattenOptions, expand_transparent_tile_images, flatten_document}; use super::super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param}; use super::{ArtboardPick, Encoded, FormatOption}; @@ -299,11 +299,13 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> { return Err(bad(C, "the document has no artboard")); } let regions: Vec<Rect> = pages.iter().map(|(_, region, _)| *region).collect(); - let transparent = doc.layers.iter().any(|l| l.shows_transparency()); - let flat = flatten_document(doc, &set.flatten)?; - let drawn = flat.as_ref().unwrap_or(doc); + let expanded = expand_transparent_tile_images(doc, &set.flatten)?; + let source = expanded.as_ref().unwrap_or(doc); + let transparent = source.layers.iter().any(|l| l.shows_transparency()); + let flat = flatten_document(source, &set.flatten)?; + let drawn = flat.as_ref().unwrap_or(source); let mut enc = Encoded { warnings, joiner: Some("_"), ..Encoded::default() }; - if transparent && flat.is_some() { + if transparent && (flat.is_some() || expanded.is_some()) { enc.warnings.push("transparency is flattened into opaque art and images (EPS has none): see the flattener preset".into()); } let preview_limit = if saving { SAVE_PREVIEW } else { MAX_PREVIEW }; diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index dfa7d1cfa7..213a442cf6 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -317,9 +317,9 @@ pub const DEFAULT_FLATTENER: &str = "High Resolution"; /// `doc` with its transparency flattened for a PDF 1.3 file (asked for, or PDF/X-1a and PDF/X-3, /// whose files have none), with `flattenerPreset` (default High Resolution) and `p`'s `flattener` -/// options over it; images with see-through pixels and colorized images count as transparency, -/// rasterized areas are clipped to their regions, and discarded overprints are dropped. `None` -/// when nothing changes (or the file keeps transparency). +/// options over it; images with see-through pixels and colorized images, including those in +/// pattern tiles, count as transparency. Rasterized areas are clipped to their regions, and +/// discarded overprints are dropped. `None` when nothing changes (or the file keeps transparency). fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<Option<Document>> { if !set.pdf13() { return Ok(None); diff --git a/crates/engine/src/cmd/flatten.rs b/crates/engine/src/cmd/flatten.rs index 47a190a430..94e05a3572 100644 --- a/crates/engine/src/cmd/flatten.rs +++ b/crates/engine/src/cmd/flatten.rs @@ -49,7 +49,7 @@ mod presets; mod report; pub(crate) use analysis::{outlined_text, see_through_images}; -pub(crate) use apply::flatten_document; +pub(crate) use apply::{expand_transparent_tile_images, flatten_document}; pub use commands::specs; pub use options::FlattenOptions; pub use presets::{FlattenerPreset, PRESET_EXTS, PRESET_FORMAT}; diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index 884351dea6..463323029f 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -292,13 +292,35 @@ pub(super) fn opaque(n: &mut Node) { } } +/// Expand pattern fills whose image tiles need transparency flattening. +pub(crate) fn expand_transparent_tile_images(doc: &Document, o: &FlattenOptions) -> Result<Option<Document>> { + if doc.patterns.is_empty() { + return Ok(None); + } + let keys = o.no_transparency.clone().unwrap_or_default(); + if !crate::cmd::expand::has_transparent_image_patterns(doc, &keys) { + return Ok(None); + } + let mut d = doc.clone(); + let layers: Vec<NodeId> = d.layers.iter().map(|l| l.id).collect(); + let mut changed = 0; + for id in layers { + changed += crate::cmd::expand::expand_transparent_image_patterns(&mut d, id, &keys)?; + } + Ok((changed > 0).then_some(d)) +} + /// `doc` with everything it draws flattened with `o`, as formats without transparency (EPS) /// write it: every visible object of the visible layers, locked ones too (a clipping layer's -/// clipping path stays). `None` when that changes nothing. +/// clipping path stays). Pattern tile images with opacity, blending or colorize are expanded; +/// see-through tile pixels are expanded when `o.no_transparency` counts them. `None` when nothing +/// changes. pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result<Option<Document>> { + let expanded = expand_transparent_tile_images(doc, o)?; + let doc = expanded.as_ref().unwrap_or(doc); let outlining = o.text_to_outlines || o.strokes_to_outlines || !o.preserve_overprints; if !outlining && !doc.layers.iter().any(|l| l.shows_transparency() || o.draws_see_through_image(l)) { - return Ok(None); + return Ok(expanded); } let mut roots = vec![]; for l in doc.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })) { @@ -307,7 +329,7 @@ pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result<Opt } let plan = plan(doc, &roots, o, true)?; if plan.flat.is_empty() && !plan.kept.iter().any(|id| doc.node(*id).is_some_and(|n| kept_work(n, o))) { - return Ok(None); + return Ok(expanded); } let mut d = doc.clone(); apply(&mut d, &mut vectorcraft_doc::Selection::default(), plan, o)?; diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 0face3aa8c..be6e9e67c2 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -11,6 +11,7 @@ use vectorcraft_pdf::{PrintLayers, PrintOptions, PrintPreview, PrintSettings}; use super::fileio::pdf::{merge, pdf_error}; use super::fileio::{extension, write_or_return}; +use super::flatten::expand_transparent_tile_images; use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param}; const SETUP: &str = "print.setup"; @@ -179,6 +180,14 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> { // Raster effects print as images at the document's raster effects resolution. let flat = super::rasterfx::flatten_raster_effects(doc); let doc = flat.as_ref().unwrap_or(doc); + let bitmap = set.advanced.print_as_bitmap && set.output.mode == vectorcraft_pdf::OutputMode::Composite; + let expanded = if postscript && !bitmap { + let options = super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?; + options.as_ref().map(|o| expand_transparent_tile_images(doc, o)).transpose()?.flatten() + } else { + None + }; + let doc = expanded.as_ref().unwrap_or(doc); // Print as Bitmap and the flattener preset (Advanced) render and flatten it first. let prepared = super::printadvanced::prepare(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich")?; let path = str_param(p, "path"); @@ -201,7 +210,6 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> { None => Level::default(), }; let mut warnings = vec![]; - let bitmap = set.advanced.print_as_bitmap && set.output.mode == vectorcraft_pdf::OutputMode::Composite; if !bitmap && doc.layers.iter().any(|l| l.shows_transparency()) { warnings.push("transparency is flattened into opaque art and images (PostScript has none): see flattenerPreset".to_string()); } diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index 7ac5c3c5c9..793fe19d2a 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -704,3 +704,100 @@ fn only_the_transparent_pattern_fill_of_a_leaf_is_expanded() { assert_eq!(patterns.len(), 1, "{patterns:?}"); assert!(images > 0); } + +#[test] +fn pdf13_flattens_see_through_pattern_tile_images() { + let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0); + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + let r = s.execute("document.exportPdf", &json!({"compatibility": "1.3"})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let page = vectorcraft_pdf::import(&bytes).unwrap(); + let after = [colour_at(&page, 72.0, 72.0), colour_at(&page, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } +} + +#[test] +fn pdf13_flattens_colorized_pattern_tile_images() { + let mut s = colorized_pattern_over_blue(); + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + let r = s.execute("document.exportPdf", &json!({"compatibility": "1.3"})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let page = vectorcraft_pdf::import(&bytes).unwrap(); + let after = [colour_at(&page, 72.0, 72.0), colour_at(&page, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } +} + +#[test] +fn eps_level3_writes_see_through_pattern_tile_images() { + let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0); + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + let r = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3})).unwrap(); + s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap(); + let page = &s.doc().unwrap().doc; + let after = [colour_at(page, 72.0, 72.0), colour_at(page, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } +} + +#[test] +fn eps_flattens_colorized_pattern_tile_images_and_warns() { + let mut s = colorized_pattern_over_blue(); + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + let r = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3})).unwrap(); + assert!(warnings(&r).iter().any(|w| w.contains("transparency is flattened")), "{:?}", warnings(&r)); + s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap(); + let after = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } +} + +#[test] +fn eps_warns_for_colorized_image_nested_in_pattern_tile_group() { + let mut s = colorized_pattern_over_blue(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let id = d.alloc_id(); + let art = std::mem::take(&mut d.patterns[0].art); + d.patterns[0].art.push(std::sync::Arc::new(vectorcraft_doc::Node::group(id, art))); + let r = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3})).unwrap(); + assert!(warnings(&r).iter().any(|w| w.contains("transparency is flattened")), "{:?}", warnings(&r)); +} + +#[test] +fn postscript_print_warns_for_colorized_pattern_tile_image() { + let mut s = colorized_pattern_over_blue(); + let r = s.execute("file.print", &json!({"format": "postscript"})).unwrap(); + assert!(warnings(&r).iter().any(|w| w.contains("transparency is flattened")), "{:?}", warnings(&r)); +} + +#[test] +fn eps_pattern_does_not_flatten_a_separate_see_through_image() { + let mut output = vec![]; + for tile in [checker([0, 200, 0, 255], [255, 230, 0, 255]), checker([0, 200, 0, 255], [255, 255, 255, 0])] { + let mut s = pattern_over_blue(&tile, 1.0); + s.execute("shape.rectangle", &json!({"x": 8, "y": 8, "width": 24, "height": 24})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let p = json!({"name": "i.png", "dataBase64": vectorcraft_format::base64_encode(&png(20, 20, [0, 0, 0, 128])), "at": [20, 20]}); + s.execute("file.place", &p).unwrap(); + let r = + s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3, "flattenerPreset": "high"})).unwrap(); + let image_warning = warnings(&r).iter().any(|w| w.contains("partly transparent")); + s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap(); + output.push((colour_at(&s.doc().unwrap().doc, 20.0, 20.0), image_warning)); + } + assert_eq!(output[0], output[1], "EPS layer image changed when a see-through pattern tile was present: {output:?}"); +} + +#[test] +fn opaque_pattern_tile_images_do_not_change_during_export_flattening() { + let s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 230, 0, 255]), 1.0); + let d = &s.doc().unwrap().doc; + assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_none()); + let o = crate::cmd::FlattenOptions { no_transparency: Some(crate::cmd::flatten::see_through_images(d)), ..Default::default() }; + assert!(crate::cmd::flatten::flatten_document(d, &o).unwrap().is_none()); +} From 7b4d6282f12f1b95c653d058a92bed1dbf699447 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 21:26:34 -0700 Subject: [PATCH 107/260] Flattening: an option leaves colorized images to writers that draw them Flattening counted every colorized image as transparency, in the art and in pattern tiles. A new flattener option, keeps_colorize, stops counting an image colorized with a solid paint whose pixels are grayscale or 1-bit, for a format whose writer draws such images in their ink. Opacity, blending modes, opacity masks and effects still flatten them, and pattern tiles are still expanded for those. The option is off, so exports flatten as before; the EPS writer that draws colorized images turns it on. The EPS pattern tile tests now check the exported colors, and a tile group with opacity for the warning. --- crates/doc/src/node/ops.rs | 10 ++++-- crates/engine/src/cmd/expand.rs | 38 +++++++++++++++-------- crates/engine/src/cmd/fileio/eps.rs | 2 +- crates/engine/src/cmd/fileio/legacy_ai.rs | 2 +- crates/engine/src/cmd/flatten/apply.rs | 15 ++++----- crates/engine/src/cmd/flatten/options.rs | 22 ++++++++++++- crates/engine/src/tests/legacy_ai.rs | 28 +++++++++++++---- 7 files changed, 86 insertions(+), 31 deletions(-) diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index fcf2c9429d..edab5f73c9 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -686,6 +686,12 @@ impl Node { /// stroke opacity below 100%, a blend mode, an opacity mask, effects, transparent gradient /// stops or a colorized image. Hidden objects show none. pub fn shows_transparency(&self) -> bool { + self.shows_transparency_with(&|_| true) + } + + /// [`Self::shows_transparency`], counting a colorized image by itself only when `colorize` + /// accepts it, for files that write some colorized images in their colorize paint (EPS). + pub fn shows_transparency_with(&self, colorize: &dyn Fn(&Node) -> bool) -> bool { use vectorcraft_color::Paint; let see_through = |p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity < 1.0)); let effects = |fx: &[crate::Effect]| fx.iter().any(|e| e.visible); @@ -693,14 +699,14 @@ impl Node { && (self.opacity < 1.0 || self.blend != BlendMode::Normal || self.extras().mask.as_ref().is_some_and(|m| !m.disabled) - || (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some()) + || (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some() && colorize(self)) || effects(&self.appearance.effects) || self .appearance .items .iter() .any(|i| i.visible() && (i.opacity() < 1.0 || i.blend() != BlendMode::Normal || see_through(i.paint()) || effects(i.effects()))) - || self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency()))) + || self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency_with(colorize)))) } } diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index e536d0374a..cf61a305b2 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -447,27 +447,32 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> { /// Expand the pattern fills under `root` that paint a transparent or colorized image into the tiles they paint /// ([`expand_patterns_where`]), so each tile image becomes an object of its own; the other /// pattern fills stay. A tile image counts when its key is in `see_through` (it has see-through -/// pixels), when it has a colorize paint, or when it, a group +/// pixels), when it has a colorize paint that `colorize` counts, or when it, a group /// in the tile art, the fill, the shape or a group the shape is in has opacity or a blending /// mode. Returns how many shapes changed. -pub(crate) fn expand_transparent_image_patterns(d: &mut Document, root: NodeId, see_through: &BTreeSet<String>) -> Result<usize> { +pub(crate) fn expand_transparent_image_patterns( + d: &mut Document, + root: NodeId, + see_through: &BTreeSet<String>, + colorize: &dyn Fn(&Document, &Node) -> bool, +) -> Result<usize> { let (_, n) = replace_leaves(d, root, |d, l| { // Most leaves have no pattern fill: skip the ancestry walk for them. if !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { return None; } - expand_patterns_where(d, l, |d, i| transparent_pattern_fill(d, l, i, see_through)) + expand_patterns_where(d, l, |d, i| transparent_pattern_fill(d, l, i, see_through, colorize)) })?; Ok(n) } /// Whether a path or compound path of `d` has a pattern fill that -/// [`expand_transparent_image_patterns`] would expand with `see_through`. -pub(crate) fn has_transparent_image_patterns(d: &Document, see_through: &BTreeSet<String>) -> bool { +/// [`expand_transparent_image_patterns`] would expand with `see_through` and `colorize`. +pub(crate) fn has_transparent_image_patterns(d: &Document, see_through: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool) -> bool { let mut found = false; d.walk(|n| { if !found && matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) { - found = n.appearance.items.iter().any(|i| transparent_pattern_fill(d, n, i, see_through)); + found = n.appearance.items.iter().any(|i| transparent_pattern_fill(d, n, i, see_through, colorize)); } }); found @@ -475,11 +480,17 @@ pub(crate) fn has_transparent_image_patterns(d: &Document, see_through: &BTreeSe /// Whether `i`, an item of leaf `l`, is a pattern fill whose tile art holds a transparent image /// ([`transparent_image`]), counting the fill's and the shape's opacity and blending mode. -fn transparent_pattern_fill(d: &Document, l: &Node, i: &AppearanceItem, see_through: &BTreeSet<String>) -> bool { +fn transparent_pattern_fill( + d: &Document, + l: &Node, + i: &AppearanceItem, + see_through: &BTreeSet<String>, + colorize: &dyn Fn(&Document, &Node) -> bool, +) -> bool { let Some((f, def, _)) = pattern_fill(d, i) else { return false }; let shape = d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(blended); let on = shape || f.opacity < 1.0 || f.blend != BlendMode::Normal; - def.art.iter().any(|a| transparent_image(a, see_through, on)) + def.art.iter().any(|a| transparent_image(d, a, see_through, colorize, on)) } /// Whether `n` has opacity or a blending mode of its own. @@ -487,13 +498,14 @@ fn blended(n: &Node) -> bool { n.opacity < 1.0 || n.blend != BlendMode::Normal } -/// Whether `n` is or holds an image with see-through pixels (key in `keys`), a colorize paint, -/// opacity or a blending mode of its own or of a group in `n`, or anywhere when `on`. -fn transparent_image(n: &Node, keys: &BTreeSet<String>, on: bool) -> bool { +/// Whether `n` (art of `d`) is or holds an image with see-through pixels (key in `keys`), a +/// colorize paint that `colorize` counts, opacity or a blending mode of its own or of a group in +/// `n`, or anywhere when `on`. +fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool, on: bool) -> bool { let on = on || blended(n); match &n.kind { - NodeKind::Image(im) => on || keys.contains(&im.key) || n.extras().colorize.is_some(), - _ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(c, keys, on))), + NodeKind::Image(im) => on || keys.contains(&im.key) || (n.extras().colorize.is_some() && colorize(d, n)), + _ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(d, c, keys, colorize, on))), } } diff --git a/crates/engine/src/cmd/fileio/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index a999b31ce3..2c8ae4a845 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -301,7 +301,7 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> { let regions: Vec<Rect> = pages.iter().map(|(_, region, _)| *region).collect(); let expanded = expand_transparent_tile_images(doc, &set.flatten)?; let source = expanded.as_ref().unwrap_or(doc); - let transparent = source.layers.iter().any(|l| l.shows_transparency()); + let transparent = source.layers.iter().any(|l| set.flatten.shows_transparency(source, l)); let flat = flatten_document(source, &set.flatten)?; let drawn = flat.as_ref().unwrap_or(source); let mut enc = Encoded { warnings, joiner: Some("_"), ..Encoded::default() }; diff --git a/crates/engine/src/cmd/fileio/legacy_ai.rs b/crates/engine/src/cmd/fileio/legacy_ai.rs index 0e53a5a18f..7cbbda2fed 100644 --- a/crates/engine/src/cmd/fileio/legacy_ai.rs +++ b/crates/engine/src/cmd/fileio/legacy_ai.rs @@ -167,7 +167,7 @@ fn expand_image_patterns(d: &mut Document) -> Result<()> { let keys = super::super::flatten::see_through_images(d); let layers: Vec<NodeId> = d.layers.iter().map(|l| l.id).collect(); for id in layers { - super::super::expand::expand_transparent_image_patterns(d, id, &keys)?; + super::super::expand::expand_transparent_image_patterns(d, id, &keys, &|_, _| true)?; } Ok(()) } diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index 463323029f..7fbe44a0d1 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -74,7 +74,7 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: let mut sc = Scratch { brushes: vectorcraft_brush::library(&baked), doc: baked.clone() }; let plain: Vec<Node> = art.iter().map(|n| sc.plain(n)).collect(); let reaches: Vec<Option<Rect>> = plain.iter().map(reach).collect(); - let see_through: Vec<bool> = plain.iter().map(|n| n.shows_transparency() || o.draws_see_through_image(n)).collect(); + let see_through: Vec<bool> = plain.iter().map(|n| o.shows_transparency(&baked, n) || o.draws_see_through_image(n)).collect(); let cmyk = src.color_mode == ColorMode::Cmyk; let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() }; // Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing). @@ -298,28 +298,29 @@ pub(crate) fn expand_transparent_tile_images(doc: &Document, o: &FlattenOptions) return Ok(None); } let keys = o.no_transparency.clone().unwrap_or_default(); - if !crate::cmd::expand::has_transparent_image_patterns(doc, &keys) { + let colorize = |d: &Document, n: &Node| o.counts_colorize(d, n); + if !crate::cmd::expand::has_transparent_image_patterns(doc, &keys, &colorize) { return Ok(None); } let mut d = doc.clone(); let layers: Vec<NodeId> = d.layers.iter().map(|l| l.id).collect(); let mut changed = 0; for id in layers { - changed += crate::cmd::expand::expand_transparent_image_patterns(&mut d, id, &keys)?; + changed += crate::cmd::expand::expand_transparent_image_patterns(&mut d, id, &keys, &colorize)?; } Ok((changed > 0).then_some(d)) } /// `doc` with everything it draws flattened with `o`, as formats without transparency (EPS) /// write it: every visible object of the visible layers, locked ones too (a clipping layer's -/// clipping path stays). Pattern tile images with opacity, blending or colorize are expanded; -/// see-through tile pixels are expanded when `o.no_transparency` counts them. `None` when nothing -/// changes. +/// clipping path stays). Pattern tile images with opacity, blending or a colorize paint that +/// `o` counts ([`FlattenOptions::counts_colorize`]) are expanded; see-through tile pixels are +/// expanded when `o.no_transparency` counts them. `None` when nothing changes. pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result<Option<Document>> { let expanded = expand_transparent_tile_images(doc, o)?; let doc = expanded.as_ref().unwrap_or(doc); let outlining = o.text_to_outlines || o.strokes_to_outlines || !o.preserve_overprints; - if !outlining && !doc.layers.iter().any(|l| l.shows_transparency() || o.draws_see_through_image(l)) { + if !outlining && !doc.layers.iter().any(|l| o.shows_transparency(doc, l) || o.draws_see_through_image(l)) { return Ok(expanded); } let mut roots = vec![]; diff --git a/crates/engine/src/cmd/flatten/options.rs b/crates/engine/src/cmd/flatten/options.rs index 57331660ab..d4f18f3857 100644 --- a/crates/engine/src/cmd/flatten/options.rs +++ b/crates/engine/src/cmd/flatten/options.rs @@ -2,7 +2,7 @@ use super::analysis::draws_image; use super::apply::{apply, kept_work, plan}; use super::presets::{FlattenerPreset, saved_preset}; use super::report::target_roots; -use super::{BTreeSet, Deserialize, EngineError, Node, Result, Serialize, Session, Value, bad, json, str_param}; +use super::{BTreeSet, Deserialize, Document, EngineError, Node, NodeKind, Paint, Result, Serialize, Session, Value, bad, json, str_param}; /// Object → Flatten Transparency settings: a preset's, adjusted by the command's params. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -34,6 +34,10 @@ pub struct FlattenOptions { /// amounts). `None` for ordinary flattening. Not a preset option. #[serde(skip)] pub no_transparency: Option<BTreeSet<String>>, + /// The file writes a colorized image in its colorize paint (EPS), so a colorize paint by + /// itself doesn't count as transparency. Not a preset option. + #[serde(skip)] + pub keeps_colorize: bool, } impl Default for FlattenOptions { @@ -81,6 +85,7 @@ impl FlattenOptions { preserve_alpha: false, preserve_overprints: true, no_transparency: None, + keeps_colorize: false, } } @@ -138,6 +143,21 @@ impl FlattenOptions { Ok(o) } + /// Whether `n`, art of `d`, shows transparency these options flatten + /// ([`Node::shows_transparency`], colorized images as [`Self::counts_colorize`] says). + pub(crate) fn shows_transparency(&self, d: &Document, n: &Node) -> bool { + n.shows_transparency_with(&|c| self.counts_colorize(d, c)) + } + + /// Whether colorized image `n`, art of `d`, counts as transparency by itself. With + /// [`Self::keeps_colorize`], an image colorized with a solid paint whose pixels are grayscale + /// or 1-bit doesn't: the EPS writer draws it in that paint. + pub(crate) fn counts_colorize(&self, d: &Document, n: &Node) -> bool { + let NodeKind::Image(im) = &n.kind else { return true }; + let solid = matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. })); + !self.keeps_colorize || !solid || d.image_blob(im).is_some_and(|b| b.gray_source().is_none()) + } + /// `n` shows an image whose see-through pixels count as transparency. pub(super) fn draws_see_through_image(&self, n: &Node) -> bool { self.no_transparency.as_ref().is_some_and(|keys| draws_image(n, keys)) diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index 793fe19d2a..0a3f9af6f4 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -546,7 +546,7 @@ fn a_colorized_grayscale_image_pattern_fill_is_expanded() { let keys = crate::cmd::flatten::see_through_images(d); assert!(keys.is_empty()); let layer = d.layers[0].id; - assert_eq!(crate::cmd::expand::expand_transparent_image_patterns(d, layer, &keys).unwrap(), 1); + assert_eq!(crate::cmd::expand::expand_transparent_image_patterns(d, layer, &keys, &|_, _| true).unwrap(), 1); let mut patterns = 0; let mut tile_images = 0; d.walk(|n| { @@ -688,7 +688,7 @@ fn only_the_transparent_pattern_fill_of_a_leaf_is_expanded() { let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); let keys = crate::cmd::flatten::see_through_images(d); let layer = d.layers[0].id; - assert_eq!(crate::cmd::expand::expand_transparent_image_patterns(d, layer, &keys).unwrap(), 1); + assert_eq!(crate::cmd::expand::expand_transparent_image_patterns(d, layer, &keys, &|_, _| true).unwrap(), 1); let mut patterns = vec![]; let mut images = 0; d.walk(|n| { @@ -745,11 +745,10 @@ fn eps_level3_writes_see_through_pattern_tile_images() { } #[test] -fn eps_flattens_colorized_pattern_tile_images_and_warns() { +fn eps_writes_colorized_pattern_tile_images_in_their_colors() { let mut s = colorized_pattern_over_blue(); let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; let r = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3})).unwrap(); - assert!(warnings(&r).iter().any(|w| w.contains("transparency is flattened")), "{:?}", warnings(&r)); s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap(); let after = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; for (a, b) in before.iter().zip(after) { @@ -758,14 +757,31 @@ fn eps_flattens_colorized_pattern_tile_images_and_warns() { } #[test] -fn eps_warns_for_colorized_image_nested_in_pattern_tile_group() { +fn flattening_that_keeps_colorize_leaves_colorized_pattern_tile_images_alone() { + let s = colorized_pattern_over_blue(); + let d = &s.doc().unwrap().doc; + assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_some()); + let o = crate::cmd::FlattenOptions { keeps_colorize: true, ..Default::default() }; + assert!(crate::cmd::flatten::flatten_document(d, &o).unwrap().is_none(), "the pattern isn't expanded for a colorize paint alone"); +} + +#[test] +fn eps_flattens_colorized_image_in_a_see_through_pattern_tile_group_and_warns() { let mut s = colorized_pattern_over_blue(); let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); let id = d.alloc_id(); let art = std::mem::take(&mut d.patterns[0].art); - d.patterns[0].art.push(std::sync::Arc::new(vectorcraft_doc::Node::group(id, art))); + let mut group = vectorcraft_doc::Node::group(id, art); + group.opacity = 0.5; + d.patterns[0].art.push(std::sync::Arc::new(group)); + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; let r = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3})).unwrap(); assert!(warnings(&r).iter().any(|w| w.contains("transparency is flattened")), "{:?}", warnings(&r)); + s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap(); + let after = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } } #[test] From 6dfda4db7677b91cb7818a78cae5011795a748b8 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 22:44:47 -0700 Subject: [PATCH 108/260] PDF/EPS export: pattern tile images in live art and hidden shapes flatten as drawn Blends, envelopes, repeats and Intertwine groups that hold a see-through or colorized pattern tile image are expanded into the art the writers draw for them before the tiles are expanded, so those tiles are flattened too. Random Transform effects in that art are baked first. Hidden shapes, shapes in hidden groups or layers and template layers are skipped: expanding a hidden shape made its tiles show in the file, and art that is not written no longer makes a flattened copy of the document. --- crates/engine/src/cmd/expand.rs | 94 +++++++++++++++++++++++--- crates/engine/src/cmd/flatten/apply.rs | 3 +- crates/engine/src/tests/legacy_ai.rs | 60 ++++++++++++++++ 3 files changed, 146 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index cf61a305b2..b3bfab9c6e 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -449,33 +449,107 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> { /// pattern fills stay. A tile image counts when its key is in `see_through` (it has see-through /// pixels), when it has a colorize paint that `colorize` counts, or when it, a group /// in the tile art, the fill, the shape or a group the shape is in has opacity or a blending -/// mode. Returns how many shapes changed. +/// mode. Blends, envelopes, repeats and Intertwine groups that hold such a fill are expanded +/// first ([`expand_live_with_transparent_image_patterns`]). Hidden shapes and shapes in hidden +/// groups or layers and in template layers stay as they are. Returns how many objects changed. pub(crate) fn expand_transparent_image_patterns( d: &mut Document, root: NodeId, see_through: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool, ) -> Result<usize> { + let live = expand_live_with_transparent_image_patterns(d, root, see_through, colorize)?; let (_, n) = replace_leaves(d, root, |d, l| { // Most leaves have no pattern fill: skip the ancestry walk for them. if !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { return None; } + // The expanded art would be shown. + if !d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).all(drawn) { + return None; + } expand_patterns_where(d, l, |d, i| transparent_pattern_fill(d, l, i, see_through, colorize)) })?; - Ok(n) + Ok(live + n) } -/// Whether a path or compound path of `d` has a pattern fill that -/// [`expand_transparent_image_patterns`] would expand with `see_through` and `colorize`. +/// Whether a layer of `d` holds a pattern fill that [`expand_transparent_image_patterns`] would +/// expand with `see_through` and `colorize` ([`holds_transparent_image_patterns`]). pub(crate) fn has_transparent_image_patterns(d: &Document, see_through: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool) -> bool { - let mut found = false; - d.walk(|n| { - if !found && matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) { - found = n.appearance.items.iter().any(|i| transparent_pattern_fill(d, n, i, see_through, colorize)); + d.layers.iter().any(|l| holds_transparent_image_patterns(d, l, see_through, colorize)) +} + +/// Whether `n`, art of `d`, is or holds a shown path or compound path (in groups, blends, +/// envelopes, repeats and Intertwine groups) with a pattern fill that +/// [`transparent_pattern_fill`] counts. Guides, clipping paths and template layers don't count. +fn holds_transparent_image_patterns(d: &Document, n: &Node, see_through: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool) -> bool { + if !drawn(n) { + return false; + } + match &n.kind { + NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. } => false, + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + n.appearance.items.iter().any(|i| transparent_pattern_fill(d, n, i, see_through, colorize)) } - }); - found + _ => n.children().is_some_and(|ch| ch.iter().any(|c| holds_transparent_image_patterns(d, c, see_through, colorize))), + } +} + +/// Whether `n` is shown and isn't a template layer. +fn drawn(n: &Node) -> bool { + n.visible && !matches!(n.kind, NodeKind::Layer { template: true, .. }) +} + +/// Expand the shown blends, envelopes, repeats and Intertwine groups under `root` that hold a +/// pattern fill [`holds_transparent_image_patterns`] counts into the art the exporters write for +/// them ([`expand_live_deep`](vectorcraft_render::effects::expand_live_deep), under one budget for +/// everything nested in each), so the shapes they draw are leaves. Returns how many were expanded. +fn expand_live_with_transparent_image_patterns( + d: &mut Document, + root: NodeId, + see_through: &BTreeSet<String>, + colorize: &dyn Fn(&Document, &Node) -> bool, +) -> Result<usize> { + fn outermost(d: &Document, n: &Node, see_through: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool, out: &mut Vec<NodeId>) { + if !drawn(n) { + return; + } + match &n.kind { + NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => { + if holds_transparent_image_patterns(d, n, see_through, colorize) { + out.push(n.id); + } + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { + children.iter().for_each(|c| outermost(d, c, see_through, colorize, out)); + } + _ => {} + } + } + /// Fresh ids for everything under `n`: copies of the same art share theirs. + fn fresh_ids(d: &mut Document, n: &mut Node) { + for c in n.children_mut().into_iter().flatten() { + let c = Arc::make_mut(c); + c.id = d.alloc_id(); + fresh_ids(d, c); + } + } + let mut live = vec![]; + if let Some(n) = d.node(root) { + outermost(d, n, see_through, colorize, &mut live); + } + let mut count = 0; + for id in &live { + let Some(n) = d.node(*id) else { continue }; + // Random Transform effects take their seed from the ids: bake them first ([`bake_seeded`]), + // and leave the object live when that can't be done. + let Some(mut g) = bake_seeded(&vectorcraft_render::effects::expand_live_deep(Some(d), n)) else { continue }; + g.id = *id; + fresh_ids(d, &mut g); + *d.node_mut(*id).ok_or(EngineError::NoNode(*id))? = g; + count += 1; + } + Ok(count) } /// Whether `i`, an item of leaf `l`, is a pattern fill whose tile art holds a transparent image diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index 7fbe44a0d1..0cd1ab159b 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -303,7 +303,8 @@ pub(crate) fn expand_transparent_tile_images(doc: &Document, o: &FlattenOptions) return Ok(None); } let mut d = doc.clone(); - let layers: Vec<NodeId> = d.layers.iter().map(|l| l.id).collect(); + let layers: Vec<NodeId> = + d.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })).map(|l| l.id).collect(); let mut changed = 0; for id in layers { changed += crate::cmd::expand::expand_transparent_image_patterns(&mut d, id, &keys, &colorize)?; diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index 0a3f9af6f4..96878b0432 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -817,3 +817,63 @@ fn opaque_pattern_tile_images_do_not_change_during_export_flattening() { let o = crate::cmd::FlattenOptions { no_transparency: Some(crate::cmd::flatten::see_through_images(d)), ..Default::default() }; assert!(crate::cmd::flatten::flatten_document(d, &o).unwrap().is_none()); } + +/// The id of the square [`pattern_over_blue`] fills with its pattern. +fn pattern_square(s: &Session) -> vectorcraft_doc::NodeId { + let mut id = None; + s.doc().unwrap().doc.walk(|n| { + if n.appearance.items.iter().any(|i| matches!(i.paint(), vectorcraft_color::Paint::Pattern { .. })) { + id = Some(n.id); + } + }); + id.unwrap() +} + +/// PDF 1.3 draws `s` as the canvas draws it at two points of the pattern square. +fn assert_pdf13_draws_pattern_square_as_canvas(s: &mut Session) { + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + let r = s.execute("document.exportPdf", &json!({"compatibility": "1.3"})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let page = vectorcraft_pdf::import(&bytes).unwrap(); + let after = [colour_at(&page, 72.0, 72.0), colour_at(&page, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } +} + +#[test] +fn pdf13_flattens_colorized_pattern_tile_images_in_a_repeat() { + let mut s = colorized_pattern_over_blue(); + let square = pattern_square(&s); + s.execute("object.repeat.grid", &json!({"ids": [square.0]})).unwrap(); + assert!(s.doc().unwrap().doc.layers[0].count() > 3); + let d = &s.doc().unwrap().doc; + let mut repeats = 0; + d.walk(|n| repeats += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Repeat(_)))); + assert_eq!(repeats, 1); + assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_some()); + assert_pdf13_draws_pattern_square_as_canvas(&mut s); +} + +#[test] +fn pdf13_leaves_a_hidden_shape_with_a_colorized_pattern_tile_image_hidden() { + let mut s = colorized_pattern_over_blue(); + let square = pattern_square(&s); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(square).unwrap().visible = false; + assert_pdf13_draws_pattern_square_as_canvas(&mut s); +} + +#[test] +fn flattening_skips_pattern_tile_images_on_hidden_and_template_layers() { + for template in [false, true] { + let mut s = colorized_pattern_over_blue(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let layer = std::sync::Arc::make_mut(&mut d.layers[0]); + match &mut layer.kind { + vectorcraft_doc::NodeKind::Layer { template: t, .. } if template => *t = true, + _ => layer.visible = false, + } + let d = &s.doc().unwrap().doc; + assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_none(), "template {template}"); + } +} From c09ea597319ff9b22fff48375cff4099c950b8f0 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 00:06:51 -0700 Subject: [PATCH 109/260] PDF/EPS export: transparent images in patterns nested in tile art flatten A pattern fill in a pattern's tile art that paints a see-through or colorized image was not counted, so PDF 1.3 export kept it as a pattern and failed on its transparency. Detection now follows pattern fills in tile art down to the three levels the canvas draws, skipping hidden tile art, and the tiles the expansion makes are expanded again for them. Expansion stops once the expanded art holds MAX_GENERATED objects. --- crates/engine/src/cmd/expand.rs | 119 ++++++++++++++++++++------- crates/engine/src/tests/legacy_ai.rs | 48 +++++++++++ 2 files changed, 137 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index b3bfab9c6e..eec854a743 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -451,47 +451,73 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> { /// in the tile art, the fill, the shape or a group the shape is in has opacity or a blending /// mode. Blends, envelopes, repeats and Intertwine groups that hold such a fill are expanded /// first ([`expand_live_with_transparent_image_patterns`]). Hidden shapes and shapes in hidden -/// groups or layers and in template layers stay as they are. Returns how many objects changed. +/// groups or layers and in template layers stay as they are. A pattern fill in tile art counts +/// too, down to the [`PATTERN_LEVELS`] the canvas draws, and the tile art the expansion makes is +/// expanded again for it. Pattern fills stay once the expanded art holds +/// [`MAX_GENERATED`](vectorcraft_doc::live::MAX_GENERATED) objects. Returns how many objects +/// changed. pub(crate) fn expand_transparent_image_patterns( d: &mut Document, root: NodeId, see_through: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool, ) -> Result<usize> { - let live = expand_live_with_transparent_image_patterns(d, root, see_through, colorize)?; - let (_, n) = replace_leaves(d, root, |d, l| { - // Most leaves have no pattern fill: skip the ancestry walk for them. - if !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { - return None; + let mut changed = 0; + let made = std::cell::Cell::new(0usize); + // Each pass brings the patterns in the expanded tiles' art up one level. + for levels in (1..=PATTERN_LEVELS).rev() { + let live = expand_live_with_transparent_image_patterns(d, root, see_through, colorize, levels)?; + let (_, n) = replace_leaves(d, root, |d, l| { + // Past the budget, and for most leaves, which have no pattern fill, skip the ancestry walk. + if made.get() >= vectorcraft_doc::live::MAX_GENERATED || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { + return None; + } + // The expanded art would be shown. + if !d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).all(drawn) { + return None; + } + let art = expand_patterns_where(d, l, |d, i| transparent_pattern_fill(d, l, i, see_through, colorize, levels))?; + made.set(made.get().saturating_add(art.count())); + Some(art) + })?; + if live + n == 0 { + break; } - // The expanded art would be shown. - if !d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).all(drawn) { - return None; - } - expand_patterns_where(d, l, |d, i| transparent_pattern_fill(d, l, i, see_through, colorize)) - })?; - Ok(live + n) + changed += live + n; + } + Ok(changed) } +/// How many levels of patterns the canvas draws: a pattern fill in the art of a pattern, and so +/// on, as [`vectorcraft_render`] draws them. +const PATTERN_LEVELS: u32 = 3; + /// Whether a layer of `d` holds a pattern fill that [`expand_transparent_image_patterns`] would /// expand with `see_through` and `colorize` ([`holds_transparent_image_patterns`]). pub(crate) fn has_transparent_image_patterns(d: &Document, see_through: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool) -> bool { - d.layers.iter().any(|l| holds_transparent_image_patterns(d, l, see_through, colorize)) + d.layers.iter().any(|l| holds_transparent_image_patterns(d, l, see_through, colorize, PATTERN_LEVELS)) } /// Whether `n`, art of `d`, is or holds a shown path or compound path (in groups, blends, /// envelopes, repeats and Intertwine groups) with a pattern fill that -/// [`transparent_pattern_fill`] counts. Guides, clipping paths and template layers don't count. -fn holds_transparent_image_patterns(d: &Document, n: &Node, see_through: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool) -> bool { +/// [`transparent_pattern_fill`] counts with `levels`. Guides, clipping paths and template layers +/// don't count. +fn holds_transparent_image_patterns( + d: &Document, + n: &Node, + see_through: &BTreeSet<String>, + colorize: &dyn Fn(&Document, &Node) -> bool, + levels: u32, +) -> bool { if !drawn(n) { return false; } match &n.kind { NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. } => false, NodeKind::Path { .. } | NodeKind::Compound { .. } => { - n.appearance.items.iter().any(|i| transparent_pattern_fill(d, n, i, see_through, colorize)) + n.appearance.items.iter().any(|i| transparent_pattern_fill(d, n, i, see_through, colorize, levels)) } - _ => n.children().is_some_and(|ch| ch.iter().any(|c| holds_transparent_image_patterns(d, c, see_through, colorize))), + _ => n.children().is_some_and(|ch| ch.iter().any(|c| holds_transparent_image_patterns(d, c, see_through, colorize, levels))), } } @@ -501,7 +527,7 @@ fn drawn(n: &Node) -> bool { } /// Expand the shown blends, envelopes, repeats and Intertwine groups under `root` that hold a -/// pattern fill [`holds_transparent_image_patterns`] counts into the art the exporters write for +/// pattern fill [`holds_transparent_image_patterns`] counts with `levels` into the art the exporters write for /// them ([`expand_live_deep`](vectorcraft_render::effects::expand_live_deep), under one budget for /// everything nested in each), so the shapes they draw are leaves. Returns how many were expanded. fn expand_live_with_transparent_image_patterns( @@ -509,19 +535,27 @@ fn expand_live_with_transparent_image_patterns( root: NodeId, see_through: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool, + levels: u32, ) -> Result<usize> { - fn outermost(d: &Document, n: &Node, see_through: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool, out: &mut Vec<NodeId>) { + fn outermost( + d: &Document, + n: &Node, + see_through: &BTreeSet<String>, + colorize: &dyn Fn(&Document, &Node) -> bool, + levels: u32, + out: &mut Vec<NodeId>, + ) { if !drawn(n) { return; } match &n.kind { NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => { - if holds_transparent_image_patterns(d, n, see_through, colorize) { + if holds_transparent_image_patterns(d, n, see_through, colorize, levels) { out.push(n.id); } } NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { - children.iter().for_each(|c| outermost(d, c, see_through, colorize, out)); + children.iter().for_each(|c| outermost(d, c, see_through, colorize, levels, out)); } _ => {} } @@ -536,7 +570,7 @@ fn expand_live_with_transparent_image_patterns( } let mut live = vec![]; if let Some(n) = d.node(root) { - outermost(d, n, see_through, colorize, &mut live); + outermost(d, n, see_through, colorize, levels, &mut live); } let mut count = 0; for id in &live { @@ -553,18 +587,36 @@ fn expand_live_with_transparent_image_patterns( } /// Whether `i`, an item of leaf `l`, is a pattern fill whose tile art holds a transparent image -/// ([`transparent_image`]), counting the fill's and the shape's opacity and blending mode. +/// ([`transparent_image`], through pattern fills in that art down to `levels` patterns), +/// counting the fill's and the shape's opacity and blending mode. fn transparent_pattern_fill( d: &Document, l: &Node, i: &AppearanceItem, see_through: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool, + levels: u32, ) -> bool { - let Some((f, def, _)) = pattern_fill(d, i) else { return false }; let shape = d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(blended); - let on = shape || f.opacity < 1.0 || f.blend != BlendMode::Normal; - def.art.iter().any(|a| transparent_image(d, a, see_through, colorize, on)) + pattern_fill_holds_transparent_image(d, i, see_through, colorize, shape, levels) +} + +/// Whether `i` is a pattern fill whose tile art holds a transparent image ([`transparent_image`]), +/// down to `levels` patterns, counting the fill's opacity and blending mode, or anything when `on`. +fn pattern_fill_holds_transparent_image( + d: &Document, + i: &AppearanceItem, + keys: &BTreeSet<String>, + colorize: &dyn Fn(&Document, &Node) -> bool, + on: bool, + levels: u32, +) -> bool { + if levels == 0 { + return false; + } + let Some((f, def, _)) = pattern_fill(d, i) else { return false }; + let on = on || f.opacity < 1.0 || f.blend != BlendMode::Normal; + def.art.iter().any(|a| transparent_image(d, a, keys, colorize, on, levels - 1)) } /// Whether `n` has opacity or a blending mode of its own. @@ -574,12 +626,19 @@ fn blended(n: &Node) -> bool { /// Whether `n` (art of `d`) is or holds an image with see-through pixels (key in `keys`), a /// colorize paint that `colorize` counts, opacity or a blending mode of its own or of a group in -/// `n`, or anywhere when `on`. -fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool, on: bool) -> bool { +/// `n`, or anywhere when `on`, also in the tile art of the pattern fills of the paths in `n`, down +/// to `levels` patterns. Hidden art doesn't count. +fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool, on: bool, levels: u32) -> bool { + if !n.visible { + return false; + } let on = on || blended(n); match &n.kind { NodeKind::Image(im) => on || keys.contains(&im.key) || (n.extras().colorize.is_some() && colorize(d, n)), - _ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(d, c, keys, colorize, on))), + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + n.appearance.items.iter().any(|i| pattern_fill_holds_transparent_image(d, i, keys, colorize, on, levels)) + } + _ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(d, c, keys, colorize, on, levels))), } } diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index 96878b0432..ecac48bb7e 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -855,6 +855,54 @@ fn pdf13_flattens_colorized_pattern_tile_images_in_a_repeat() { assert_pdf13_draws_pattern_square_as_canvas(&mut s); } +/// [`colorized_pattern_over_blue`] with the square filled with a pattern named `outer` whose tile +/// art is a 32 pt square filled with the colorized image pattern. +fn nested_colorized_pattern_over_blue() -> Session { + let mut s = colorized_pattern_over_blue(); + let square = pattern_square(&s); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 32, "height": 32})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let inner = d.patterns[0].name.clone(); + let rect = d.layers[0].children().unwrap().last().unwrap().id; + let mut tile = d.remove(rect).unwrap(); + let paint = vectorcraft_color::Paint::Pattern { pattern: inner, xf: Default::default() }; + let tile_node = std::sync::Arc::make_mut(&mut tile); + tile_node.appearance.items.retain(|i| matches!(i, vectorcraft_doc::appearance::AppearanceItem::Fill(_))); + for i in &mut tile_node.appearance.items { + if let vectorcraft_doc::appearance::AppearanceItem::Fill(f) = i { + f.paint = paint.clone(); + } + } + let mut outer = d.patterns[0].clone(); + outer.name = "outer".into(); + outer.art = vec![tile]; + d.patterns.push(outer); + for i in &mut d.node_mut(square).unwrap().appearance.items { + if let vectorcraft_doc::appearance::AppearanceItem::Fill(f) = i { + f.paint = vectorcraft_color::Paint::Pattern { pattern: "outer".into(), xf: Default::default() }; + } + } + s +} + +#[test] +fn pdf13_flattens_colorized_image_in_a_pattern_nested_in_tile_art() { + let mut s = nested_colorized_pattern_over_blue(); + assert_eq!(colour_at(&s.doc().unwrap().doc, 72.0, 72.0), [255, 0, 0]); + assert!(crate::cmd::flatten::flatten_document(&s.doc().unwrap().doc, &crate::cmd::FlattenOptions::default()).unwrap().is_some()); + assert_pdf13_draws_pattern_square_as_canvas(&mut s); +} + +#[test] +fn flattening_skips_a_pattern_nested_in_hidden_tile_art() { + let mut s = nested_colorized_pattern_over_blue(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let outer = d.pattern_mut("outer").unwrap(); + std::sync::Arc::make_mut(&mut outer.art[0]).visible = false; + let d = &s.doc().unwrap().doc; + assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_none()); +} + #[test] fn pdf13_leaves_a_hidden_shape_with_a_colorized_pattern_tile_image_hidden() { let mut s = colorized_pattern_over_blue(); From e2fddc6b127fc4728cecffb13fc9fc9693c1d52a Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 04:11:26 -0700 Subject: [PATCH 110/260] PDF/EPS export: pattern fills whose tiles pass the object limit stay pattern fills The expansion counted the objects a pattern fill made only after making them, so one shape could clone up to 250,000 tile positions times the tile art's objects past the limit. Each fill now counts its tiles before they are made, and after outlining strokes and effects for turned or sheared tiles, and keeps room for the copy and group of the fills after it. A fill that does not fit stays a pattern fill. --- crates/engine/src/cmd/expand.rs | 86 ++++++++++++++++++++++------ crates/engine/src/tests/legacy_ai.rs | 55 ++++++++++++++++++ 2 files changed, 125 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index eec854a743..1b09fb6318 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -453,7 +453,7 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> { /// first ([`expand_live_with_transparent_image_patterns`]). Hidden shapes and shapes in hidden /// groups or layers and in template layers stay as they are. A pattern fill in tile art counts /// too, down to the [`PATTERN_LEVELS`] the canvas draws, and the tile art the expansion makes is -/// expanded again for it. Pattern fills stay once the expanded art holds +/// expanded again for it. A pattern fill stays when its tiles would take the expanded art past /// [`MAX_GENERATED`](vectorcraft_doc::live::MAX_GENERATED) objects. Returns how many objects /// changed. pub(crate) fn expand_transparent_image_patterns( @@ -461,6 +461,18 @@ pub(crate) fn expand_transparent_image_patterns( root: NodeId, see_through: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool, +) -> Result<usize> { + expand_transparent_image_patterns_within(d, root, see_through, colorize, vectorcraft_doc::live::MAX_GENERATED) +} + +/// [`expand_transparent_image_patterns`] with the art the pattern fills expand to held to `budget` +/// objects. Live art expands under its own budget ([`expand_live_with_transparent_image_patterns`]). +pub(crate) fn expand_transparent_image_patterns_within( + d: &mut Document, + root: NodeId, + see_through: &BTreeSet<String>, + colorize: &dyn Fn(&Document, &Node) -> bool, + budget: usize, ) -> Result<usize> { let mut changed = 0; let made = std::cell::Cell::new(0usize); @@ -469,15 +481,21 @@ pub(crate) fn expand_transparent_image_patterns( let live = expand_live_with_transparent_image_patterns(d, root, see_through, colorize, levels)?; let (_, n) = replace_leaves(d, root, |d, l| { // Past the budget, and for most leaves, which have no pattern fill, skip the ancestry walk. - if made.get() >= vectorcraft_doc::live::MAX_GENERATED || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { + if made.get() >= budget || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { return None; } // The expanded art would be shown. if !d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).all(drawn) { return None; } - let art = expand_patterns_where(d, l, |d, i| transparent_pattern_fill(d, l, i, see_through, colorize, levels))?; - made.set(made.get().saturating_add(art.count())); + let which = |d: &Document, i: &AppearanceItem| transparent_pattern_fill(d, l, i, see_through, colorize, levels); + let art = expand_patterns_where(d, l, which, budget - made.get())?; + // The copies of the shape's other items count too. + let count = art.count_with_masks(); + if count > budget - made.get() { + return None; + } + made.set(made.get() + count); Some(art) })?; if live + n == 0 { @@ -650,12 +668,12 @@ fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet<String>, colorize: /// ([`pattern_tiles`]). A pattern fill that lays no tile there stays. `None` when no pattern fill /// lays a tile. fn expand_patterns(d: &mut Document, l: &Node) -> Option<Node> { - expand_patterns_where(d, l, |_, _| true) + expand_patterns_where(d, l, |_, _| true, usize::MAX) } /// [`expand_patterns`] for only the pattern fills `which` picks: the others stay like the other -/// items. -fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, &AppearanceItem) -> bool) -> Option<Node> { +/// items, as does a pattern fill whose tiles would take the tiles of `l` past `budget` objects. +fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, &AppearanceItem) -> bool, budget: usize) -> Option<Node> { if !matches!(l.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some() && which(d, i)) { @@ -668,19 +686,47 @@ fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, & let mut parts = vec![]; let mut rest = vec![]; let mut expanded = false; + // What `assemble` adds around the tiles when every picked fill expands: a copy of the path for + // each run of other items, a group around the parts and one for the path's transparency, and + // the path's opacity mask. + let (mut copies, mut run, mut picked) = (0usize, false, vec![]); + for i in &l.appearance.items { + if let Some((f, _, _)) = pattern_fill(d, i).filter(|_| which(d, i)) { + run = false; + picked.push(f.opacity < 1.0 || f.blend != BlendMode::Normal); + } else if i.visible() && !i.paint().is_none() && !run { + (copies, run) = (copies + 1, true); + } + } + let group = copies + picked.len() > 1 || !l.appearance.effects.is_empty(); + // A lone tile group with transparency of its own goes in a group for the path's. + let transparency = blended(l) && !group && picked.first().is_some_and(|b| *b); + let around = copies.saturating_mul(l.count()) + usize::from(group) + usize::from(transparency) + l.count_with_masks().saturating_sub(l.count()); + let mut left = budget.saturating_sub(around); + // A fill that expands while others follow leaves room for the copy and group that those take + // if they don't fit, and once one doesn't fit, the ones after it stay too. + let (mut later, mut full) = (picked.len(), false); for item in &l.appearance.items { let fill = pattern_fill(d, item).filter(|_| which(d, item)).map(|(f, def, xf)| (f, def.clone(), xf)); - let tiles = fill.and_then(|(f, def, xf)| { + later -= usize::from(fill.is_some()); + let room = if later > 0 { left.saturating_sub(l.count() + 1) } else { left }; + let tiles = fill.filter(|_| !full).and_then(|(f, def, xf)| { let (fl, _, bounds) = fill_shape(l, item, &path, bounds)?; - let t = pattern_tiles(d, &def, xf, bounds); + let Some(t) = pattern_tiles(d, &def, xf, bounds, room) else { + full = true; + return None; + }; (!t.is_empty()).then_some((f, fl, t)) }); - let Some(art) = tiles.and_then(|(f, fl, t)| tile_art(d, &fl, f, &t)) else { + let art = tiles.and_then(|(f, fl, t)| tile_art(d, &fl, f, &t)); + full |= art.as_ref().is_some_and(|a| a.count_with_masks() > room); + let Some(art) = art.filter(|a| a.count_with_masks() <= room) else { if item.visible() && !item.paint().is_none() { rest.push(item.clone()); } continue; }; + left -= art.count_with_masks(); if !rest.is_empty() { parts.push(styled_copy(d, l, std::mem::take(&mut rest))); } @@ -707,30 +753,38 @@ fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, & /// not, and when it does more than move art that holds a symbol instance, whose strokes the canvas /// draws scaled with the tile and an instance does not scale. Random Transform effects and brushes /// that vary at random in the art are baked first ([`seeds_baked`], [`random_brushes_baked`]). -fn pattern_tiles(d: &mut Document, def: &PatternDef, xf: Affine, bounds: Rect) -> Vec<Node> { +/// `None` when the tiles would hold more than `budget` objects. +fn pattern_tiles(d: &mut Document, def: &PatternDef, xf: Affine, bounds: Rect, budget: usize) -> Option<Vec<Node>> { if !moves_only(xf) && def.art.iter().any(|a| has_instances(a)) { - return vec![]; + return Some(vec![]); } let Some(def) = seeds_baked(def) else { - return vec![]; + return Some(vec![]); }; let brushes = vectorcraft_brush::library(d); let def = random_brushes_baked(d, &brushes, def); let def = &*def; + let per_tile = def.art.iter().map(|a| a.count_with_masks()).sum::<usize>(); + if def.offsets_covering(xf.inverse().transform_rect_bbox(bounds)).len().saturating_mul(per_tile) > budget { + return None; + } let scaling = Scaling { strokes: true, effects: Some(vectorcraft_render::effects::scale_effect), patterns: true, ..Scaling::default() }; if scales_evenly(xf) && (moves_only(xf) || !def.art.iter().any(|a| has_geometry_effects(a))) { - return def.instances_in_with(xf, bounds, scaling); + return Some(def.instances_in_with(xf, bounds, scaling)); } if def.art.iter().any(|a| has_unbakeable_effects(a)) { - return vec![]; + return Some(vec![]); } let placed = Scaling { patterns: true, ..Scaling::default() }; let mut tiles = def.instances_in_with(Affine::IDENTITY, xf.inverse().transform_rect_bbox(bounds), placed); + // Outlined strokes and effects can make more objects than the art had. + let mut left = budget; for t in &mut tiles { *t = prepared(d, &brushes, t); + left = left.checked_sub(t.count_with_masks())?; place_art(t, xf, scaling); } - tiles + Some(tiles) } /// Pattern `def` with each path in its art (opacity masks included) that has a random Transform diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index ecac48bb7e..f038ab2514 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -705,6 +705,61 @@ fn only_the_transparent_pattern_fill_of_a_leaf_is_expanded() { assert!(images > 0); } +/// A pattern fill whose expanded art would hold more objects than the budget stays a pattern fill: +/// the 32 pt tiles over the 128 pt square are 25 copies of the tile art's 3 objects, which are not +/// made with a smaller budget, and the clip group around them counts too. +#[test] +fn a_transparent_image_pattern_past_the_budget_stays() { + let expand = |budget: usize| { + let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0); + assert_eq!(s.doc().unwrap().doc.patterns[0].art.iter().map(|a| a.count_with_masks()).sum::<usize>(), 3); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let keys = crate::cmd::flatten::see_through_images(d); + let layer = d.layers[0].id; + let before = d.layers[0].count_with_masks(); + let n = crate::cmd::expand::expand_transparent_image_patterns_within(d, layer, &keys, &|_, _| true, budget).unwrap(); + // The objects the expansion made, with the square it replaced. + (n, images(d).0, d.layers[0].count_with_masks() + 1 - before) + }; + let (n, tiles, made) = expand(usize::MAX); + assert_eq!((n, tiles), (1, 25)); + assert!(made > 75, "{made}"); + assert_eq!(expand(made), (1, 25, made)); + assert_eq!(expand(made - 1).0, 0); + assert_eq!(expand(74).0, 0); +} + +/// On a shape with two transparent image pattern fills, both expand with a budget their tiles and +/// the group around them fit, and one expands with one object less. +#[test] +fn two_transparent_image_pattern_fills_expand_within_the_budget() { + let expand = |budget: usize| { + let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let mut square = None; + d.walk(|n| { + if n.appearance.items.iter().any( + |i| matches!(i, vectorcraft_doc::appearance::AppearanceItem::Fill(f) if matches!(f.paint, vectorcraft_color::Paint::Pattern { .. })), + ) { + square = Some(n.id); + } + }); + let n = d.node_mut(square.unwrap()).unwrap(); + assert_eq!(n.appearance.items.len(), 1); + let fill = n.appearance.items[0].clone(); + n.appearance.items.push(fill); + let keys = crate::cmd::flatten::see_through_images(d); + let layer = d.layers[0].id; + let before = d.layers[0].count_with_masks(); + let n = crate::cmd::expand::expand_transparent_image_patterns_within(d, layer, &keys, &|_, _| true, budget).unwrap(); + (n, images(d).0, d.layers[0].count_with_masks() + 1 - before) + }; + let (n, tiles, made) = expand(usize::MAX); + assert_eq!((n, tiles), (1, 50)); + assert_eq!(expand(made), (1, 50, made)); + assert_eq!(expand(made - 1).1, 25); +} + #[test] fn pdf13_flattens_see_through_pattern_tile_images() { let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0); From a32a7cbb0d685471403764fc97e1e6cd8846fd7c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 04:27:09 -0700 Subject: [PATCH 111/260] PDF/EPS export: EPS export and PostScript printing expand pattern tile images once EPS export expanded the pattern fills whose tile images need flattening and then flattened the result with flatten_document, which expanded them again with a new object limit. PostScript printing did the same, on the layers shown rather than the layers that print. EPS export now flattens the expanded document without expanding it again (flatten_expanded), and PostScript printing leaves the expansion to the flattener, which runs on the layers that print, and only checks for such pattern fills to warn. --- crates/engine/src/cmd/fileio/eps.rs | 4 ++-- crates/engine/src/cmd/flatten.rs | 2 +- crates/engine/src/cmd/flatten/apply.rs | 24 +++++++++++++++++------- crates/engine/src/cmd/print.rs | 16 +++++++--------- crates/engine/src/tests/legacy_ai.rs | 9 +++++++++ 5 files changed, 36 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/fileio/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index 2c8ae4a845..d2424bf0a7 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -12,7 +12,7 @@ use vectorcraft_doc::Document; use vectorcraft_eps::{EpsOptions, Level, Overprint, Preview, Raster}; use vectorcraft_geom::{Point, Rect}; -use super::super::flatten::{FlattenOptions, expand_transparent_tile_images, flatten_document}; +use super::super::flatten::{FlattenOptions, expand_transparent_tile_images, flatten_expanded}; use super::super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param}; use super::{ArtboardPick, Encoded, FormatOption}; @@ -302,7 +302,7 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> { let expanded = expand_transparent_tile_images(doc, &set.flatten)?; let source = expanded.as_ref().unwrap_or(doc); let transparent = source.layers.iter().any(|l| set.flatten.shows_transparency(source, l)); - let flat = flatten_document(source, &set.flatten)?; + let flat = flatten_expanded(source, &set.flatten)?; let drawn = flat.as_ref().unwrap_or(source); let mut enc = Encoded { warnings, joiner: Some("_"), ..Encoded::default() }; if transparent && (flat.is_some() || expanded.is_some()) { diff --git a/crates/engine/src/cmd/flatten.rs b/crates/engine/src/cmd/flatten.rs index 94e05a3572..ccbe9c0493 100644 --- a/crates/engine/src/cmd/flatten.rs +++ b/crates/engine/src/cmd/flatten.rs @@ -49,7 +49,7 @@ mod presets; mod report; pub(crate) use analysis::{outlined_text, see_through_images}; -pub(crate) use apply::{expand_transparent_tile_images, flatten_document}; +pub(crate) use apply::{expand_transparent_tile_images, flatten_document, flatten_expanded, has_transparent_tile_images}; pub use commands::specs; pub use options::FlattenOptions; pub use presets::{FlattenerPreset, PRESET_EXTS, PRESET_FORMAT}; diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index 0cd1ab159b..d229f1bbb8 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -292,16 +292,21 @@ pub(super) fn opaque(n: &mut Node) { } } +/// Whether `doc` has pattern fills whose image tiles need transparency flattening with `o` +/// ([`expand_transparent_tile_images`]). +pub(crate) fn has_transparent_tile_images(doc: &Document, o: &FlattenOptions) -> bool { + let keys = o.no_transparency.clone().unwrap_or_default(); + let colorize = |d: &Document, n: &Node| o.counts_colorize(d, n); + !doc.patterns.is_empty() && crate::cmd::expand::has_transparent_image_patterns(doc, &keys, &colorize) +} + /// Expand pattern fills whose image tiles need transparency flattening. pub(crate) fn expand_transparent_tile_images(doc: &Document, o: &FlattenOptions) -> Result<Option<Document>> { - if doc.patterns.is_empty() { + if !has_transparent_tile_images(doc, o) { return Ok(None); } let keys = o.no_transparency.clone().unwrap_or_default(); let colorize = |d: &Document, n: &Node| o.counts_colorize(d, n); - if !crate::cmd::expand::has_transparent_image_patterns(doc, &keys, &colorize) { - return Ok(None); - } let mut d = doc.clone(); let layers: Vec<NodeId> = d.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })).map(|l| l.id).collect(); @@ -319,10 +324,15 @@ pub(crate) fn expand_transparent_tile_images(doc: &Document, o: &FlattenOptions) /// expanded when `o.no_transparency` counts them. `None` when nothing changes. pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result<Option<Document>> { let expanded = expand_transparent_tile_images(doc, o)?; - let doc = expanded.as_ref().unwrap_or(doc); + Ok(flatten_expanded(expanded.as_ref().unwrap_or(doc), o)?.or(expanded)) +} + +/// [`flatten_document`] for `doc` whose pattern tile images were expanded already +/// ([`expand_transparent_tile_images`]). +pub(crate) fn flatten_expanded(doc: &Document, o: &FlattenOptions) -> Result<Option<Document>> { let outlining = o.text_to_outlines || o.strokes_to_outlines || !o.preserve_overprints; if !outlining && !doc.layers.iter().any(|l| o.shows_transparency(doc, l) || o.draws_see_through_image(l)) { - return Ok(expanded); + return Ok(None); } let mut roots = vec![]; for l in doc.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })) { @@ -331,7 +341,7 @@ pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result<Opt } let plan = plan(doc, &roots, o, true)?; if plan.flat.is_empty() && !plan.kept.iter().any(|id| doc.node(*id).is_some_and(|n| kept_work(n, o))) { - return Ok(expanded); + return Ok(None); } let mut d = doc.clone(); apply(&mut d, &mut vectorcraft_doc::Selection::default(), plan, o)?; diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index be6e9e67c2..075bac2f5b 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -11,7 +11,7 @@ use vectorcraft_pdf::{PrintLayers, PrintOptions, PrintPreview, PrintSettings}; use super::fileio::pdf::{merge, pdf_error}; use super::fileio::{extension, write_or_return}; -use super::flatten::expand_transparent_tile_images; +use super::flatten::has_transparent_tile_images; use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param}; const SETUP: &str = "print.setup"; @@ -181,13 +181,11 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> { let flat = super::rasterfx::flatten_raster_effects(doc); let doc = flat.as_ref().unwrap_or(doc); let bitmap = set.advanced.print_as_bitmap && set.output.mode == vectorcraft_pdf::OutputMode::Composite; - let expanded = if postscript && !bitmap { - let options = super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?; - options.as_ref().map(|o| expand_transparent_tile_images(doc, o)).transpose()?.flatten() - } else { - None - }; - let doc = expanded.as_ref().unwrap_or(doc); + // The flattener expands pattern fills whose tile images need flattening, in the layers that print. + let tile_images = postscript + && !bitmap + && super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)? + .is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o)); // Print as Bitmap and the flattener preset (Advanced) render and flatten it first. let prepared = super::printadvanced::prepare(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich")?; let path = str_param(p, "path"); @@ -210,7 +208,7 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> { None => Level::default(), }; let mut warnings = vec![]; - if !bitmap && doc.layers.iter().any(|l| l.shows_transparency()) { + if !bitmap && (tile_images || doc.layers.iter().any(|l| l.shows_transparency())) { warnings.push("transparency is flattened into opaque art and images (PostScript has none): see flattenerPreset".to_string()); } if !set.color.profile.trim().is_empty() && set.output.mode == vectorcraft_pdf::OutputMode::Composite { diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index f038ab2514..1b0f7ad3f3 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -820,6 +820,15 @@ fn flattening_that_keeps_colorize_leaves_colorized_pattern_tile_images_alone() { assert!(crate::cmd::flatten::flatten_document(d, &o).unwrap().is_none(), "the pattern isn't expanded for a colorize paint alone"); } +/// EPS export expands pattern tile images once: flattening the expanded +/// document leaves the patterns the expansion kept, past its object limit, as they are. +#[test] +fn flattening_an_expanded_document_does_not_expand_patterns_again() { + let s = colorized_pattern_over_blue(); + let d = &s.doc().unwrap().doc; + assert!(crate::cmd::flatten::flatten_expanded(d, &crate::cmd::FlattenOptions::default()).unwrap().is_none()); +} + #[test] fn eps_flattens_colorized_image_in_a_see_through_pattern_tile_group_and_warns() { let mut s = colorized_pattern_over_blue(); From 93e27cafd341459b3861feba87470b00ce8fefa1 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 04:33:50 -0700 Subject: [PATCH 112/260] PDF/EPS export: live art expanded for pattern tile images counts against the object limit Blends, envelopes, repeats and Intertwine groups that hold a pattern fill with a transparent tile image were each expanded under a limit of their own, so many of them together had no limit. Their art now counts toward the same limit as the pattern tiles, and an object whose art would pass it stays live. --- crates/engine/src/cmd/expand.rs | 26 +++++++++++++++++++------- crates/engine/src/tests/legacy_ai.rs | 16 ++++++++++++++++ 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 1b09fb6318..4745437d40 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -453,9 +453,9 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> { /// first ([`expand_live_with_transparent_image_patterns`]). Hidden shapes and shapes in hidden /// groups or layers and in template layers stay as they are. A pattern fill in tile art counts /// too, down to the [`PATTERN_LEVELS`] the canvas draws, and the tile art the expansion makes is -/// expanded again for it. A pattern fill stays when its tiles would take the expanded art past -/// [`MAX_GENERATED`](vectorcraft_doc::live::MAX_GENERATED) objects. Returns how many objects -/// changed. +/// expanded again for it. A pattern fill stays, and a live object stays live, when its art would +/// take the expanded art past [`MAX_GENERATED`](vectorcraft_doc::live::MAX_GENERATED) objects. +/// Returns how many objects changed. pub(crate) fn expand_transparent_image_patterns( d: &mut Document, root: NodeId, @@ -465,8 +465,7 @@ pub(crate) fn expand_transparent_image_patterns( expand_transparent_image_patterns_within(d, root, see_through, colorize, vectorcraft_doc::live::MAX_GENERATED) } -/// [`expand_transparent_image_patterns`] with the art the pattern fills expand to held to `budget` -/// objects. Live art expands under its own budget ([`expand_live_with_transparent_image_patterns`]). +/// [`expand_transparent_image_patterns`] with the expanded art held to `budget` objects. pub(crate) fn expand_transparent_image_patterns_within( d: &mut Document, root: NodeId, @@ -478,7 +477,7 @@ pub(crate) fn expand_transparent_image_patterns_within( let made = std::cell::Cell::new(0usize); // Each pass brings the patterns in the expanded tiles' art up one level. for levels in (1..=PATTERN_LEVELS).rev() { - let live = expand_live_with_transparent_image_patterns(d, root, see_through, colorize, levels)?; + let live = expand_live_with_transparent_image_patterns(d, root, see_through, colorize, levels, &made, budget)?; let (_, n) = replace_leaves(d, root, |d, l| { // Past the budget, and for most leaves, which have no pattern fill, skip the ancestry walk. if made.get() >= budget || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { @@ -547,13 +546,17 @@ fn drawn(n: &Node) -> bool { /// Expand the shown blends, envelopes, repeats and Intertwine groups under `root` that hold a /// pattern fill [`holds_transparent_image_patterns`] counts with `levels` into the art the exporters write for /// them ([`expand_live_deep`](vectorcraft_render::effects::expand_live_deep), under one budget for -/// everything nested in each), so the shapes they draw are leaves. Returns how many were expanded. +/// everything nested in each), so the shapes they draw are leaves. The objects that art holds count +/// in `made`, and an object whose art would take `made` past `budget` stays live. Returns how many +/// were expanded. fn expand_live_with_transparent_image_patterns( d: &mut Document, root: NodeId, see_through: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool, levels: u32, + made: &std::cell::Cell<usize>, + budget: usize, ) -> Result<usize> { fn outermost( d: &Document, @@ -592,10 +595,19 @@ fn expand_live_with_transparent_image_patterns( } let mut count = 0; for id in &live { + if made.get() >= budget { + break; + } let Some(n) = d.node(*id) else { continue }; // Random Transform effects take their seed from the ids: bake them first ([`bake_seeded`]), // and leave the object live when that can't be done. let Some(mut g) = bake_seeded(&vectorcraft_render::effects::expand_live_deep(Some(d), n)) else { continue }; + // An object whose art would take the expanded art past the budget stays live. + let size = g.count_with_masks(); + if size > budget - made.get() { + continue; + } + made.set(made.get() + size); g.id = *id; fresh_ids(d, &mut g); *d.node_mut(*id).ok_or(EngineError::NoNode(*id))? = g; diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index 1b0f7ad3f3..90c728a2fc 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -919,6 +919,22 @@ fn pdf13_flattens_colorized_pattern_tile_images_in_a_repeat() { assert_pdf13_draws_pattern_square_as_canvas(&mut s); } +/// A repeat whose art would take the expanded art past the budget stays live. +#[test] +fn a_repeat_past_the_budget_stays_live() { + for (budget, live) in [(1, 1), (usize::MAX, 0)] { + let mut s = colorized_pattern_over_blue(); + let square = pattern_square(&s); + s.execute("object.repeat.grid", &json!({"ids": [square.0]})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let layer = d.layers[0].id; + crate::cmd::expand::expand_transparent_image_patterns_within(d, layer, &Default::default(), &|_, _| true, budget).unwrap(); + let mut repeats = 0; + d.walk(|n| repeats += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Repeat(_)))); + assert_eq!(repeats, live, "budget {budget}"); + } +} + /// [`colorized_pattern_over_blue`] with the square filled with a pattern named `outer` whose tile /// art is a 32 pt square filled with the colorized image pattern. fn nested_colorized_pattern_over_blue() -> Session { From bb6cbfb2b44ceeca70da27c80dcd5760b5e22de0 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 18:37:09 -0700 Subject: [PATCH 113/260] Images: SVG and EPS export write colorized grayscale and 1-bit images in their fill color SVG export ignored an image's colorize paint and wrote the image's own black, white and gray pixels. EPS export flattened every colorized image into a process-color raster, so a spot color lost its plate. Both now write the image in the fill color, with the coverage the canvas and PDF export use (darkness times alpha), so white and transparent pixels take no color. - SVG writes a coverage PNG as a mask over a rectangle in the color, shared between repeated images while each keeps its own color. Linked mode writes the coverage PNG as a file, and SVG Tiny 1.2 writes a PNG in the color. A colorized image whose pixels are missing, or whose grayscale pixels can't be decoded, is left out with a warning. - EPS writes fully covered or uncovered pixels as an imagemask in the color's process or Separation ink (Registration on every plate), and a grayscale image as ink samples scaled by coverage. Level 3 masks its uncovered pixels out and Level 2 writes them white; gray midtones are written over white, with the existing warnings. - EPS flattening no longer counts a solid colorize paint on a grayscale or 1-bit image as transparency by itself. Opacity, blending modes, opacity masks, effects and overlapping transparent art still flatten it, and so does a colorize paint the writer can't draw. The svg crate's tests turn on resvg's raster-images feature to render the embedded PNGs. Docs: docs/mcp.md, docs/target-app-parity.md. --- Cargo.lock | 48 +++-- crates/engine/src/cmd/fileio/eps.rs | 2 + crates/engine/src/tests/colorize.rs | 32 ++++ crates/eps/src/scene.rs | 156 +++++++++++++++- crates/eps/src/tests.rs | 181 +++++++++++++++++++ crates/svg/Cargo.toml | 2 +- crates/svg/src/export.rs | 12 ++ crates/svg/src/export/nodes.rs | 13 ++ crates/svg/src/export/paint.rs | 131 +++++++++++++- crates/svg/tests/it/colorized_images.rs | 229 ++++++++++++++++++++++++ crates/svg/tests/it/main.rs | 1 + docs/mcp.md | 2 + docs/target-app-parity.md | 1 + 13 files changed, 795 insertions(+), 15 deletions(-) create mode 100644 crates/svg/tests/it/colorized_images.rs diff --git a/Cargo.lock b/Cargo.lock index a1512c6d0d..aeec6db30e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1940,6 +1940,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "gif" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b" +dependencies = [ + "color_quant", + "weezl 0.1.12", +] + [[package]] name = "gif" version = "0.14.2" @@ -2233,7 +2243,7 @@ dependencies = [ "rustc-hash 2.1.3", "smallvec", "stringprep", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -2609,14 +2619,14 @@ dependencies = [ "bytemuck", "byteorder-lite", "color_quant", - "gif", + "gif 0.14.2", "image-webp", "moxcms", "num-traits", "png 0.18.1", "tiff", - "zune-core", - "zune-jpeg", + "zune-core 0.5.3", + "zune-jpeg 0.5.15", ] [[package]] @@ -2837,7 +2847,7 @@ dependencies = [ "bumpalo", "flate2", "float-cmp", - "gif", + "gif 0.14.2", "image-webp", "imagesize 0.14.0", "indexmap", @@ -2852,7 +2862,7 @@ dependencies = [ "tiny-skia-path 0.12.0", "xmp-writer", "yoke", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -4380,12 +4390,15 @@ version = "0.45.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43" dependencies = [ + "gif 0.13.3", + "image-webp", "log", "pico-args", "rgb", "svgtypes 0.15.3", "tiny-skia", "usvg 0.45.1", + "zune-jpeg 0.4.21", ] [[package]] @@ -5490,7 +5503,7 @@ dependencies = [ "half", "quick-error 2.0.1", "weezl 0.1.12", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -6169,7 +6182,7 @@ dependencies = [ "tiff", "vectorcraft-color", "vectorcraft-geom", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -6374,7 +6387,7 @@ name = "vectorcraft-render" version = "0.19.0" dependencies = [ "flate2", - "gif", + "gif 0.14.2", "image", "jpeg-encoder", "log", @@ -7950,19 +7963,34 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "zune-core" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a" + [[package]] name = "zune-core" version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" +[[package]] +name = "zune-jpeg" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713" +dependencies = [ + "zune-core 0.4.12", +] + [[package]] name = "zune-jpeg" version = "0.5.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" dependencies = [ - "zune-core", + "zune-core 0.5.3", ] [[package]] diff --git a/crates/engine/src/cmd/fileio/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index d2424bf0a7..49ecfaa345 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -152,6 +152,8 @@ fn parse(p: &Value) -> Result<Settings> { let overprint = choice("overprints", q.overprints.clone(), Overprint::from_id, d.overprint, "preserve or discard")?; let mut flatten = flattener(&q, &[])?; flatten.preserve_overprints &= overprint == Overprint::Preserve; + // The writer draws colorized images in their ink. + flatten.keeps_colorize = true; let level = q.level.as_ref().map(super::dxf::text); let eps = EpsOptions { level: choice("level", level, Level::from_id, d.level, "2 or 3")?, diff --git a/crates/engine/src/tests/colorize.rs b/crates/engine/src/tests/colorize.rs index bb9a9ac0f9..bcd590c2d4 100644 --- a/crates/engine/src/tests/colorize.rs +++ b/crates/engine/src/tests/colorize.rs @@ -379,6 +379,38 @@ fn colorized_gray_image_is_omitted_from_legacy_ai_when_requested() { assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("are left out")), "{}", out["warnings"]); } +#[test] +fn eps_export_writes_a_colorized_image_in_its_spot_ink_without_flattening() { + let mut s = session(); + let id = image(&mut s, "gray", gray(false)); + s.execute("paint.setFill", &json!({"swatch": "Ink", "ids": [id.0]})).unwrap(); + let out = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap(); + assert!(out["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap().contains("transparency is flattened")), "{}", out["warnings"]); + let bytes = vectorcraft_format::base64_decode(out["dataBase64"].as_str().unwrap()).unwrap(); + let ps = String::from_utf8_lossy(&bytes); + assert!(ps.contains("imagemask") && ps.contains("/Separation (Ink) cvn"), "the image prints on the Ink plate"); + assert!(ps.contains("%%DocumentCustomColors: (Ink)")); + + // Opacity still flattens it. + s.execute("transparency.set", &json!({"ids": [id.0], "opacity": 50})).unwrap(); + let out = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap(); + assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("transparency is flattened")), "{}", out["warnings"]); +} + +#[test] +fn eps_export_still_flattens_a_colorize_paint_on_a_color_image() { + let mut s = session(); + let rgb = png(image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(2, 1, vec![0, 128, 255, 255, 0, 0]).unwrap())); + let id = image(&mut s, "rgb", rgb); + s.edit("Colorize", |d, _| { + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + Ok(()) + }) + .unwrap(); + let out = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap(); + assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("transparency is flattened")), "{}", out["warnings"]); +} + #[test] fn flattened_colorized_image_shows_the_art_under_white_pixels() { let mut s = session(); diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 83d3e7e01f..6e6ba05847 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -119,6 +119,8 @@ pub(crate) struct Scene<'a> { brushes: Option<Vec<vectorcraft_brush::Brush>>, /// Image keys → what draws them (`None`: left out). images: HashMap<String, Option<Arc<String>>>, + /// The source key and solid paint together identify a colorized encoding. + colorized_images: HashMap<(String, String), Option<Arc<String>>>, /// Symbols and brush art being written inside one another. nest: u32, } @@ -137,6 +139,7 @@ impl<'a> Scene<'a> { warnings: vec![], brushes: None, images: HashMap::new(), + colorized_images: HashMap::new(), nest: 0, } } @@ -297,7 +300,15 @@ impl<'a> Scene<'a> { self.shape(n, &bp, *rule); } NodeKind::Text(t) => self.text(n, t), - NodeKind::Image(im) => self.image(&im.key, self.doc.image_blob(im), im.width, im.height, im.xf), + NodeKind::Image(im) => { + let blob = self.doc.image_blob(im); + match n.extras().colorize.as_deref() { + Some(p @ Paint::Solid { .. }) if blob.is_none_or(|b| b.gray_source().is_some()) => { + self.colorized_image(&im.key, blob, im.width, im.height, im.xf, p); + } + _ => self.image(&im.key, blob, im.width, im.height, im.xf), + } + } NodeKind::SymbolInstance { symbol, xf } => { if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol) && self.nest < MAX_NEST @@ -886,6 +897,149 @@ impl<'a> Scene<'a> { } } + /// Gray coverage in the selected process or Separation ink. Binary coverage is a stencil; + /// continuous coverage leaves zero pixels untouched at Level 3 and writes them as paper at Level 2. + fn colorized_image(&mut self, key: &str, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine, paint: &Paint) { + let place = xf * Affine::scale_non_uniform(f64::from(width.max(1)), f64::from(height.max(1))); + if !invertible(place) { + return; + } + let cache = (key.to_string(), format!("{paint:?}")); + let encoded = match self.colorized_images.get(&cache) { + Some(e) => e.clone(), + None => { + let e = self.encode_colorized(blob, paint).map(Arc::new); + self.colorized_images.insert(cache, e.clone()); + e + } + }; + if let Some(e) = encoded { + self.place_image(&e, place); + } + } + + fn encode_colorized(&mut self, blob: Option<&ImageBlob>, paint: &Paint) -> Option<String> { + let Some((w, h, coverage)) = blob.and_then(ImageBlob::coverage) else { + self.warn(UNDECODED); + return None; + }; + if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_IMAGE_PIXELS { + self.warn(LARGE_IMAGE); + return None; + } + let Paint::Solid { color, swatch, tint } = paint else { return None }; + let ink = self.solid(color, swatch.as_deref(), *tint); + let binary = coverage.iter().all(|&v| v == 0 || v == 255); + let clear = coverage.contains(&0); + if coverage.iter().any(|&v| v > 0 && v < 255) { + self.warn(IMAGE_PARTLY); + } + let keyed = !binary && clear && self.o.level == Level::Three; + if !binary && clear && !keyed { + self.warn(IMAGE_ALPHA_L2); + } + // Zero tint is uncommon for covered spot pixels; process uses the same rare key as + // ordinary images. Nudge a covered collision so only clear pixels match the mask. + let key = match ink { + Ink::Spot { .. } => [0, 0, 0, 0], + Ink::Process(Space::Gray, ..) => [0, 0, 0, 0], + Ink::Process(..) => [255, 0, 255, 0], + }; + let mut data = Vec::new(); + if binary { + let stride = (w as usize).div_ceil(8); + data.resize(stride.saturating_mul(h as usize), 0); + for (i, &v) in coverage.iter().enumerate() { + if v == 255 + && let Some(byte) = data.get_mut((i / w as usize) * stride + (i % w as usize) / 8) + { + *byte |= 0x80 >> (i % w as usize % 8); + } + } + } else { + for &v in &coverage { + if v == 0 && keyed { + let n = match ink { + Ink::Spot { .. } => 1, + Ink::Process(space, ..) => space.n(), + }; + data.extend(key.iter().take(n)); + continue; + } + let a = f32::from(v) / 255.0; + match ink { + Ink::Spot { tint, .. } => { + let mut sample = (255.0 * tint * a).round() as u8; + if keyed && sample == key[0] { + sample = 1; + } + data.push(sample); + } + Ink::Process(space, components) => { + let paper = if space == Space::Cmyk { 0.0 } else { 1.0 }; + let n = space.n(); + let mut samples = [0; 4]; + for (sample, &component) in samples.iter_mut().zip(components.iter()).take(n) { + *sample = (255.0 * (paper + (component - paper) * a)).round() as u8; + } + if keyed && samples.iter().take(n).eq(key.iter().take(n)) { + samples[if n > 1 { 1 } else { 0 }] = 1; + } + data.extend(samples.iter().take(n)); + } + } + } + } + let (filter, encoded) = match self.o.level { + Level::Three => ("/FlateDecode", ps::deflate(&data)), + Level::Two => { + let mut rl = Vec::new(); + ps::packbits(&data, &mut rl); + rl.push(128); + ("/RunLengthDecode", rl) + } + }; + let mut out = String::new(); + if binary { + // imagemask takes its current ink from the graphics state. + out.push_str(&self.ink_code(ink)); + } else { + match ink { + Ink::Spot { space, .. } => { + let _ = writeln!(out, "VCsp{space} setcolorspace"); + } + Ink::Process(space, ..) => { + let _ = writeln!(out, "{} setcolorspace", space.name()); + } + } + } + let n = match ink { + Ink::Spot { .. } => 1, + Ink::Process(space, ..) => space.n(), + }; + let decode = if binary { "1 0".to_string() } else { "0 1 ".repeat(n).trim_end().to_string() }; + let _ = write!( + out, + "{{ /VCsrc currentfile /ASCII85Decode filter def\n<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent {} /Decode [{decode}] /ImageMatrix [{w} 0 0 {h} 0 0]", + if keyed { 4 } else { 1 }, + if binary { 1 } else { 8 }, + ); + if keyed { + let mask: Vec<String> = key.iter().take(n).map(|v| format!("{v} {v}")).collect(); + let _ = write!(out, " /MaskColor [{}]", mask.join(" ")); + } + let _ = writeln!(out, "\n/DataSource VCsrc {filter} filter >> {}\nVCsrc flushfile }} exec", if binary { "imagemask" } else { "image" }); + out.push_str(&ps::ascii85(&encoded)); + Some(out) + } + + /// Ink-setting operators in the cached stencil body, built with the same path as solid fills. + fn ink_code(&mut self, ink: Ink) -> String { + let body = std::mem::take(&mut self.body); + self.set_ink(ink); + std::mem::replace(&mut self.body, body) + } + /// Image `blob` as RGBA pixels; `None` (with a warning) when it can't be written. fn decode_image(&mut self, blob: Option<&ImageBlob>) -> Option<image::RgbaImage> { let Some(img) = blob.and_then(|blob| image::load_from_memory(&blob.bytes).ok()) else { diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 40eade3b59..c8271dda81 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -331,6 +331,187 @@ fn unpack(data: &[u8]) -> Vec<u8> { out } +fn colorized_doc(gray: Vec<u8>, paint: Option<Paint>) -> Document { + let mut d = Document::new(200.0, 200.0); + d.swatches.push(Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), global: true, spot: true }); + let mut png = Vec::new(); + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(gray.len() as u32, 1, gray).unwrap()) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + d.images.insert("gray".into(), ImageBlob::png(png)); + let im = ImageObject { + key: "gray".into(), + width: 3, + height: 1, + xf: Affine::translate((10.0, 10.0)) * Affine::scale(10.0), + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + n.extras_mut().colorize = paint.map(Box::new); + d.insert(d.default_layer(), 0, n).unwrap(); + d +} + +fn one_bit_blob() -> ImageBlob { + // Uncompressed two-pixel TIFF, BlackIsZero; black then white. + let entries: [(u16, u16, u32); 9] = + [(256, 3, 2), (257, 3, 1), (258, 3, 1), (259, 3, 1), (262, 3, 1), (273, 4, 122), (277, 3, 1), (278, 3, 1), (279, 4, 1)]; + let mut bytes = b"II*\0".to_vec(); + bytes.extend_from_slice(&8u32.to_le_bytes()); + bytes.extend_from_slice(&9u16.to_le_bytes()); + for (tag, kind, value) in entries { + bytes.extend_from_slice(&tag.to_le_bytes()); + bytes.extend_from_slice(&kind.to_le_bytes()); + bytes.extend_from_slice(&1u32.to_le_bytes()); + bytes.extend_from_slice(&value.to_le_bytes()); + } + bytes.extend_from_slice(&0u32.to_le_bytes()); + bytes.push(0b0100_0000); + ImageBlob::new("image/tiff", bytes) +} + +fn colorized_samples(d: &Document, level: Level) -> (String, Vec<u8>, Vec<String>) { + let out = export(d, &EpsOptions { level, ..opts(d) }, None, None).unwrap(); + let ps = text(&out); + checked_page(&ps); + let encoded = image_data(&ps); + let samples = if level == Level::Three { ps::inflate(&encoded, 1 << 20).unwrap() } else { unpack(&encoded) }; + (ps, samples, out.warnings) +} + +#[test] +fn binary_colorized_images_are_ink_stencils_at_both_levels() { + for (paint, setup) in [ + (Paint::solid(Color::rgb8(255, 0, 0)), "1 0 0 rg"), + (Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 0.5 }, "VCsp0 setcolorspace 0.5 setcolor"), + (Paint::registration(), "VCsp0 setcolorspace 1 setcolor"), + ] { + let d = colorized_doc(vec![0, 255, 0], Some(paint.clone())); + for level in [Level::Two, Level::Three] { + let (ps, samples, warnings) = colorized_samples(&d, level); + assert!(ps.contains("imagemask") && ps.contains("/BitsPerComponent 1 /Decode [1 0]"), "{ps}"); + assert!(ps.contains(setup), "{ps}"); + assert_eq!(samples, vec![0b1010_0000]); + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(ps.contains(if level == Level::Two { "/RunLengthDecode" } else { "/FlateDecode" })); + if matches!(paint, Paint::Solid { swatch: Some(_), .. }) { + assert!(ps.contains("/Separation")); + } + if paint.is_registration() { + assert!(ps.contains("/All /DeviceCMYK")); + assert!(dsc(&ps, "DocumentCustomColors").is_none()); + } else if matches!(paint, Paint::Solid { swatch: Some(_), .. }) { + assert_eq!(dsc(&ps, "DocumentCustomColors").as_deref(), Some("(Ink)")); + } + } + } +} + +#[test] +fn one_bit_source_uses_the_same_stencil_coverage() { + let mut d = colorized_doc(vec![0, 255, 255], Some(Paint::solid(Color::rgb8(0, 0, 255)))); + d.images.insert("gray".into(), one_bit_blob()); + let id = d.layers[0].children().unwrap()[0].id; + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.width = 2; + } + assert!(d.images["gray"].gray_source().unwrap().one_bit); + let (_, samples, warnings) = colorized_samples(&d, Level::Three); + assert_eq!(samples, vec![0b1000_0000]); + assert!(warnings.is_empty()); +} + +#[test] +fn one_source_with_two_spot_tints_writes_two_inks() { + let first = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 }; + let mut d = colorized_doc(vec![0, 255, 0], Some(first)); + let mut n = (*d.layers[0].children().unwrap()[0]).clone(); + n.id = d.alloc_id(); + n.extras_mut().colorize = Some(Box::new(Paint::Solid { color: Color::rgb8(255, 128, 128), swatch: Some("Ink".into()), tint: 0.5 })); + d.insert(d.default_layer(), 1, n).unwrap(); + let ps = page_of(&d, &opts(&d)); + assert!(ps.contains("VCsp0 setcolorspace 1 setcolor") && ps.contains("VCsp0 setcolorspace 0.5 setcolor"), "{ps}"); + assert_eq!(ps.matches("imagemask").count(), 2); +} + +#[test] +fn gray_colorized_ramp_scales_process_and_spot_inks_over_paper() { + for level in [Level::Two, Level::Three] { + let process = colorized_doc(vec![0, 128, 255], Some(Paint::solid(Color::rgb8(255, 0, 0)))); + let (ps, pixels, warnings) = colorized_samples(&process, level); + assert!(ps.contains("/DeviceRGB setcolorspace") && !ps.contains("imagemask")); + if level == Level::Three { + assert!(ps.contains("/ImageType 4") && ps.contains("/MaskColor [255 255 0 0 255 255]")); + assert_eq!(pixels, vec![255, 0, 0, 255, 128, 128, 255, 0, 255]); + assert_eq!(warnings, vec!["partly transparent image pixels are written over white"]); + } else { + assert!(ps.contains("/ImageType 1") && !ps.contains("/MaskColor")); + assert_eq!(pixels, vec![255, 0, 0, 255, 128, 128, 255, 255, 255]); + assert_eq!( + warnings, + vec![ + "partly transparent image pixels are written over white", + "transparent image pixels are written white at PostScript Level 2 (Level 3 masks them out)" + ] + ); + } + + let gray = colorized_doc(vec![0, 128, 255], Some(Paint::solid(Color::gray(0.5)))); + let (ps, pixels, warnings) = colorized_samples(&gray, level); + assert!(ps.contains("/DeviceGray setcolorspace")); + assert_eq!(pixels, if level == Level::Three { vec![128, 192, 0] } else { vec![128, 192, 255] }); + assert_eq!(ps.contains("/MaskColor [0 0]"), level == Level::Three); + assert_eq!(warnings.len(), if level == Level::Three { 1 } else { 2 }); + + let spot = colorized_doc(vec![0, 128, 255], Some(Paint::Solid { color: Color::rgb8(255, 128, 128), swatch: Some("Ink".into()), tint: 0.5 })); + let (ps, pixels, warnings) = colorized_samples(&spot, level); + assert!(ps.contains("/Separation (Ink) cvn") && ps.contains("VCsp0 setcolorspace")); + assert_eq!(dsc(&ps, "DocumentCustomColors").as_deref(), Some("(Ink)")); + assert_eq!(pixels, vec![128, 64, 0]); + assert_eq!(ps.contains("/MaskColor [0 0]"), level == Level::Three); + assert_eq!(warnings.len(), if level == Level::Three { 1 } else { 2 }); + + let mut cmyk = process.clone(); + cmyk.color_mode = vectorcraft_doc::ColorMode::Cmyk; + let (ps, pixels, _) = colorized_samples(&cmyk, level); + assert!(ps.contains("/DeviceCMYK setcolorspace")); + assert_eq!(pixels.len(), 12); + assert_eq!(&pixels[8..], if level == Level::Three { &[255, 0, 255, 0][..] } else { &[0, 0, 0, 0][..] }); + } +} + +#[test] +fn continuous_colorized_coverage_without_clear_pixels_only_warns_for_midtones() { + let d = colorized_doc(vec![0, 128, 254], Some(Paint::solid(Color::rgb8(255, 0, 255)))); + for level in [Level::Two, Level::Three] { + let (ps, pixels, warnings) = colorized_samples(&d, level); + assert!(ps.contains("/ImageType 1") && !ps.contains("/MaskColor")); + assert_eq!(&pixels[..3], &[255, 0, 255]); + assert_eq!(warnings, vec!["partly transparent image pixels are written over white"]); + } + let d = colorized_doc(vec![0, 128, 255], Some(Paint::solid(Color::rgb8(255, 0, 255)))); + let (ps, pixels, _) = colorized_samples(&d, Level::Three); + assert!(ps.contains("/MaskColor [255 255 0 0 255 255]")); + assert_eq!(&pixels[..3], &[255, 1, 255]); + assert_eq!(&pixels[6..], &[255, 0, 255]); +} + +#[test] +fn uncolorized_image_stays_on_original_eps_path() { + let d = colorized_doc(vec![0, 128, 255], None); + let ps = page_of(&d, &opts(&d)); + assert!(!ps.contains("imagemask") && ps.contains("/ImageType 1")); + let patterned = colorized_doc(vec![0, 128, 255], Some(Paint::Pattern { pattern: "missing".into(), xf: Affine::IDENTITY })); + assert_eq!(page_of(&patterned, &opts(&patterned)), ps); + let mut color = png_doc(); + let original = page_of(&color, &opts(&color)); + let id = color.layers[0].children().unwrap()[0].id; + color.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + assert_eq!(page_of(&color, &opts(&color)), original); +} + #[test] fn run_length_and_ascii85_round_trip() { let cycle: Vec<u8> = (0..=255u8).cycle().take(1000).collect(); diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 27be13e207..6ef3b64ddf 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -34,7 +34,7 @@ svgtypes = "0.16" skrifa = { workspace = true } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } -resvg = { version = "0.45", default-features = false } +resvg = { version = "0.45", default-features = false, features = ["raster-images"] } # usvg as a reference viewer that lays text out in a font (text_layout.rs). usvg = { workspace = true, features = ["text"] } vectorcraft-testkit = { workspace = true } diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index 1da24959ca..b9cd372eae 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -107,11 +107,17 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: symbol_nest: 0, fonts: Vec::new(), shared_images: HashMap::new(), + colorized_counts: HashMap::new(), + colorized_hrefs: HashMap::new(), + shared_colorized: HashMap::new(), layer_nest: 0, non_latin1_names: false, foreign_ns: BTreeMap::new(), }; w.assign_name_ids(); + for layer in &doc.layers { + w.count_colorized_images(layer); + } // Page Isolated Blending / Page Knockout Group: the page content is one isolated group. let page_group = doc.page_isolate || doc.page_knockout; if page_group { @@ -216,6 +222,8 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: Output { svg: out, linked: w.linked, warnings: w.warnings, encoding } } +type ColorizedKey = (String, u32, u32, Option<[u8; 3]>); + struct Writer<'a> { doc: &'a Document, opts: &'a ExportOptions, @@ -268,6 +276,10 @@ struct Writer<'a> { /// Images written once in the defs and drawn with `<use>`, by key and size: the pieces an /// envelope cuts a distorted image into share its pixels. shared_images: HashMap<(String, u32, u32), String>, + /// Counts and generated PNG hrefs for gray images, keyed by source, size and baked RGB. + colorized_counts: HashMap<ColorizedKey, usize>, + colorized_hrefs: HashMap<ColorizedKey, String>, + shared_colorized: HashMap<ColorizedKey, String>, /// Layers being written inside one another (more than one: a sublayer). layer_nest: usize, /// An emitted attribute name requires an encoding wider than Latin-1. diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index 16722d9395..e88ad85098 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -117,6 +117,7 @@ fn pin_to_page(n: &mut Node, m: Affine) { /// What SVG Tiny 1.2 does without masks. const TINY_MASKS: &str = "SVG Tiny 1.2 has no masks: opacity masks are left out and knockout groups written as plain groups"; +pub(super) const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; /// A region covering any artwork (mask and filter extents). const BIG: &str = "x=\"-100000\" y=\"-100000\" width=\"200000\" height=\"200000\""; @@ -565,6 +566,18 @@ impl Writer<'_> { } NodeKind::Text(t) => self.text_node(n, t), NodeKind::Image(im) => { + if let Some(Paint::Solid { color, .. }) = n.extras().colorize.as_deref() + && let Some(blob) = self.doc.image_blob(im) + && blob.gray_source().is_some() + { + self.colorized_image(n, im, *color, blob); + return; + } + if matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. })) && self.doc.image_blob(im).is_none_or(|b| b.bytes.is_empty()) { + // Missing pixels cannot show the original file in place of a colorized image. + self.warn(UNDECODED); + return; + } let id = self.id_attr(n); let m = self.matrix(self.xf * im.xf); let mut props = css::transparency(n); diff --git a/crates/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index b21d45eb62..462387d70f 100644 --- a/crates/svg/src/export/paint.rs +++ b/crates/svg/src/export/paint.rs @@ -1,9 +1,9 @@ -use super::nodes::{MASK, doc_path}; +use super::nodes::{MASK, UNDECODED, doc_path}; use super::output::sanitize_id; use super::{ Affine, BezPath, BlendMode, Color, FillLayer, FillRule, GradientKind, GradientPaint, HashMap, ImageBlob, ImageMode, LineCap, LineJoin, - LinkedImage, Node, NodeKind, Paint, PathData, Point, Props, Rect, StrokeAlign, StrokeLayer, Writer, Written, base64_encode, blend_css, fmt_num, - stroke, xml_escape, + LinkedImage, Node, NodeKind, Paint, PathData, Point, Props, Rect, StrokeAlign, StrokeLayer, Writer, Written, base64_encode, blend_css, css, + fmt_num, stroke, xml_escape, }; /// Image `b` as SVG viewers show it: PNG, JPEG, GIF, WebP and SVG as they are, other formats (a @@ -38,6 +38,125 @@ pub(super) enum StrokePlan { } impl Writer<'_> { + pub(super) fn count_colorized_images(&mut self, art: &Node) { + art.walk(&mut |n| { + let NodeKind::Image(im) = &n.kind else { return }; + let Some(Paint::Solid { color, .. }) = n.extras().colorize.as_deref() else { return }; + if self.doc.image_blob(im).is_none_or(|blob| blob.gray_source().is_none()) { + return; + } + let key = self.colorized_key(im, *color); + *self.colorized_counts.entry(key).or_default() += 1; + }); + } + + fn colorized_key(&self, im: &vectorcraft_doc::ImageObject, color: Color) -> super::ColorizedKey { + let rgb = color.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + (im.key.clone(), im.width, im.height, self.tiny().then_some(rgb)) + } + + /// Colorize the decoded gray pixels without changing the source blob. The white pixels of the + /// coverage image contribute their alpha to an alpha mask; Tiny uses the same alpha in RGBA. + pub(super) fn colorized_image(&mut self, n: &Node, im: &vectorcraft_doc::ImageObject, color: Color, blob: &ImageBlob) { + let key = self.colorized_key(im, color); + let rgb = color.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + let href = if let Some(href) = self.colorized_hrefs.get(&key) { + href.clone() + } else { + let Some((width, height, coverage)) = blob.coverage() else { + self.warn(UNDECODED); + return; + }; + if u64::from(width) + .checked_mul(u64::from(height)) + .and_then(|pixels| pixels.checked_mul(4)) + .is_none_or(|bytes| bytes > vectorcraft_doc::MAX_RASTER_ALLOC) + { + self.warn(UNDECODED); + return; + } + let mut rgba = Vec::with_capacity(coverage.len().saturating_mul(4)); + for alpha in coverage { + rgba.extend_from_slice(&if self.tiny() { [rgb[0], rgb[1], rgb[2], alpha] } else { [255, 255, 255, alpha] }); + } + let Some(pixels) = image::RgbaImage::from_raw(width, height, rgba) else { + self.warn(UNDECODED); + return; + }; + let mut png = Vec::new(); + if pixels.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() { + self.warn(UNDECODED); + return; + } + let href = self.blob_href(&ImageBlob::png(png)); + self.colorized_hrefs.insert(key.clone(), href.clone()); + href + }; + let shared = if self.opts.images == ImageMode::Embed && self.colorized_counts.get(&key).is_some_and(|count| *count > 1) { + if let Some(id) = self.shared_colorized.get(&key) { + Some(id.clone()) + } else { + let id = self.fresh_id("colorize-image"); + self.def( + 0, + &format!( + "<image id=\"{id}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" xlink:href=\"{}\"/>", + im.width, + im.height, + xml_escape(&href) + ), + ); + self.shared_colorized.insert(key, id.clone()); + Some(id) + } + } else { + None + }; + let id = self.id_attr(n); + let transform = self.matrix(self.xf * im.xf); + let outer = self.attrs(&css::transparency(n)); + let sampling = if n.extras().pixelated { " image-rendering=\"pixelated\"" } else { "" }; + if self.tiny() { + if let Some(shared) = shared { + self.line(&format!("<use{id} transform=\"{transform}\"{outer}{sampling} xlink:href=\"#{shared}\"/>")); + } else { + self.line(&format!( + "<image{id} width=\"{}\" height=\"{}\" transform=\"{transform}\" preserveAspectRatio=\"none\"{outer}{sampling} xlink:href=\"{}\"/>", + im.width, im.height, xml_escape(&href) + )); + } + return; + } + let mask = self.fresh_id("colorize-mask"); + let size = Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)); + let b = (self.xf * im.xf).transform_rect_bbox(size).inflate(1.0, 1.0); + let (x, y, w, h) = (self.num(b.x0), self.num(b.y0), self.num(b.width()), self.num(b.height())); + self.def(1, &format!("<mask id=\"{mask}\" {MASK} mask-type=\"alpha\" x=\"{x}\" y=\"{y}\" width=\"{w}\" height=\"{h}\">")); + if let Some(shared) = shared { + self.def(2, &format!("<use transform=\"{transform}\"{sampling} xlink:href=\"#{shared}\"/>")); + } else { + self.def( + 2, + &format!( + "<image width=\"{}\" height=\"{}\" transform=\"{transform}\" preserveAspectRatio=\"none\"{sampling} xlink:href=\"{}\"/>", + im.width, + im.height, + xml_escape(&href) + ), + ); + } + self.def(1, "</mask>"); + self.line(&format!("<g{id} mask=\"url(#{mask})\"{outer}>")); + self.depth += 1; + self.line(&format!("<g transform=\"{transform}\">")); + self.depth += 1; + self.line(&format!("<rect width=\"{}\" height=\"{}\" fill=\"{}\"{sampling}/>", im.width, im.height, color.to_hex())); + self.depth -= 1; + self.line("</g>"); + self.depth -= 1; + self.line("</g>"); + } + /// The `href` of image `im`: its file with [`ImageMode::Link`] (or when its pixels are /// missing), else its bytes. `None` when it has neither. pub(super) fn image_href(&mut self, im: &vectorcraft_doc::ImageObject) -> Option<String> { @@ -52,10 +171,16 @@ impl Writer<'_> { /// Images drawn more than once in `art` (the pieces of a distorted image) go into the defs /// once; each piece then draws them with `<use>`. pub(super) fn share_images(&mut self, art: &Node) { + self.count_colorized_images(art); // Each image's count and its first piece, which shows what they all show. let mut seen: HashMap<(String, u32, u32), (usize, vectorcraft_doc::ImageObject)> = HashMap::new(); art.walk(&mut |c| { if let NodeKind::Image(im) = &c.kind { + if matches!(c.extras().colorize.as_deref(), Some(Paint::Solid { .. })) + && self.doc.image_blob(im).is_none_or(|b| b.gray_source().is_some()) + { + return; + } seen.entry((im.key.clone(), im.width, im.height)).or_insert_with(|| (0, (**im).clone())).0 += 1; } }); diff --git a/crates/svg/tests/it/colorized_images.rs b/crates/svg/tests/it/colorized_images.rs new file mode 100644 index 0000000000..d3590977f2 --- /dev/null +++ b/crates/svg/tests/it/colorized_images.rs @@ -0,0 +1,229 @@ +//! Colorized gray and bilevel image export, checked as pixels as well as markup. + +use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_doc::{Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind}; +use vectorcraft_geom::Affine; +use vectorcraft_svg::{ExportOptions, ImageMode, Profile, base64_encode, export_full}; + +fn bilevel() -> Vec<u8> { + let entries: [(u16, u16, u32); 9] = + [(256, 3, 2), (257, 3, 1), (258, 3, 1), (259, 3, 1), (262, 3, 1), (273, 4, 122), (277, 3, 1), (278, 3, 1), (279, 4, 1)]; + let mut out = b"II*\0".to_vec(); + out.extend_from_slice(&8u32.to_le_bytes()); + out.extend_from_slice(&9u16.to_le_bytes()); + for (tag, kind, value) in entries { + out.extend_from_slice(&tag.to_le_bytes()); + out.extend_from_slice(&kind.to_le_bytes()); + out.extend_from_slice(&1u32.to_le_bytes()); + out.extend_from_slice(&value.to_le_bytes()); + } + out.extend_from_slice(&0u32.to_le_bytes()); + out.push(0b0100_0000); + out +} + +fn png(img: image::DynamicImage) -> Vec<u8> { + let mut out = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +fn document(bytes: Vec<u8>, paint: Option<Paint>) -> Document { + let mut d = Document::new(80.0, 40.0); + d.swatches.push(Swatch { name: "Ink".into(), paint: Paint::solid(Color::rgb8(255, 0, 0)), global: true, spot: true }); + d.images.insert("source".into(), ImageBlob::new("image/tiff", bytes)); + let im = ImageObject { + key: "source".into(), + width: 2, + height: 1, + xf: Affine::translate((10.0, 10.0)) * Affine::scale(20.0), + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + n.extras_mut().pixelated = true; + n.extras_mut().colorize = paint.map(Box::new); + d.insert(d.default_layer(), 0, n).unwrap(); + d +} + +fn rendered(svg: &str) -> ([u8; 4], [u8; 4]) { + let tree = resvg::usvg::Tree::from_str(svg, &resvg::usvg::Options::default()).unwrap(); + let mut pixmap = resvg::tiny_skia::Pixmap::new(80, 40).unwrap(); + pixmap.fill(resvg::tiny_skia::Color::WHITE); + resvg::render(&tree, resvg::tiny_skia::Transform::identity(), &mut pixmap.as_mut()); + let sample = |x| { + let p = pixmap.pixel(x, 15).unwrap().demultiply(); + [p.red(), p.green(), p.blue(), p.alpha()] + }; + (sample(15), sample(45)) +} + +fn samples(svg: &str, points: &[(u32, u32)]) -> Vec<[u8; 4]> { + let tree = resvg::usvg::Tree::from_str(svg, &resvg::usvg::Options::default()).unwrap(); + let mut pixmap = resvg::tiny_skia::Pixmap::new(80, 40).unwrap(); + pixmap.fill(resvg::tiny_skia::Color::WHITE); + resvg::render(&tree, resvg::tiny_skia::Transform::identity(), &mut pixmap.as_mut()); + points + .iter() + .map(|&(x, y)| { + let p = pixmap.pixel(x, y).unwrap().demultiply(); + [p.red(), p.green(), p.blue(), p.alpha()] + }) + .collect() +} + +#[test] +fn repeated_colorized_source_shares_coverage_but_keeps_instance_paint() { + let mut d = document(bilevel(), Some(Paint::solid(Color::rgb8(255, 0, 0)))); + let first_id = d.layers[0].children().unwrap()[0].id; + if let NodeKind::Image(im) = &mut d.node_mut(first_id).unwrap().kind { + im.xf = Affine::translate((10.0, 10.0)) * Affine::scale(10.0); + } + for (i, color) in [(1, Color::rgb8(0, 0, 255)), (2, Color::rgb8(255, 0, 0))] { + let mut next = (*d.layers[0].children().unwrap()[0]).clone(); + next.id = d.alloc_id(); + next.extras_mut().colorize = Some(Box::new(Paint::solid(color))); + if let NodeKind::Image(im) = &mut next.kind { + im.xf = Affine::translate((10.0 + f64::from(i) * 25.0, 10.0)) * Affine::scale(10.0); + } + d.insert(d.default_layer(), i as usize, next).unwrap(); + } + for profile in [Profile::Svg11, Profile::Tiny12] { + let svg = export_full(&d, &ExportOptions { profile, artboard: Some(0), ..Default::default() }, None).svg; + let png_count = svg.matches("data:image/png;base64,").count(); + assert_eq!(png_count, if profile == Profile::Svg11 { 1 } else { 2 }, "{svg}"); + assert_eq!(svg.matches("<use").count(), if profile == Profile::Svg11 { 3 } else { 2 }, "{svg}"); + let actual = samples(&svg, &[(15, 15), (25, 15), (40, 15), (50, 15), (65, 15), (75, 15)]); + let expected: [[u8; 4]; 6] = [[255, 0, 0, 255], [255; 4], [0, 0, 255, 255], [255; 4], [255, 0, 0, 255], [255; 4]]; + for (got, want) in actual.iter().zip(expected) { + assert!(got.iter().zip(want).all(|(&a, b)| i16::from(a).abs_diff(i16::from(b)) <= 25), "{actual:?}\n{svg}"); + } + } +} + +#[test] +fn colorize_mask_region_follows_an_image_far_from_the_origin() { + let mut d = document(bilevel(), Some(Paint::solid(Color::rgb8(255, 0, 0)))); + let id = d.layers[0].children().unwrap()[0].id; + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.xf = Affine::translate((200_010.0, 10.0)) * Affine::scale(20.0); + } + let svg = export_full(&d, &ExportOptions::default(), None).svg; + let mask = svg.lines().find(|l| l.contains("<mask id=\"colorize-mask")).unwrap(); + assert!(mask.contains("x=\"200009\" y=\"9\" width=\"42\" height=\"22\""), "{mask}"); +} + +#[test] +fn bilevel_process_and_spot_use_coverage_in_embed_link_and_tiny() { + let paints = [Paint::solid(Color::rgb8(255, 0, 0)), Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 }]; + for paint in paints { + let d = document(bilevel(), Some(paint)); + for profile in [Profile::Svg11, Profile::Tiny12] { + let opts = ExportOptions { profile, artboard: Some(0), ..Default::default() }; + let embedded = export_full(&d, &opts, None); + assert_eq!(rendered(&embedded.svg), ([255, 0, 0, 255], [255, 255, 255, 255]), "{}", embedded.svg); + assert!(!embedded.svg.contains("colorize-image"), "single images stay inline"); + assert_eq!(embedded.svg.contains("<mask id=\"colorize-mask"), profile == Profile::Svg11); + assert!(embedded.svg.contains("image-rendering=\"pixelated\"")); + let linked = export_full(&d, &ExportOptions { images: ImageMode::Link, ..opts }, None); + assert_eq!(linked.linked.len(), 1); + let file = &linked.linked[0]; + assert!(linked.svg.contains(&file.name)); + let rgba = image::load_from_memory(&file.bytes).unwrap().to_rgba8(); + assert_eq!((rgba.get_pixel(0, 0).0[3], rgba.get_pixel(1, 0).0[3]), (255, 0)); + let inlined = linked.svg.replace(&file.name, &format!("data:image/png;base64,{}", base64_encode(&file.bytes))); + assert_eq!(rendered(&inlined), rendered(&embedded.svg)); + } + } +} + +#[test] +fn gray_alpha_and_two_spot_tints_keep_distinct_colors() { + let bytes = png(image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(2, 1, vec![0, 128, 128, 255]).unwrap())); + let mut d = document(bytes, Some(Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 })); + let mut second = (*d.layers[0].children().unwrap()[0]).clone(); + second.id = d.alloc_id(); + second.extras_mut().colorize = Some(Box::new(Paint::Solid { color: Color::rgb8(255, 128, 128), swatch: Some("Ink".into()), tint: 0.5 })); + if let NodeKind::Image(im) = &mut second.kind { + im.xf = Affine::translate((10.0, 25.0)) * Affine::scale(10.0); + } + d.insert(d.default_layer(), 1, second).unwrap(); + let svg = export_full(&d, &ExportOptions { artboard: Some(0), ..Default::default() }, None).svg; + assert_eq!(svg.matches("<mask id=\"colorize-mask").count(), 2); + assert!(svg.contains("#ff0000") && svg.contains("#ff8080"), "{svg}"); + let linked = export_full(&d, &ExportOptions { images: ImageMode::Link, artboard: Some(0), ..Default::default() }, None); + assert_eq!(linked.linked.len(), 1, "both tints use one coverage PNG"); + assert_eq!(linked.svg.matches(&linked.linked[0].name).count(), 2); + let (a, b) = rendered(&svg); + assert!((a[1] as i16 - 127).abs() <= 2 && (b[1] as i16 - 128).abs() <= 2, "{a:?} {b:?}"); +} + +#[test] +fn gray_midtone_uses_process_cmyk_display_color() { + let color = Color::cmyk(0.2, 0.7, 0.1, 0.1); + let bytes = png(image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![128, 255]).unwrap())); + let d = document(bytes, Some(Paint::solid(color))); + let out = export_full(&d, &ExportOptions { artboard: Some(0), ..Default::default() }, None); + let (actual, white) = rendered(&out.svg); + let rgb = color.to_rgb(); + let expected = rgb.map(|v| (255.0 * (1.0 - 127.0 / 255.0 + v.clamp(0.0, 1.0) * 127.0 / 255.0)).round() as u8); + for i in 0..3 { + assert!((i16::from(actual[i]) - i16::from(expected[i])).abs() <= 2, "{actual:?}, expected {expected:?}"); + } + assert_eq!(white, [255; 4]); + assert!(out.warnings.is_empty()); +} + +#[test] +fn uncolorized_and_color_image_controls_keep_original_paths() { + let gray = document(bilevel(), None); + let svg = export_full(&gray, &ExportOptions { artboard: Some(0), ..Default::default() }, None).svg; + assert!(!svg.contains("colorize-mask") && svg.contains("<image")); + let patterned = document(bilevel(), Some(Paint::Pattern { pattern: "missing".into(), xf: Affine::IDENTITY })); + assert_eq!(export_full(&patterned, &ExportOptions { artboard: Some(0), ..Default::default() }, None).svg, svg); + let color = png(image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(2, 1, vec![0, 0, 255, 0, 255, 0]).unwrap())); + let mut d = document(color, None); + d.images.get_mut("source").unwrap().mime = "image/png".into(); + let before = export_full(&d, &ExportOptions { artboard: Some(0), ..Default::default() }, None).svg; + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + assert_eq!(export_full(&d, &ExportOptions { artboard: Some(0), ..Default::default() }, None).svg, before); + // Pixels that aren't grayscale (an embedded SVG, unknown bytes) keep the uncolorized path. + let svg_source = br#"<svg xmlns="http://www.w3.org/2000/svg" width="2" height="1"><rect width="2" height="1" fill="blue"/></svg>"#.to_vec(); + for (bytes, mime) in [(svg_source, "image/svg+xml"), (vec![1, 2, 3], "image/tiff")] { + let mut d = document(bytes, None); + d.images.get_mut("source").unwrap().mime = mime.into(); + let before = export_full(&d, &ExportOptions { artboard: Some(0), ..Default::default() }, None); + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + let after = export_full(&d, &ExportOptions { artboard: Some(0), ..Default::default() }, None); + assert!(after.svg.contains("<image"), "{mime}"); + assert_eq!((after.svg, after.warnings), (before.svg, before.warnings), "{mime}"); + } + + let mut truncated = bilevel(); + truncated.pop(); // Keep the TIFF header, but remove its pixel data. + let damaged = document(truncated, Some(Paint::solid(Color::rgb8(255, 0, 0)))); + assert!(damaged.images["source"].gray_source().is_some()); + let out = export_full(&damaged, &ExportOptions { artboard: Some(0), ..Default::default() }, None); + assert!(!out.svg.contains("<image")); + assert_eq!(out.warnings, ["an image couldn't be decoded and is missing from the picture"]); + + let mut missing = document(bilevel(), Some(Paint::solid(Color::rgb8(255, 0, 0)))); + missing.images.remove("source"); + let id = missing.layers[0].children().unwrap()[0].id; + if let NodeKind::Image(im) = &mut missing.node_mut(id).unwrap().kind { + im.link = Some(LinkInfo::new("/original/gray.tiff")); + } + let out = export_full(&missing, &ExportOptions { artboard: Some(0), images: ImageMode::Link, ..Default::default() }, None); + assert!(!out.svg.contains("/original/gray.tiff") && !out.svg.contains("<image")); + assert!(out.linked.is_empty()); + assert_eq!(out.warnings, ["an image couldn't be decoded and is missing from the picture"]); + + missing.images.insert("source".into(), ImageBlob::new("image/tiff", vec![])); + let out = export_full(&missing, &ExportOptions { artboard: Some(0), ..Default::default() }, None); + assert!(!out.svg.contains("/original/gray.tiff") && !out.svg.contains("<image")); + assert_eq!(out.warnings, ["an image couldn't be decoded and is missing from the picture"]); +} diff --git a/crates/svg/tests/it/main.rs b/crates/svg/tests/it/main.rs index 3e554a3977..3605bd014d 100644 --- a/crates/svg/tests/it/main.rs +++ b/crates/svg/tests/it/main.rs @@ -4,6 +4,7 @@ mod basic_shapes; mod blend_export; +mod colorized_images; mod colour_glyphs; mod container_export; mod css_rules; diff --git a/docs/mcp.md b/docs/mcp.md index 35bf8314b2..89afecd0dd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -585,6 +585,7 @@ font whose licence (OS/2 `fsType`) forbids subsetting is embedded whole, one tha with a warning. Type names its faces by numeric `font-weight` (600 for Semibold and for a Japanese face's W6, 300 for Light, `bold` for 700), embedded or not. `svgz` takes the same options and writes the SVG gzipped (`.svgz` files also open, place and paste). `run_command document.save {path: "x.svg", svg: {…}}` saves as SVG (or `.svgz`). +Colorized grayscale and 1-bit images export in their fill color; linked mode writes a coverage PNG, and Tiny 1.2 writes a colorized PNG. Symbols export as one `<symbol>` with a `<use>` per instance. An instance the def can't stand for is written as its own art: one stained by its fill; one scaled while the symbol has strokes (their weight doesn't scale), or rotated or @@ -4038,6 +4039,7 @@ is accepted); spot colours are Separation colour spaces, and overprinting fills `overprints: "discard"`. RGB documents are written in CMYK unless `cmykPostScript: false`. When the file would hold an image that can't be decoded, the image is left out, and `warnings` carries "an image couldn't be decoded and is missing from the picture" once for all such images. +Colorized grayscale and 1-bit images use their process or spot ink; the flattener leaves them alone unless they have opacity, a blending mode, an opacity mask or effects, or overlap other transparent art. Binary coverage leaves underlying art untouched. For a grayscale image, Level 3 leaves white (zero-coverage) pixels out, Level 2 writes them white, and gray midtones are written over white at both levels. PostScript has no transparency: it is flattened first with `flattenerPreset` (`high`, `medium` (default), `low` or a saved preset, see `flattener.presets.list`) and `flattener: {…}` options over it (those of diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0699ef5bc6..e7e1bbc5f6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -927,6 +927,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **CSS swatch libraries:** fractional linear and radial gradient stop positions are preserved, so nearby stops such as 12.5% and 12.890625% remain distinct instead of collapsing to 13%. Reference: [CSS Images 3 color stops](https://www.w3.org/TR/css-images-3/#color-stop-syntax). The original synthetic regression is `palette_io::tests::css_preserves_fractional_gradient_stop_positions` in `crates/color/src/palette_io.rs`. Scores and hours are unchanged. - **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate. Editing, renaming, deleting or merging a global swatch also changes the colors linked to it in graph designs, the art of brushes and the tile that pattern editing's Cancel puts back, in the same undo step as the rest of the art; Default Swatches with replace unlinks them there too. + - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. SVG writes the fill color through a coverage mask (or a colorized PNG in Tiny 1.2); EPS writes binary coverage as an image mask in the color's ink, and a grayscale image as ink samples scaled by coverage, with white pixels left out at Level 3 and gray midtones written over white. The prompt for deleting several swatches and groups uses the interface language's plural form for the count. Evidence: `deleting_several_swatches_uses_each_count_form` in `crates/ui-egui/src/panels/swatches/tests.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels. - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. From d6297dbfb9ed13dbe71f1c924acc91d489a02fb8 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 1 Nov 2026 00:35:35 +0700 Subject: [PATCH 114/260] .ai import: type comes from the text document alone when every shown story reads Squashed from #4865 onto main. --- crates/engine/tests/import_fuzz.rs | 117 +++++++ crates/eps/src/import/ate.rs | 38 ++- crates/eps/src/import/native.rs | 49 ++- crates/eps/src/import/native/build.rs | 79 +++-- crates/eps/src/import/native/compare.rs | 135 ++++++-- crates/eps/src/import/native/plan.rs | 316 +++++++++++++------ crates/eps/src/import/native/slots.rs | 41 +-- crates/eps/src/import/tests_native.rs | 402 +++++++++++++++++++++--- docs/file-format-parity.md | 3 +- docs/target-app-parity.md | 5 +- 10 files changed, 962 insertions(+), 223 deletions(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 0f096b62ad..12eaf13d64 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -2784,9 +2784,126 @@ fn text_eps_of(document: &str, objects: &str) -> Vec<u8> { editing_eps(&editing) } +/// A text document of `kinds.len()` stories, story `i` in frame `i` of kind `kinds[i]` (0 point type, +/// 1 area type, 2 type on a path, others a kind the reader doesn't know), with a line break inside +/// its paragraph (`\x03`) at each of `soft` (by character, wrapping, the story's end included) and +/// its paragraph runs `runs` characters long (the whole story when there are none). +fn stories_document_text(kinds: &[u8], soft: &[usize], runs: &[usize]) -> String { + let frames: Vec<String> = kinds + .iter() + .enumerate() + .map(|(i, kind)| { + // Six rows 15 apart on the page (the canvas is y down), then the same rows again a little + // to the right. + let (x, y) = (8150.0 + (i / 6) as f64 * 5.0, 8150.0 + (i % 6) as f64 * 15.0); + match kind { + 0 => format!("<< /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 {x} {y} ] >> >> >>"), + 1 => format!( + "<< /0 << /0 [ 0 0 ] /1 << /0 [ {x} {y} {x} {y} {0} {y} {0} {y} {0} {y} {0} {y} {0} {1} {0} {1} {0} {1} {0} {1} {x} {1} {x} {1} ] >> /2 << /0 1 >> >> >>", + x + 70.0, + y + 12.0 + ), + 2 => format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {x} {y} {x} {y} {0} {y} {0} {y} ] >> /2 << /0 2 /6 [ 0 0.9 ] >> >> >>", x + 70.0), + k => format!("<< /0 << /0 [ 0 0 ] /2 << /0 {k} /2 [ 1 0 0 1 {x} {y} ] >> >> >>"), + } + }) + .collect(); + let stories: Vec<String> = (0..kinds.len()) + .map(|i| { + let mut chars: Vec<char> = format!("Line {i} one two\rand three\r").chars().collect(); + for at in soft { + chars.insert(at % (chars.len() + 1), '\x03'); + } + let n = chars.len(); + let text: String = chars.iter().map(|c| match c { + '\r' => "\\r".to_string(), + '\x03' => "\\003".to_string(), + c => c.to_string(), + }).collect(); + let lengths: Vec<usize> = if runs.is_empty() { vec![n] } else { runs.to_vec() }; + let paras: String = lengths + .iter() + .enumerate() + .map(|(j, len)| format!("<< /0 << /0 << /0 () /5 << /0 {} /2 2 /4 {j} >> /6 0 >> >> /1 {len} >> ", j % 3)) + .collect(); + format!( + "<< /0 << /0 ({text}) /5 << /0 [ {paras}] >> /6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /1 8.0 >> >> >> /1 {n} >> ] >> >> /1 << /0 [ << /0 {i} >> ] >> >>" + ) + }) + .collect(); + format!( + "/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> /8 << /0 [ {} ] >> >>\n/1 << /1 [ {} ] /2 << /1 12.0 >> >>\n", + frames.join(" "), + stories.join(" ") + ) +} + +/// An EPS whose page draws `page` (PostScript), with the text `objects` on a layer that shows and +/// the stories in `document`. +fn shown_text_eps(document: &str, objects: &str, page: &str) -> Vec<u8> { + let lines: Vec<String> = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); + let editing = format!( + "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI3_TemplateBox: 50 50 50 50\n\ + %AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(Words) Ln\n{objects}LB\n%AI5_EndLayer--\n\ + %AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n%%Trailer\n", + lines.join("\n") + ); + let stream = ascii85(&zstd(&editing)); + let private: Vec<String> = stream.as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); + format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n0 0 0 1 setcmykcolor /Helvetica findfont 8 scalefont setfont {page}\nshowpage\n%%EOF\n%AI9_PrivateDataBegin\n%AI24_DataStream\n{}\n%AI9_PrivateDataEnd\n", + private.join("\n") + ) + .into_bytes() +} + +/// The page of [`stories_document_text`]'s first story's first line, at its place. +const FIRST_LINE: &str = "8.5 91.5 moveto (Line 0 one two) show"; + +/// The text objects of `pairs` (story, frame among the story's). +fn story_objects(pairs: &[(u32, u32)]) -> String { + pairs.iter().map(|(story, frame)| format!("/AI11Text :\n{frame} /FrameIndex ,\n{story} /StoryIndex ,\n;\n")).collect() +} + +/// The fixture, as it is (point type, area type and type on a path, a line break inside each +/// paragraph), opens with its layers and every story's type from its text document. +#[test] +fn the_shown_stories_fixture_opens_with_its_layers() { + let doc = stories_document_text(&[0, 1, 2], &[4], &[]); + // Each story's first line where the page draws it: the area type's below its frame's top, the + // type on a path on its path. + let page = format!("{FIRST_LINE} 8.5 69.5 moveto (Line 1) show 8.5 61.5 moveto (Line 2) show"); + let l = vectorcraft_engine::cmd::fileio::load("x.eps", &shown_text_eps(&doc, &story_objects(&[(0, 0), (1, 0), (2, 0)]), &page)).unwrap(); + let names: Vec<_> = l.doc.layers.iter().map(|l| l.name.clone()).collect(); + assert_eq!(names, [Some("Words".to_string())], "{:?}", l.warnings); + let mut texts = vec![]; + l.doc.walk(|n| { + if let vectorcraft_doc::NodeKind::Text(t) = &n.kind { + texts.push(t.plain_text()); + } + }); + assert_eq!(texts.len(), 3, "{texts:?} {:?}", l.warnings); + assert!(texts.iter().all(|t| t.contains('\u{2028}') && t.contains('\n')), "{texts:?}"); +} + proptest! { #![proptest_config(config())] + /// An Illustrator EPS with text objects that show, in frames of every kind and some the reader + /// doesn't know, naming stories and frames that may not exist, with line breaks inside their + /// paragraphs and paragraph runs of any length: read as its layers, or as its page. + #[test] + fn eps_shown_stories_never_panic( + kinds in prop::collection::vec(0u8..4, 1..20), + pairs in prop::collection::vec((0u32..24, 0u32..3), 1..24), + soft in prop::collection::vec(0usize..40, 0..5), + runs in prop::collection::vec(0usize..40, 0..5), + ) { + let kinds: Vec<u8> = kinds.into_iter().map(|k| if k == 3 { 9 } else { k }).collect(); + let bytes = shown_text_eps(&stories_document_text(&kinds, &soft, &runs), &story_objects(&pairs), FIRST_LINE); + survive("EPS with shown stories", || vectorcraft_engine::cmd::fileio::load("x.eps", &bytes).ok().map(|l| l.doc))?; + } + /// An Illustrator EPS whose text document is damaged or hostile: read as its type, or without it. #[test] fn eps_text_document_never_panics(cut in 0usize..1_500, edits in prop::collection::vec((0usize..1_500, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', '[', ']', '<', '>', '\\', 'e', '1'])), 0..12)) { diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 6ad647cad3..60273bb508 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -8,9 +8,9 @@ //! The format isn't documented. What is read here was worked out from the files of the project's //! users, used locally and never committed, by comparing it with the type their pages draw: the //! meaning of each key below was checked against the page's own type in more than a thousand text -//! objects, and it is only used for the keys that matched. A story the reader doesn't recognise (area -//! type, type on a path, anything with a frame that has more than a point and a matrix) is left -//! alone: it has no text, and the importer says so. +//! objects, and it is only used for the keys that matched. Point type, area type and type on a path +//! are read; a story in a frame of any other kind is left alone: it has no text, and the importer +//! says so. //! //! Where type sits: a story lays its lines out round a point `F` (the anchor: the start of a line of //! left-aligned type, the middle of a centred one, the end of a right-aligned one), each line with an @@ -654,11 +654,6 @@ impl Story { self.text.len() } - /// The story's characters, with `\r` ending paragraphs and `\x03` ending lines. - pub(super) fn text(&self) -> &str { - &self.text - } - /// The point frame's matrix (the first frame's, when it is one), else the identity. fn matrix(&self) -> [f64; 6] { match self.frames.first() { @@ -749,10 +744,20 @@ impl Story { (1.0, Affine::IDENTITY, TextKind::OnPath { path: path_of(segments, template, to_doc), start: length_fraction(segments, *start), end }) } }; + // A `\x03` ends a line inside its paragraph: a forced line break (U+2028), which the + // paragraph's style runs over. let text: String = if threaded { String::new() } else { - self.text.trim_end_matches('\r').chars().map(|c| if matches!(c, '\r' | '\x03') { '\n' } else { c }).collect() + self.text + .trim_end_matches('\r') + .chars() + .map(|c| match c { + '\r' => '\n', + '\x03' => '\u{2028}', + c => c, + }) + .collect() }; if text.trim().is_empty() && !threaded { return None; @@ -1253,6 +1258,21 @@ mod tests { assert_eq!(story("one\r", &[0.0], &Para::default()).line_leading(1.0), None); } + /// A `\x03` ends a line inside its paragraph: it comes in as a forced line break, and the + /// paragraph's style runs over it to the paragraph's end. + #[test] + fn a_soft_return_is_a_line_break_in_its_paragraph() { + let para = Para { space_before: 4.0, space_after: 2.0, first_indent: 6.0, ..Para::default() }; + let mut s = story("A\x03B\rC\r", &[0.0, 15.6, 31.2], ¶); + s.paras[1].1 = Para { left_indent: 3.0, ..para.clone() }; + let node = s.node(NodeId(1), 0, (0.0, 0.0), Affine::IDENTITY).unwrap(); + let NodeKind::Text(t) = &node.kind else { panic!("not text") }; + assert_eq!(t.plain_text(), "A\u{2028}B\nC"); + assert_eq!(t.paras.len(), 2, "{:?}", t.paras); + assert_eq!((t.paras[0].first_line_indent, t.paras[0].left_indent, t.paras[0].space_before), (6.0, 0.0, 4.0)); + assert_eq!((t.paras[1].first_line_indent, t.paras[1].left_indent), (6.0, 3.0)); + } + #[test] fn a_frame_too_short_for_its_first_line_is_made_taller() { // A heading in a frame as tall as its size: a line of the font it shows in here is taller. diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index 42f968faa5..efbb8a3a11 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -12,10 +12,12 @@ //! colours, gradients, transparency and images of the art. //! //! Text objects are slots in that document: their characters, fonts and places are in the file's -//! text document (see `ate`). Type that shows comes from the page, which draws it, into the slot -//! whose text is where the page has it. Type that doesn't show (a hidden layer or object, or off -//! the page) is made from the text document; where that can't be read (area type, type on a path) -//! it's left out, with a warning. +//! text document (see `ate`). When the text document has the type of every text object that shows, +//! all the type is made from it, each text object in its own place, and the page's type is only +//! compared with it. Otherwise the type it has is still made from it, and the page's type that +//! lies elsewhere goes into the text objects it can't make, by where the text document puts their +//! lines or else in painting order. A text object whose type neither has (a frame of a kind it +//! doesn't read, on a hidden layer or object) is left out, with a warning. //! //! What a layer that shows has that `ai` doesn't read makes the file come in as its page, as it did //! before; on a layer that doesn't show it is left out of that layer, with a warning. The page is @@ -46,7 +48,9 @@ mod slots; #[cfg(test)] use build::{Frame, MADE, prune_unseen}; #[cfg(test)] -use compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour}; +use compare::{ + MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, Shares, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour, +}; pub use layers::{ai_alone, layered_ai}; pub(super) use layers::{layered, program_alone}; pub use slots::is_loss; @@ -88,7 +92,7 @@ mod tests { let rect = page.artboards[0].rect; let frame = Frame { page: &page, page_rect: rect, rect, whole: false }; let mut view = PageView::new(&frame); - assert_eq!(prune_unseen(&frame, &mut view, &mut layers), 1, "only the ring the page doesn't draw"); + assert_eq!(prune_unseen(&frame, &mut view, &mut layers, false), 1, "only the ring the page doesn't draw"); let widths: Vec<f64> = layers.layers[0].children().unwrap().iter().filter_map(|n| n.appearance.stroke().map(|s| s.width)).collect(); assert_eq!(widths, [12.0, 6.0]); // Taken by lightness alone, the red and the dark red are alike. @@ -99,6 +103,33 @@ mod tests { assert!(!differ(&px(dark), &px(red)) && differ_in_colour(&px(dark), &px(red))); } + /// The share of a rectangle's pixels in the areas, however many areas there are: none for one + /// that only shares their edge, lies off the drawing or isn't a number. + #[test] + fn the_share_of_a_rectangle_in_the_areas_counts_its_pixels() { + let in_areas = |areas: &[Rect], w: usize, h: usize| { + let marks: Vec<bool> = (0..w * h) + .map(|k| { + let (x, y) = ((k % w) as f64 + 0.5, (k / w) as f64 + 0.5); + areas.iter().any(|a| a.contains(Point::new(x, y))) + }) + .collect(); + let shares = Shares::of(&marks, w, h); + move |r: &Rect| shares.share(r) + }; + let share = in_areas(&[Rect::new(10.0, 10.0, 20.0, 20.0), Rect::new(30.0, 0.0, 31.0, 1.0)], 40, 40); + assert_eq!((share(&Rect::new(12.0, 12.0, 22.0, 18.0)), share(&Rect::new(10.0, 10.0, 30.0, 20.0))), (0.8, 0.5)); + assert_eq!((share(&Rect::new(15.0, 15.0, 30.0, 30.0)), share(&Rect::new(30.2, 0.2, 30.8, 0.8))), (25.0 / 225.0, 1.0)); + assert_eq!( + [share(&Rect::new(20.0, 20.0, 30.0, 30.0)), share(&Rect::new(0.0, 0.0, 5.0, 5.0)), share(&Rect::new(50.0, 50.0, 60.0, 60.0))], + [0.0; 3] + ); + assert_eq!(share(&Rect::new(f64::NAN, 0.0, 39.0, 39.0)), 0.0); + let many: Vec<Rect> = (0..5000).map(|i| Rect::new(f64::from(i % 70), 50.0, f64::from(i % 70) + 1.0, 51.0)).collect(); + let share = in_areas(&many, 80, 80); + assert_eq!((share(&Rect::new(60.0, 50.0, 75.0, 51.0)), share(&Rect::new(70.0, 50.0, 75.0, 51.0))), (10.0 / 15.0, 0.0)); + } + fn piece(text: &str, x: f64, y: f64) -> Arc<Node> { Arc::new(Node::new(NodeId(0), NodeKind::Text(Box::new(TextObject::point(Point::new(x, y), text, CharStyle::default()))))) } @@ -163,9 +194,9 @@ mod tests { assert!(compared(&a, &b, &[], &[]).solid > MAX_SOLID_DIFFERENCE, "the old point sampling falsely refused this page"); let frame = Frame { page: &page, page_rect: rect, rect, whole: false }; let mut view = PageView::new(&frame); - assert!(compare(&frame, &mut view, &vector).is_ok()); - assert!(compare(&frame, &mut view, &Document::new(1000.0, 500.0)).is_err(), "missing artwork remains an error"); + assert!(compare(&frame, &mut view, &vector, false).is_ok()); + assert!(compare(&frame, &mut view, &Document::new(1000.0, 500.0), false).is_err(), "missing artwork remains an error"); let shifted = Rect::new(0.0, 0.0, 500.0, 500.0); - assert!(view.difference(&vector, shifted).any > MAX_DIFFERENCE, "wrong framing remains an error"); + assert!(view.difference(&vector, shifted, false).any > MAX_DIFFERENCE, "wrong framing remains an error"); } } diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 8e80703d76..1dd8b7d2b0 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -1,8 +1,8 @@ use super::compare::{MAX_DIFFERENCE, PageView, compare, difference}; -use super::plan::plan; +use super::plan::{made_only, make_slots, plan, readable_all}; use super::slots::{ - ART_LEFT_OUT, Content, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, TEXT_LEFT_OUT, TYPE_LEFT_OUT, collect_slots, extent, few, fill_slots, - letters, text_objects, words, + ART_LEFT_OUT, Content, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT, collect_slots, extent, few, + fill_slots, letters, text_objects, words, }; use super::{Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, Vec2, ai}; @@ -183,10 +183,6 @@ pub(super) fn build_from( // The page's type that needs no text object of the layers: the layers' own legacy text, or // placed files that show it. let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?; - // The page's type is compared with every text object of the layers: that has its limits. - if infos.len() > MAX_SLOTS || infos.len().saturating_mul(shown.len()) > MAX_PAIRS { - return Err("it has too many text objects".into()); - } let texts = Texts::read(data); // Each story is read once, however many text objects name it. let mut read: std::collections::BTreeMap<u32, Option<Arc<Story>>> = Default::default(); @@ -202,7 +198,8 @@ pub(super) fn build_from( } let template = template.map(|t| ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0)); let mut notes = warnings; - let content = plan(&infos, &stories, template, to_doc, [&shown, &hidden], &mut notes); + let own = (!outlined).then(|| outside_placed_files(&shown, &doc, &placed_elsewhere)); + let (content, reflow) = slot_content(&infos, &stories, template, to_doc, own.as_deref(), [&shown, &hidden], &mut notes)?; // The glyphs left out with the rest of the page's art, and how many text objects take type of // the page right next to them (not counted past `MAX_PAIRS` comparisons). let compared = lone.len().saturating_mul(shown.iter().chain(&hidden).map(Vec::len).sum()); @@ -211,7 +208,7 @@ pub(super) fn build_from( matches!(n.kind, NodeKind::Text(_)) && n.visual_bounds().is_some_and(|b| missing.iter().any(|r| !b.inflate(OUTLINE_REACH, OUTLINE_REACH).intersect(*r).is_zero_area())) }; - let short = content.iter().filter(|c| matches!(c, Content::Page(p) | Content::Made(_, _, _, p) if p.iter().any(next_to_missing))).count(); + let short = content.iter().filter(|c| matches!(c, Content::Page(p) if p.iter().any(next_to_missing))).count(); let mut empty = 0; let mut layers = std::mem::take(&mut doc.layers); let mut made = vec![]; @@ -244,16 +241,16 @@ pub(super) fn build_from( // doesn't draw is weighed again with the images there, since an image that covered a // text object at the first placement may not cover it at the other. let other = elsewhere(&doc, &placed_elsewhere); - let unseen = prune_unseen(&frame, &mut view, &mut doc); + let unseen = prune_unseen(&frame, &mut view, &mut doc, reflow); let unseen_note = |n: usize| (n > 0).then(|| format!("{n} {UNSEEN_TEXT}")); - match compare(&frame, &mut view, &doc) { + match compare(&frame, &mut view, &doc, reflow) { // Placed files at the other point their data gives, where that draws closer to the // page: a small image in the wrong place differs too little to fail. Ok(note) => { let closer = other.and_then(|mut other| { - let unseen = prune_unseen(&frame, &mut view, &mut other); - let closer = view.difference(&other, frame.rect).any < view.difference(&doc, frame.rect).any; - closer.then(|| compare(&frame, &mut view, &other).ok()).flatten().map(|note| (other, unseen, note)) + let unseen = prune_unseen(&frame, &mut view, &mut other, reflow); + let closer = view.difference(&other, frame.rect, reflow).any < view.difference(&doc, frame.rect, reflow).any; + closer.then(|| compare(&frame, &mut view, &other, reflow).ok()).flatten().map(|note| (other, unseen, note)) }); match closer { Some((other, unseen, note)) => { @@ -265,8 +262,8 @@ pub(super) fn build_from( } // Placed files at the other point their data gives, where that draws as the page. Err(why) => match other.map(|mut other| { - let unseen = prune_unseen(&frame, &mut view, &mut other); - (compare(&frame, &mut view, &other), other, unseen) + let unseen = prune_unseen(&frame, &mut view, &mut other, reflow); + (compare(&frame, &mut view, &other, reflow), other, unseen) }) { Some((Ok(note), other, unseen)) => { doc = other; @@ -288,6 +285,34 @@ pub(super) fn build_from( Ok((doc, notes)) } +/// What goes into each of `infos`' slots, and whether the type is all made from the file's text +/// document. When the text document makes the type of every text object that shows (and the type +/// isn't asked for as outlines: `own` has the page's text objects that show outside placed files), +/// each slot takes its own made type and the page's type is only compared with it: type laid out +/// again, in another font where the file's isn't installed, may differ from the page's. Otherwise +/// see [`plan`], with `pages` (the page's text objects that show and that don't). +fn slot_content( + infos: &[SlotInfo], + stories: &[Option<Arc<Story>>], + template: Option<(f64, f64)>, + to_doc: Affine, + own: Option<&[Vec<Arc<Node>>]>, + pages: [&[Vec<Arc<Node>>]; 2], + notes: &mut Vec<String>, +) -> Result<(Vec<Content>, bool), String> { + let made = make_slots(infos, stories, template, to_doc, notes); + if let Some(own) = own.filter(|_| readable_all(infos, &made)) { + return Ok((made_only(infos, made, [own, pages[1]], notes), true)); + } + // The page's type is matched with every text object whose type isn't made, and weighed against + // where every made one draws: that has its limits. + let open = made.iter().filter(|m| m.is_none()).count(); + if open > MAX_SLOTS || infos.len().saturating_mul(pages[0].len()) > MAX_PAIRS { + return Err("it has too many text objects".into()); + } + Ok((plan(infos, stories, made, template, to_doc, pages, notes), false)) +} + /// `doc` with the placed files `placed` lists at their other placement (see /// [`ai::Structure::placed_elsewhere`]): each image's transform followed by its move. `None` when /// none is listed. @@ -391,6 +416,21 @@ fn in_placed_files(objects: &[Vec<Arc<Node>>], doc: &Document, placed: &[(NodeId inside(doc) || elsewhere(doc, placed).is_some_and(|other| inside(&other)) } +/// The page's text objects in `objects` that don't lie inside a placed file that shows in `doc`, at +/// either placement (see [`in_placed_files`]): the placed file's preview has the others. +fn outside_placed_files(objects: &[Vec<Arc<Node>>], doc: &Document, placed: &[(NodeId, Affine)]) -> Vec<Vec<Arc<Node>>> { + let mut files = vec![]; + placed_files(&doc.layers, &mut files); + if let Some(other) = elsewhere(doc, placed) { + placed_files(&other.layers, &mut files); + } + if files.is_empty() { + return objects.to_vec(); + } + let inside = |o: &[Arc<Node>]| extent(o).is_some_and(|r| files.iter().any(|f| f.inflate(OUTLINE_REACH, OUTLINE_REACH).contains_rect(r))); + objects.iter().filter(|o| !inside(o)).cloned().collect() +} + /// Where the placed files that show in `nodes` are: the linked images the editing data's reader /// makes of them. fn placed_files(nodes: &[Arc<Node>], out: &mut Vec<Rect>) { @@ -520,15 +560,16 @@ fn take_out(nodes: &mut Vec<Arc<Node>>, id: NodeId, hide: bool) -> bool { /// The text objects made from the file's text document that show and print on the page's area, /// where the page has no type to match them, and that the layers look no worse without, are not /// drawn by the app that wrote the file (which paints every shown text object; it keeps the type -/// of what was turned to outlines): they are taken out. How many. -pub(super) fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document) -> usize { +/// of what was turned to outlines): they are taken out. How many. `reflow`: the type is all laid +/// out again from the text document (see [`compare`]). +pub(super) fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document, reflow: bool) -> usize { let mut found = vec![]; unmark(&mut doc.layers, true, true, &mut found); let rect = frame.rect; if found.is_empty() || found.len() > MAX_WEIGHED { return 0; } - let with = view.difference(doc, rect).any; + let with = view.difference(doc, rect, reflow).weighed(reflow); // Taking a text object out changes only what is drawn in its box. When the art would still // differ from the page by more than `compare` allows with every candidate gone, the layers // aren't used whatever is pruned: don't draw them again for each one (#758). diff --git a/crates/eps/src/import/native/compare.rs b/crates/eps/src/import/native/compare.rs index cf86445e59..e8ebed707f 100644 --- a/crates/eps/src/import/native/compare.rs +++ b/crates/eps/src/import/native/compare.rs @@ -75,6 +75,14 @@ pub(super) struct Difference { pub(super) solid: f64, } +impl Difference { + /// The share [`compare`] holds to [`MAX_DIFFERENCE`]: every pixel that differs, or with `reflow` + /// (type laid out again from the file's text) those away from type. + pub(super) fn weighed(&self, reflow: bool) -> f64 { + if reflow { self.art } else { self.any } + } +} + /// The scale the comparisons draw a region at: about 400 pixels along its longer side. fn compare_scale(r: Rect) -> f64 { (400.0 / r.width().max(r.height()).max(1.0)).min(4.0) @@ -129,6 +137,8 @@ pub(super) struct PageView { /// rendering of the style there, the layers VectorCraft's live effects, and the two aren't /// held to look alike. restyled: Vec<Rect>, + /// Where the page draws anything (its type, or its own outlines of type) or has its type. + page_marks: Shares, layers: vectorcraft_render::Renderer, scale: f64, samples: u32, @@ -144,7 +154,11 @@ impl PageView { let page = comparison_render(&mut vectorcraft_render::Renderer::new(), frame.page, ra, scale, samples); let mut page_type = vec![]; type_areas(&frame.page.layers, ra, scale, &mut page_type); - Self { page, page_type, restyled: vec![], layers: vectorcraft_render::Renderer::new(), scale, samples } + let (w, h) = (page.width as usize, page.height as usize); + let typed = in_areas(&page_type, w, h); + let marks: Vec<bool> = page.pixels.as_chunks::<4>().0.iter().zip(&typed).map(|(p, t)| *t || ink(on_white(p)) > WHITE).collect(); + let page_marks = Shares::of(&marks, w, h); + Self { page, page_type, restyled: vec![], page_marks, layers: vectorcraft_render::Renderer::new(), scale, samples } } /// Leave the drawn looks in `looks` (on `region`, the page's area in the layers' document) out @@ -159,13 +173,27 @@ impl PageView { } /// How `b` on `rb` (a rectangle the page's size) draws differently from the page ([`compared`]). - pub(super) fn difference(&mut self, b: &Document, rb: Rect) -> Difference { + /// With `reflow` (`b`'s type laid out again from the file's text), type counts as type only where + /// both have something: `b`'s where the page has type or draws anything in at least [`MARKED`] + /// of it, the page's where at least half of it lies where `b` has a text object, shown or not, + /// or a placed file. Elsewhere it is art the other lacks. + pub(super) fn difference(&mut self, b: &Document, rb: Rect, reflow: bool) -> Difference { // The page doesn't print what isn't printed. let printed = as_printed(b); let b = printed.as_ref().unwrap_or(b); let y = comparison_render(&mut self.layers, b, rb, self.scale, self.samples); - let mut areas = self.page_type.clone(); + let mut areas = vec![]; type_areas(&b.layers, rb, self.scale, &mut areas); + if reflow { + areas.retain(|r| self.page_marks.share(r) >= MARKED); + let mut texts = vec![]; + all_type_areas(&b.layers, rb, self.scale, &mut texts); + let (w, h) = (self.page.width as usize, self.page.height as usize); + let on_layers = Shares::of(&in_areas(&texts, w, h), w, h); + areas.extend(self.page_type.iter().filter(|r| on_layers.share(r) >= 0.5)); + } else { + areas.extend(&self.page_type); + } compared(&self.page, &y, &areas, &self.restyled) } @@ -241,6 +269,62 @@ fn type_areas(nodes: &[Arc<Node>], region: Rect, scale: f64, out: &mut Vec<Rect> } } +/// Where every text object in `nodes` is, shown or not, as [`type_areas`] gives it, and every placed +/// file (whose preview draws the type it has). +fn all_type_areas(nodes: &[Arc<Node>], region: Rect, scale: f64, out: &mut Vec<Rect>) { + for n in nodes { + let placed = matches!(&n.kind, NodeKind::Image(im) if im.link.is_some()); + if (placed || matches!(n.kind, NodeKind::Text(_))) + && let Some(b) = n.visual_bounds() + { + let b = b.inflate(OUTLINE_REACH, OUTLINE_REACH); + out.push(Rect::new((b.x0 - region.x0) * scale, (b.y0 - region.y0) * scale, (b.x1 - region.x0) * scale, (b.y1 - region.y0) * scale)); + } else if let Some(c) = n.children() { + all_type_areas(c, region, scale, out); + } + } +} + +/// Which of `w` × `h` pixels are marked, counted so that the share of any rectangle's pixels that +/// are is read at once. +pub(super) struct Shares { + /// How many of the marked pixels lie above and left of each pixel corner. + sums: Vec<u32>, + w: usize, + h: usize, +} + +impl Shares { + /// The pixels `marks` marks (row by row). + pub(super) fn of(marks: &[bool], w: usize, h: usize) -> Self { + let stride = w + 1; + let mut sums = vec![0u32; stride * (h + 1)]; + for (k, marked) in marks.iter().enumerate().take(w * h) { + let (i, j) = (k % w.max(1), k / w.max(1)); + let left = sums.get((j + 1) * stride + i).copied().unwrap_or(0); + let up = sums.get(j * stride + i + 1).copied().unwrap_or(0); + let corner = sums.get(j * stride + i).copied().unwrap_or(0); + if let Some(s) = sums.get_mut((j + 1) * stride + i + 1) { + *s = (left + up + u32::from(*marked)).saturating_sub(corner); + } + } + Self { sums, w, h } + } + + /// The share (0 to 1) of `r`'s pixels that are marked: 0 for one with none of the pixels. + pub(super) fn share(&self, r: &Rect) -> f64 { + let (w, h, stride) = (self.w, self.h, self.w + 1); + let clamp = |v: f64, max: usize| if v.is_finite() { v.clamp(0.0, max as f64) as usize } else { 0 }; + let (x0, y0, x1, y1) = (clamp(r.x0.floor(), w), clamp(r.y0.floor(), h), clamp(r.x1.ceil(), w), clamp(r.y1.ceil(), h)); + if !r.is_finite() || x1 <= x0 || y1 <= y0 { + return 0.0; + } + let at = |x: usize, y: usize| self.sums.get(y * stride + x).copied().unwrap_or(0); + let inside = (at(x1, y1) + at(x0, y0)).saturating_sub(at(x0, y1) + at(x1, y0)); + f64::from(inside) / ((x1 - x0) as f64 * (y1 - y0) as f64) + } +} + /// Which of `w` × `h` pixels (row by row) lie in one of `areas`. fn in_areas(areas: &[Rect], w: usize, h: usize) -> Vec<bool> { // Each area adds one inside it: corners marked, then summed along the rows and down the columns. @@ -272,6 +356,10 @@ fn in_areas(areas: &[Rect], w: usize, h: usize) -> Vec<bool> { (0..h).flat_map(|j| (0..w).map(move |i| (i, j))).map(|(i, j)| count.get(j * stride + i).is_some_and(|c| *c > 0)).collect() } +/// The least share of a text object's area (with the margin round it) where the page draws anything +/// or has type, for its type laid out again to count as type. +const MARKED: f64 = 0.05; + /// More of the page than this differing between the layers' art and the page's own, and the /// layers aren't used. pub(super) const MAX_DIFFERENCE: f64 = 0.05; @@ -287,11 +375,13 @@ pub(super) const MAX_SOLID_DIFFERENCE: f64 = 0.001; const PAST_THE_PAGE: f64 = 1.0; /// Do the layers' art and the page's own look alike (where the page holds all the art that prints, -/// also round it)? An error says they don't; `Ok` has the note to give when they differ a little: +/// also round it)? An error says they don't; `Ok` has the notes to give when they differ a little: /// with the share of the pixels that differ away from type when that is notable, otherwise with the -/// share of those that differ in the type's areas. -pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document) -> Result<Option<String>, String> { - let mut diff = view.difference(layered, frame.rect); +/// share of those that differ in the type's areas. With `type_reflow` (all the type laid out again +/// from the file's text, which may show in another font), type that differs doesn't make them +/// differ: only art away from type does, and the type's share is a note of its own. +pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document, type_reflow: bool) -> Result<Vec<String>, String> { + let mut diff = view.difference(layered, frame.rect, type_reflow); if frame.whole && let Some(art) = vectorcraft_render::encode::art_bounds(as_printed(layered).as_ref().unwrap_or(layered)) .filter(|a| !frame.rect.inflate(PAST_THE_PAGE, PAST_THE_PAGE).contains_rect(*a)) @@ -302,21 +392,24 @@ pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document let round = difference(frame.page, Rect::new(all.x0 + dx, all.y0 + dy, all.x1 + dx, all.y1 + dy), layered, all); diff = Difference { any: diff.any.max(round.any), art: diff.art.max(round.art), solid: diff.solid.max(round.solid) }; } - if diff.any > MAX_DIFFERENCE || diff.solid > MAX_SOLID_DIFFERENCE { - return Err(format!("the art on them differs from the page's in {:.1}% of it", diff.any * 100.0)); + if diff.weighed(type_reflow) > MAX_DIFFERENCE || diff.solid > MAX_SOLID_DIFFERENCE { + return Err(format!("the art on them differs from the page's in {:.1}% of it", diff.weighed(type_reflow) * 100.0)); } if diff.any <= NOTABLE_DIFFERENCE { - return Ok(None); + return Ok(vec![]); } - Ok(Some(if diff.art > NOTABLE_DIFFERENCE { - format!( - "the art on the layers differs from the file's own page in about {:.1}% of it (brush strokes, live effects and the like that the layers' data doesn't describe)", - diff.art * 100.0 - ) - } else { - format!( - "the type on the layers differs from the file's own page in about {:.1}% of it (type laid out again from the file's text, or drawn in another font)", - (diff.any - diff.art) * 100.0 - ) - })) + let art = format!( + "the art on the layers differs from the file's own page in about {:.1}% of it (brush strokes, live effects and the like that the layers' data doesn't describe)", + diff.art * 100.0 + ); + let typed = format!( + "the type on the layers differs from the file's own page in about {:.1}% of it (type laid out again from the file's text, or drawn in another font)", + (diff.any - diff.art) * 100.0 + ); + let art_notable = diff.art > NOTABLE_DIFFERENCE; + Ok(match (art_notable, type_reflow && diff.any - diff.art > NOTABLE_DIFFERENCE) { + (true, true) => vec![art, typed], + (true, false) => vec![art], + (false, _) => vec![typed], + }) } diff --git a/crates/eps/src/import/native/plan.rs b/crates/eps/src/import/native/plan.rs index 4bb3675cd1..6c6cb82b4d 100644 --- a/crates/eps/src/import/native/plan.rs +++ b/crates/eps/src/import/native/plan.rs @@ -1,11 +1,21 @@ use super::layers::closed_where_ends_meet; -use super::slots::{Content, SlotInfo, assign, covered, extent, join_pieces, letters, same_type, words}; +use super::slots::{ + Content, MAX_PAIRS, OUTLINE_REACH, PAGE_TYPE_LEFT_OUT, PAGE_TYPE_UNCHECKED, SlotInfo, assign, covered, extent, join_pieces, letters, same_type, + words, +}; use super::{Affine, Arc, Node, NodeId, NodeKind, Point, Rect, Story, TextKind}; -/// Match page objects to the nearest slot whose story describes them, including hidden slots. -fn match_page_objects(infos: &[SlotInfo], lines: &[Option<Vec<(String, Point)>>], shown: &[Vec<Arc<Node>>]) -> Vec<Option<usize>> { +/// A slot's type made from the file's text document, and roughly where it lies on the document. +pub(super) type Made = (Box<Node>, Option<Rect>); + +/// Match page objects to the nearest slot that `open` (the slots whose type wasn't made) has and +/// whose story describes them, including hidden slots. +fn match_page_objects(infos: &[SlotInfo], lines: &[Option<Vec<(String, Point)>>], open: &[bool], shown: &[Vec<Arc<Node>>]) -> Vec<Option<usize>> { let mut pairs: Vec<(f64, usize, usize)> = vec![]; for (k, _) in infos.iter().enumerate() { + if !open.get(k).copied().unwrap_or(false) { + continue; + } let Some(l) = lines.get(k).and_then(Option::as_ref) else { continue }; for (j, object) in shown.iter().enumerate() { if let Some(d) = object.iter().filter_map(|n| same_type(n, l)).min_by(f64::total_cmp) { @@ -40,12 +50,139 @@ fn frame_text_from_art(info: &SlotInfo, node: &mut Node, region: &mut Option<Rec } } -/// What goes into each of `infos`' slots: the page's type that the file's text document puts where the -/// page has it, else type made from the text document, else (for a file whose text document can't say) -/// the page's type in painting order. +/// Each of `infos`' slots' type made from the file's text document, once: `None` where the text +/// document can't make it (no story, a frame of a kind it doesn't read, mirrored type, no text). +pub(super) fn make_slots( + infos: &[SlotInfo], + stories: &[Option<Arc<Story>>], + template: Option<(f64, f64)>, + to_doc: Affine, + warn: &mut Vec<String>, +) -> Vec<Option<Made>> { + let mut taller = 0; + let made = infos + .iter() + .enumerate() + .map(|(k, info)| { + let t = template?; + let story = stories.get(k)?.as_ref()?; + let mut node = story.node(NodeId(0), info.frame, t, to_doc)?; + let mut region = story.region(t, to_doc); + // The first line where the file has it, in the text document's frame (that of a + // copied object is its original's, as its lines are). + story.place_first_line(&mut node, t, to_doc); + // Area type and type on a path in the object's own frame: the text document's frame + // of a copied object keeps its original's path. + frame_text_from_art(info, &mut node, &mut region); + if let NodeKind::Text(text) = &mut node.kind + && story.fit_first_line(text) + { + taller += 1; + } + Some((Box::new(node), region)) + }) + .collect(); + if taller > 0 { + warn.push(format!( + "area type in frames too short for a line of the font it shows in got taller frames ({taller}): their type wouldn't show otherwise" + )); + } + made +} + +/// Does the file's text document make the type of every slot that shows (at least one does)? +pub(super) fn readable_all(infos: &[SlotInfo], made: &[Option<Made>]) -> bool { + infos.iter().any(|i| i.shown) && infos.iter().zip(made).all(|(i, m)| !i.shown || m.is_some()) +} + +/// Each slot's made type, where its slot is (the page's type that shows isn't put anywhere). Shown +/// made type with none of the page's type where it draws is weighed against the page (see +/// `prune_unseen`); the page's type that no made type takes, shown or not, is left out with a note +/// in `warn`. Slots that don't show and whose type isn't made take the page's type that doesn't +/// show (`pages`: the page's text objects that show and that don't), by painting order. +pub(super) fn made_only(infos: &[SlotInfo], made: Vec<Option<Made>>, pages: [&[Vec<Arc<Node>>]; 2], warn: &mut Vec<String>) -> Vec<Content> { + let [shown, hidden] = pages; + let mut content = made_content(infos, made); + match see_page_type(&mut content, shown) { + Some(0) => {} + Some(_) => warn.push(PAGE_TYPE_LEFT_OUT.into()), + None => warn.push(PAGE_TYPE_UNCHECKED.into()), + } + fill_hidden(infos, &mut content, hidden); + content +} + +/// The letters and digits of `s`, in any script, in lower case: what is compared of the page's type +/// and made type (the page may spell a mark another way). +fn spelling(s: &str) -> String { + s.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect() +} + +/// The text of `n`, if it is a text object. +fn plain_text(n: &Node) -> String { + if let NodeKind::Text(t) = &n.kind { t.plain_text() } else { String::new() } +} + +/// The words of the page's text object `o`, each as its [`spelling`], the empty ones left out. +fn object_words(o: &[Arc<Node>]) -> Vec<String> { + o.iter().flat_map(|n| plain_text(n).split_whitespace().map(spelling).collect::<Vec<_>>()).filter(|w| !w.is_empty()).collect() +} + +/// Each slot's made type as its content, else nothing yet. Made type that shows has where it draws, +/// or where its story lies when it draws nothing. +fn made_content(infos: &[SlotInfo], made: Vec<Option<Made>>) -> Vec<Content> { + infos + .iter() + .zip(made) + .map(|(info, m)| match m { + Some((node, region)) => { + let drawn = node.visual_bounds().filter(|b| !b.is_zero_area()).or(region); + Content::Made(node, drawn.filter(|_| info.shown), false) + } + None => Content::Empty, + }) + .collect() +} + +/// Mark the made type that has at least half of a piece of the page's type where it draws (or round +/// it, as far as strokes round type reach) as type the page draws. How many of the page's text +/// objects no made type takes, shown or not: none that holds a piece of the object has its words +/// ([`spelling`]). Past `MAX_PAIRS` comparisons nothing is marked or counted (`None`). +fn see_page_type(content: &mut [Content], shown: &[Vec<Arc<Node>>]) -> Option<usize> { + let texts = |o: &[Arc<Node>]| o.iter().filter_map(|n| if let NodeKind::Text(_) = &n.kind { Some(n.clone()) } else { None }).collect::<Vec<_>>(); + // Each object's pieces of type, and the words of them that no made type holding it has yet. + let mut objects: Vec<(Vec<Rect>, Vec<String>, bool)> = + shown.iter().map(|o| (texts(o).iter().filter_map(|n| n.visual_bounds()).collect(), object_words(o), false)).collect(); + let pieces: usize = objects.iter().map(|o| o.0.len()).sum(); + if content.len().saturating_mul(pieces) > MAX_PAIRS { + return None; + } + let holds = |drawn: Rect, r: &Rect| drawn.inflate(OUTLINE_REACH, OUTLINE_REACH).intersect(*r).area() >= 0.5 * r.area().max(1e-9); + for c in content { + let Content::Made(node, region, seen) = c else { continue }; + // Hidden made type has no region: where it draws, shown, is its own box. + let Some(drawn) = region.or_else(|| node.visual_bounds()) else { continue }; + let spelled = if let NodeKind::Text(t) = &node.kind { spelling(&t.plain_text()) } else { String::new() }; + for (rects, words, held) in &mut objects { + if rects.iter().any(|r| holds(drawn, r)) { + *held = true; + *seen |= region.is_some(); + words.retain(|w| !spelled.contains(w.as_str())); + } + } + } + Some(objects.iter().filter(|(_, words, held)| !held || !words.is_empty()).count()) +} + +/// What goes into each of `infos`' slots when the file's text document can't make the type of every +/// slot that shows: type made from the text document (`made`) where it can, else the page's type that +/// the text document puts where the page has it, else the page's type in painting order. The page's +/// type that lies where made type draws and has its words is that type as the page draws it; the +/// rest goes only into slots without made type. pub(super) fn plan( infos: &[SlotInfo], stories: &[Option<Arc<Story>>], + made: Vec<Option<Made>>, template: Option<(f64, f64)>, to_doc: Affine, pages: [&[Vec<Arc<Node>>]; 2], @@ -59,49 +196,16 @@ pub(super) fn plan( Some(s.line_starts(t).into_iter().map(|(text, (x, y))| (text, to_doc * Point::new(x, y))).collect()) }) .collect(); - let owner = match_page_objects(infos, &lines, shown); - // Type the text document makes, shown or not: the page's pieces of it aren't needed. - let mut content: Vec<Content> = infos.iter().map(|_| Content::Empty).collect(); + // A story's lines are its first frame's: a frame of a story whose type is made in another + // text object can't say that the page's type there is its own. + let made_stories: std::collections::BTreeSet<u32> = infos.iter().zip(&made).filter(|(_, m)| m.is_some()).filter_map(|(i, _)| i.story).collect(); + let open: Vec<bool> = infos.iter().zip(&made).map(|(i, m)| m.is_none() && i.story.is_none_or(|s| !made_stories.contains(&s))).collect(); + let owner = match_page_objects(infos, &lines, &open, shown); // Where the made type that doesn't show lies, by slot. - let mut hidden_at: Vec<(usize, Rect)> = vec![]; - let mut taller = 0; - if let Some(t) = template { - for (k, info) in infos.iter().enumerate() { - let Some(Some(story)) = stories.get(k) else { continue }; - let Some(mut node) = story.node(NodeId(0), info.frame, t, to_doc) else { continue }; - let mut region = story.region(t, to_doc); - // The first line where the file has it, in the text document's frame (that of a - // copied object is its original's, as its lines are). - story.place_first_line(&mut node, t, to_doc); - // Area type and type on a path in the object's own frame: the text document's frame - // of a copied object keeps its original's path. - frame_text_from_art(info, &mut node, &mut region); - if let (false, Some(r)) = (info.shown, region) { - hidden_at.push((k, r)); - } - if let NodeKind::Text(text) = &mut node.kind - && story.fit_first_line(text) - { - taller += 1; - } - if let Some(c) = content.get_mut(k) { - *c = Content::Made(Box::new(node), region.filter(|_| info.shown), false, vec![]); - } - } - } - if taller > 0 { - warn.push(format!( - "area type in frames too short for a line of the font it shows in got taller frames ({taller}): their type wouldn't show otherwise" - )); - } - // The file's text document is trusted where it agrees with the page about something (its lines - // start where the page's type does, or the page has type where it lays type out), or where the - // page has no type to disagree with. - let in_region = |object: &[Arc<Node>]| covered(object, &content, |_| true); - let trusted = owner.iter().any(Option::is_some) || shown.is_empty() || shown.iter().any(|o| in_region(o)); - if !trusted { - content.iter_mut().for_each(|c| *c = Content::Empty); - } + let hidden_at: Vec<(usize, Rect)> = + infos.iter().zip(&made).enumerate().filter_map(|(k, (info, m))| Some((k, m.as_ref().filter(|_| !info.shown)?.1?))).collect(); + // Type the text document makes, shown or not: the page's pieces of it aren't needed. + let mut content = made_content(infos, made); // Is `object` the type of a text object that doesn't show, as the page draws it: in its frame, // with its words? (A copied object's lines are where its original's are, so they don't say.) let hidden_type = |object: &[Arc<Node>]| { @@ -116,59 +220,45 @@ pub(super) fn plan( }) }) }; - // The letters of each slot's story, in lower case. - let spelled: Vec<String> = stories.iter().map(|s| s.as_ref().map(|s| letters(s.text()).to_ascii_lowercase()).unwrap_or_default()).collect(); - // For each slot: is its made type where `object` is, with the words of one of `object`'s texts in - // its story? All are false unless such slots have the words of every text between them. - let spelling = |object: &[Arc<Node>], content: &[Content]| -> Vec<bool> { - let r = extent(object); - let texts: Vec<Vec<String>> = object + // The letters and digits of each slot's made type that shows, in any script, in lower case. + let spelled: Vec<String> = content + .iter() + .map(|c| match c { + Content::Made(node, Some(_), _) => match &node.kind { + NodeKind::Text(t) => spelling(&t.plain_text()), + _ => String::new(), + }, + _ => String::new(), + }) + .collect(); + // Has made type that draws where `object` lies every word of it ([`spelling`]), in any order? + let made_words = |object: &[Arc<Node>], content: &[Content]| { + let Some(r) = extent(object) else { return true }; + let near: Vec<&String> = content .iter() - .filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(words(&t.plain_text().to_ascii_lowercase())) } else { None }) - .filter(|ws| !ws.is_empty()) + .zip(&spelled) + .filter(|(c, _)| matches!(c, Content::Made(_, Some(region), _) if !region.intersect(r).is_zero_area())) + .map(|(_, s)| s) .collect(); - let has = |k: usize| spelled.get(k).is_some_and(|s| texts.is_empty() || texts.iter().any(|ws| ws.iter().all(|w| s.contains(w.as_str())))); - let near: Vec<bool> = content - .iter() - .enumerate() - .map(|(k, c)| match (c, r) { - (Content::Made(_, Some(region), ..), Some(r)) => region.intersect(r).area() > 0.0 && has(k), - _ => false, - }) - .collect(); - let every = texts.iter().flatten().all(|w| near.iter().zip(&spelled).any(|(n, s)| *n && s.contains(w.as_str()))); - if every { near } else { vec![] } + object_words(object).iter().all(|w| near.iter().any(|s| s.contains(w.as_str()))) }; let mut spare: Vec<Vec<Arc<Node>>> = vec![]; for (j, object) in shown.iter().enumerate() { - let spells = spelling(object, &content); - let spells = |k: usize| spells.get(k).copied().unwrap_or(false); - match owner.get(j).copied().flatten().filter(|_| trusted) { - // The type of a text object the layers hide: the layers have it, hidden, so the page's - // isn't another text object's. - Some(k) if infos.get(k).is_some_and(|i| !i.shown) && matches!(content.get(k), Some(Content::Made(..))) => {} + match owner.get(j).copied().flatten() { Some(k) => match content.get_mut(k) { - Some(Content::Made(_, _, seen, _)) => *seen = true, Some(Content::Page(p)) => p.extend(object.iter().cloned()), Some(c) => *c = Content::Page(object.clone()), None => {} }, - // What lies where made type is and has that type's words is that type as the page draws it. - None if covered(object, &content, spells) => { - let r = extent(object).unwrap_or(Rect::ZERO); - for (k, c) in content.iter_mut().enumerate() { - if let Content::Made(_, Some(region), seen, _) = c - && !region.intersect(r).is_zero_area() - && spells(k) - { - *seen = true; - } - } - } - None if trusted && hidden_type(object) => {} + // What lies where made type draws, with its words, is that type as the page draws it (in + // another font, maybe, and in any script). + None if covered(object, &content, |_| true) && made_words(object, &content) => {} + None if hidden_type(object) => {} None => spare.push(object.clone()), } } + // The page's type that no made type takes is the spare type below. + let _ = see_page_type(&mut content, shown); for (k, c) in content.iter_mut().enumerate() { if let (Content::Page(parts), Some(Some(l))) = (c, lines.get(k)) { join_pieces(parts, l); @@ -179,12 +269,11 @@ pub(super) fn plan( infos.iter().enumerate().filter(|(k, i)| i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect(); if loose.is_empty() { // Type of the page that no text object says it owns goes with the nearest text object that has - // type of the page; with none, it is left out. + // type of the page (never into made type); with none, it is left out. let mut left_out = false; for object in &spare { let (centre, near) = (extent(object).map(|r| r.center()), |c: &Content| match c { Content::Page(parts) => extent(parts).map(|r| r.center()), - Content::Made(_, region, ..) => region.map(|r| r.center()), _ => None, }); let nearest = content @@ -192,14 +281,14 @@ pub(super) fn plan( .filter_map(|c| near(c).zip(centre).map(|(p, q)| ((p.x - q.x).hypot(p.y - q.y), c))) .min_by(|a, b| a.0.total_cmp(&b.0)); match nearest { - Some((_, Content::Page(parts) | Content::Made(_, _, _, parts))) => parts.extend(object.iter().cloned()), + Some((_, Content::Page(parts))) => parts.extend(object.iter().cloned()), _ => left_out = true, } } if !spare.is_empty() { warn.push( if left_out { - "some of the page's type has no text object in the layers, so it is left out" + PAGE_TYPE_LEFT_OUT } else { "some of the page's type has no text object of its own in the layers, so it is with another's" } @@ -221,13 +310,50 @@ pub(super) fn plan( warn.push("the text is on the layers in the order the page paints it, so a text object may be in another group than it was".into()); } } - // The same for the slots that don't show. + fill_hidden(infos, &mut content, hidden); + content +} + +/// The page's type that doesn't show (`hidden`) goes by painting order into the slots that don't +/// show and have nothing yet, but for what is the type of made type that doesn't show: a page object +/// with words and at least half of it where such type draws, while the type has all its words left +/// (each word an object takes is the type's no longer). Past `MAX_PAIRS` comparisons all of it goes. +fn fill_hidden(infos: &[SlotInfo], content: &mut [Content], hidden: &[Vec<Arc<Node>>]) { let unread: Vec<usize> = infos.iter().enumerate().filter(|(k, i)| !i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect(); - for (slot, parts) in unread.iter().zip(assign(hidden, unread.len())) { + if unread.is_empty() { + return; + } + // Where each made type that doesn't show draws, and the letters it has left. + let mut made: Vec<(Rect, String)> = content + .iter() + .filter_map(|c| match c { + Content::Made(node, None, _) => node.visual_bounds().map(|b| (b.inflate(OUTLINE_REACH, OUTLINE_REACH), spelling(&plain_text(node)))), + _ => None, + }) + .collect(); + let pairs = made.len().saturating_mul(hidden.len()); + // Is `o` the type of made type that doesn't show? That type's letters for it are taken. + let mut theirs = |o: &[Arc<Node>]| { + let words = object_words(o); + let Some(r) = extent(o).filter(|_| !words.is_empty()) else { return false }; + let found = made.iter_mut().find_map(|(b, s)| { + if b.intersect(r).area() < 0.5 * r.area().max(1e-9) { + return None; + } + let mut left = s.clone(); + for w in &words { + let at = left.find(w.as_str())?; + left.replace_range(at..at + w.len(), ""); + } + Some((s, left)) + }); + found.map(|(s, left)| *s = left).is_some() + }; + let hidden: Vec<Vec<Arc<Node>>> = if pairs > MAX_PAIRS { hidden.to_vec() } else { hidden.iter().filter(|o| !theirs(o)).cloned().collect() }; + for (slot, parts) in unread.iter().zip(assign(&hidden, unread.len())) { if let Some(c) = content.get_mut(*slot) { *c = Content::Page(parts.into_iter().flat_map(|p| p.iter().cloned()).collect()); } } - content } diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index 1548a2e9af..e6dc909ace 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -9,13 +9,23 @@ pub(super) const TYPE_LEFT_OUT: &str = "text objects of kinds VectorCraft doesn' pub(super) const ART_LEFT_OUT: &str = "hidden layers have art this can't read"; +/// The page's type that no text object takes, left out. +pub(super) const PAGE_TYPE_LEFT_OUT: &str = "some of the page's type has no text object in the layers, so it is left out"; + +/// The page's type, too much to check against the text objects (it may have some that none takes). +pub(super) const PAGE_TYPE_UNCHECKED: &str = + "the page's type wasn't checked against the text objects, as there is too much of it: some of it may have no text object"; + pub(super) const LAYERS_UNREAD: &str = "the file's layers weren't read"; /// Does this import note say that the file has something the document doesn't (hidden text, art or -/// layers that could not be read)? Writing the document over the file would lose it for good. +/// layers that could not be read, or the page's type that no text object takes or may not take)? +/// Writing the document over the file would lose it for good. pub fn is_loss(note: &str) -> bool { note.ends_with(TEXT_LEFT_OUT) || note.ends_with(TYPE_LEFT_OUT) + || note == PAGE_TYPE_LEFT_OUT + || note == PAGE_TYPE_UNCHECKED || [ART_LEFT_OUT, LAYERS_UNREAD, crate::import::graphics::TOO_MUCH, crate::import::graphics::FAR_AWAY].iter().any(|n| note.starts_with(n)) } @@ -163,10 +173,9 @@ pub(super) fn assign(objects: &[Vec<Arc<Node>>], slots: usize) -> Vec<Vec<&[Arc< pub(super) enum Content { /// Text objects (with the strokes round them) of the page. Page(Vec<Arc<Node>>), - /// A text object made from the file's text document, where it lies on the document, whether - /// the page has type where it is, and the page's type of no text object that is nearest it - /// (kept after it). - Made(Box<Node>, Option<Rect>, bool, Vec<Arc<Node>>), + /// A text object made from the file's text document, where it draws on the document (when it + /// shows), and whether the page has type where it is. + Made(Box<Node>, Option<Rect>, bool), /// Nothing the file lets this read. Empty, /// Its type is on the page with another text object's; there is nothing to put here. @@ -252,7 +261,7 @@ pub(super) fn fill_slots( i += n; continue; } - Some(Content::Made(mut text, _, seen, extra)) => { + Some(Content::Made(mut text, _, seen)) => { text.id = doc.alloc_id(); if let Some(story) = story { made.push((story, frame, text.id)); @@ -265,20 +274,12 @@ pub(super) fn fill_slots( } // Type the page shows is kept; other made type is weighed against the page. text.name = if seen { name.cloned() } else { Some(format!("{MADE}{}", name.map_or("", String::as_str))) }; - let extra: Vec<Arc<Node>> = extra.iter().map(|p| reid(doc, p)).collect(); - // The type takes the slot's transparency; the page's type kept after it, where it has - // none of its own, goes into a group with it that has the transparency instead. - let parts: Vec<Arc<Node>> = if transparent && !extra.is_empty() && !extra.iter().any(|p| see_through(p)) { - let mut group = Node::group(doc.alloc_id(), std::iter::once(Arc::new(*text)).chain(extra).collect()); - (group.opacity, group.blend, group.isolate, group.knockout) = state; - vec![Arc::new(group)] - } else { - (text.opacity, text.blend, text.isolate, text.knockout) = state; - std::iter::once(Arc::new(*text)).chain(extra).collect() - }; - let n = parts.len(); - nodes.splice(i..=i, parts); - i += n; + // The type takes the slot's transparency. + (text.opacity, text.blend, text.isolate, text.knockout) = state; + if let Some(slot) = nodes.get_mut(i) { + *slot = Arc::new(*text); + } + i += 1; continue; } Some(Content::Merged) => { diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index ee4beca057..29e73bbc92 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -342,6 +342,24 @@ fn type_of_the_page_inside_a_placed_file_needs_no_text_object() { assert!(!read, "{warnings:?}"); assert!(warnings.iter().any(|w| w.contains("its layers have no text objects")), "{warnings:?}"); } + // With a text object the text document makes beside it, the placed file's type is still its + // own, not type left out. + // The template box's centre (100, 50) is the canvas centre: the anchor is at (5, 10) in the art. + let doc = text_document(&[("Note\r", 0, (8096.5, 8231.5), (0.0, 0.0), 0.0)]); + let both = native_with_text(&layer("Pages", true, &format!("{place}{}", text_object(0))), &doc) + .replace("%AI3_TemplateBox: 50 50 50 50", "%AI3_TemplateBox: 100 50 100 50"); + let mut page = pdf(38.0); + let style = vectorcraft_doc::CharStyle { size: 14.0, ..Default::default() }; + let note = Node::new( + page.alloc_id(), + NodeKind::Text(Box::new(vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(5.0, 90.0), "Note", style))), + ); + let layer_id = page.layers[0].id; + page.insert(Some(layer_id), 2, note).unwrap(); + let (d, warnings, read) = crate::layered_ai(&private(&both), page, vec![], false, false, 1.0); + assert!(read, "{warnings:?}"); + assert_eq!(text_of(&d.layers[0]).iter().map(|t| t.plain_text()).collect::<Vec<_>>(), ["Note"], "{warnings:?}"); + assert!(!warnings.iter().any(|w| w.contains("left out")), "{warnings:?}"); } /// A palette of `[None]` and White, and a color group `Inks` holding a spot color, Red ink. @@ -979,38 +997,83 @@ fn a_line_the_page_draws_in_pieces_goes_to_its_text_object_whole() { assert!(t.cached_bounds.is_none() && t.cached_baselines.is_empty()); } -#[test] -fn type_of_the_page_that_no_story_places_stays_with_the_nearest_text_object() { - let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); - let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); - let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 30 moveto (Extra) show"; - let r = import(&eps(page, &art)).unwrap(); - let mut all = vec![]; - r.document.walk(|n| { - if let NodeKind::Text(t) = &n.kind { - all.push(t.plain_text()); - } - }); - assert!(all.contains(&"Extra".to_string()), "{all:?} {:?}", r.warnings); +/// `doc` (from [`text_document`], whose stories all name the first frame) with its last story in +/// its own frame, the last, of a kind this doesn't read. +fn last_frame_unread(doc: &str) -> String { + let frames = doc.matches("/2 << /2 [").count(); + let mut doc = doc.to_string(); + let at = doc.rfind("/1 << /0 [ << /0 0 >> ]").unwrap(); + doc.replace_range(at..at + 23, &format!("/1 << /0 [ << /0 {} >> ]", frames - 1)); + let at = doc.rfind("/2 << /2 [").unwrap() + "/2 << ".len(); + doc.insert_str(at, "/0 9 "); + doc } -/// Page type of no text object that lies where made type is, but has other letters, is not that type: -/// it stays, with the nearest text object. -#[test] -fn type_of_the_page_near_made_type_with_other_letters_stays() { - // "Extra" is 11.5 below the line of "Hi there", well inside the box round that line. - let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); - let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); - let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 50 moveto (Extra) show"; - let r = import(&eps(page, &art)).unwrap(); +/// The plain text of every text object in `d`, in order. +fn all_texts(d: &Document) -> Vec<String> { let mut all = vec![]; - r.document.walk(|n| { + d.walk(|n| { if let NodeKind::Text(t) = &n.kind { all.push(t.plain_text()); } }); - assert_eq!(all, ["Hi there", "Extra"], "{:?}", r.warnings); - assert!(r.warnings.iter().any(|w| w.contains("with another's")), "{:?}", r.warnings); + all +} + +/// Type of the page that no story places goes to the text object whose type the text document +/// can't make, not into made type; with no such text object and none of the page's type in a text +/// object, it is art the layers don't draw, which the comparison weighs. +#[test] +fn type_of_the_page_that_no_story_places_goes_to_a_text_object_that_cant_be_made() { + let doc = + last_frame_unread(&text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Note\r", 0, (8200.0, 8120.0), (0.0, 0.0), 0.0)])); + let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 30 moveto (Extra) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert_eq!(all_texts(&r.document), ["Hi there", "Extra"], "{:?}", r.warnings); + // Every text object's type made: the page's "Extra" is in none of them, so the file comes in as its page. + let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let r = import(&eps(page, &native_with_text(&layer("Art", true, &text_object(0)), &doc))).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("layers weren't read")), "{:?}", r.warnings); +} + +/// A story whose first frame's type is made and whose second frame's can't be: the page's type of +/// the first frame stays the made type's, and isn't the second frame's too. +#[test] +fn page_type_of_a_made_frame_isnt_given_to_the_storys_other_frame() { + let mut doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Spare\r", 0, (8200.0, 8160.0), (0.0, 0.0), 0.0)]); + // Story 0 in frames 0 and 1, both point type: point type isn't threaded, so its second frame has none. + let at = doc.find("/1 << /0 [ << /0 0 >> ]").unwrap(); + doc.replace_range(at..at + 23, "/1 << /0 [ << /0 0 >> << /0 1 >> ]"); + let art = native_with_text(&layer("Art", true, &(frame_object(0, 0) + &frame_object(0, 1))), &doc); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert_eq!(all_texts(&r.document), ["Hi there"], "{:?}", r.warnings); +} + +/// Page type of no text object that lies where made type draws, with its words in any case, is that +/// type as the page draws it, and doesn't go to a text object whose type can't be made. Page type +/// with other words there, or beside made type, does. +#[test] +fn type_of_the_page_where_made_type_draws_with_its_words_is_that_type() { + let doc = + last_frame_unread(&text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Note\r", 0, (8200.0, 8120.0), (0.0, 0.0), 0.0)])); + let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc); + let with = |drawn: &str, y: f64| { + format!("0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 {y} moveto ({drawn}) show") + }; + // "THERE" over the line of "Hi there", a point below it. + let r = import(&eps(&with("THERE", 60.5), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert_eq!(all_texts(&r.document), ["Hi there"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.starts_with("1 text objects")), "{:?}", r.warnings); + // "Extra" there, or 11.5 below that line: the text object that can't be made takes it. + for y in [60.5, 50.0] { + let r = import(&eps(&with("Extra", y), &art)).unwrap(); + assert_eq!(all_texts(&r.document), ["Hi there", "Extra"], "{y}: {:?}", r.warnings); + } } /// Page type of no text object that lies where made type is and has its letters, in any case, is that @@ -1075,22 +1138,23 @@ fn type_of_the_page_with_the_letters_of_two_made_types_where_it_lies_is_their_ty } /// The file's text document is trusted where the page has type where it lays type out, whatever -/// letters that type has: its type is weighed against the page. +/// letters that type has: the type is the text document's, and the difference is noted as type. +/// The page's type with other words is left out, with a note that is a loss. #[test] fn page_type_where_made_type_is_trusts_the_text_document_whatever_its_letters() { let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 50 moveto (Extra) show"; let r = import(&eps(page, &art)).unwrap(); - let mut all = vec![]; - r.document.walk(|n| { - if let NodeKind::Text(t) = &n.kind { - all.push(t.plain_text()); - } - }); - assert_eq!(all, ["Extra"], "{:?}", r.warnings); - // "Hi there" was made from the text document and left out because the page doesn't draw it. - assert!(r.warnings.iter().any(|w| w.contains("doesn't draw")), "{:?}", r.warnings); + assert_eq!(all_texts(&r.document), ["Hi there"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.starts_with("the type on the layers differs")), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("doesn't draw")), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.ends_with("so it is left out") && crate::is_loss(w)), "{:?}", r.warnings); + // The page's type with the text document's words, in capitals: nothing is left out. + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 50 moveto (HI THERE) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(all_texts(&r.document), ["Hi there"], "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("left out")), "{:?}", r.warnings); } #[test] @@ -1161,15 +1225,6 @@ fn type_keeps_the_opacity_and_blend_mode_of_its_text_object() { let art = native_with_text(&layer("Art", true, &(drawing.clone() + &format!("{own}1 (Style) XW\n").repeat(50))), &doc); let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); assert_eq!(depth(&d.layers[0]), 4, "{notes:?}"); - // Made type with the page's type of no text object kept after it: a group of the two has it. - let art = native_with_text(&layer("Art", true, &format!("1 0.2 0 0 0 Xy\n{}", text_object(0))), &doc); - let r = import(&eps(&format!("{page} 58.5 30 moveto (Extra) show"), &art)).unwrap(); - assert_eq!(kinds(&r.document.layers[0]), ["group[2]"], "{:?}", r.warnings); - let group = &r.document.layers[0].children().unwrap()[0]; - assert_eq!((group.opacity, group.blend), (0.2, BlendMode::Multiply)); - let texts: Vec<String> = text_of(group).iter().map(|t| t.plain_text()).collect(); - assert_eq!(texts, ["Hi there", "Extra"]); - assert!(group.children().unwrap().iter().all(|p| (p.opacity, p.blend) == (1.0, BlendMode::Normal))); // A story in a frame of a kind this doesn't know: the type that shows is the page's. An EPS page has // no transparency, so its type takes its text object's. let doc = doc.replace("/2 << /2 [ 1 0 0 1 0 0 ] >>", "/2 << /0 9 /2 [ 1 0 0 1 0 0 ] >>"); @@ -1296,8 +1351,9 @@ fn a_run_longer_than_any_text_doesnt_overflow() { #[test] fn more_text_objects_than_are_matched_leave_the_page() { + // Text objects whose type the text document can't make are matched with the page's type. let many = text_object(0).repeat(5001); - let doc = text_document(&[("Hi\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let doc = last_frame_unread(&text_document(&[("Hi\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)])); let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &many)), &doc); let r = import(&eps(&page_square(10, 10), &art)).unwrap(); assert_eq!(names(&r.document), ["Back", "Spare", "Layer 1"], "{:?}", r.warnings); @@ -1440,8 +1496,10 @@ fn art_the_page_doesnt_draw_is_noted_with_its_own_share_and_not_the_types() { let r = import(&page_in_pieces_and_layers(bar)).unwrap(); assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); let notes: Vec<&String> = r.warnings.iter().filter(|w| w.contains("differs from the file's own page")).collect(); - assert_eq!(notes.len(), 1, "{:?}", r.warnings); + // The type, all laid out again from the text document, has a note of its own. + assert_eq!(notes.len(), 2, "{:?}", r.warnings); assert!(notes[0].starts_with("the art on the layers differs from the file's own page in about 0.4% of it (brush strokes"), "{notes:?}"); + assert!(notes[1].starts_with("the type on the layers differs from the file's own page"), "{notes:?}"); } /// An EPS whose page is its art's box `[x0 y0 x1 y1]` (not its artboard, 0 0 100 100), drawing @@ -1587,6 +1645,258 @@ fn area_type_and_type_on_a_path_come_from_the_text_document() { assert!(!r.warnings.iter().any(|w| w.contains("couldn't be read")), "{:?}", r.warnings); } +/// A point type frame at the point (`x`, `y`) of the art. +fn point_frame(x: f64, y: f64) -> String { + let (cx, cy) = canvas(x, y); + format!("<< /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 {cx} {cy} ] >> >> >>") +} + +/// An area type frame of the rectangle `x0 y0 x1 y1` of the art. +fn area_frame(x0: f64, y0: f64, x1: f64, y1: f64) -> String { + format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(x0, y0, x1, y1)) +} + +/// The text of `n` when it is a text object, or a group of one object whose text that is. +fn lone_text(n: &Node) -> Option<String> { + match &n.kind { + NodeKind::Text(t) => Some(t.plain_text()), + NodeKind::Group { .. } => match n.children()?.as_slice() { + [only] => lone_text(only), + _ => None, + }, + _ => None, + } +} + +/// What each object of layer `l` holds as one text object ([`lone_text`]). +fn lone_texts(l: &Node) -> Vec<Option<String>> { + l.children().into_iter().flatten().map(|n| lone_text(n)).collect() +} + +/// `text` as a string of the text document: UTF-16 after its byte order mark, each byte in octal. +fn utf16(text: &str) -> String { + let mut out = String::from("\\376\\377"); + for unit in text.encode_utf16() { + for b in unit.to_be_bytes() { + out.push_str(&format!("\\{b:03o}")); + } + } + out +} + +/// Type the text document makes for every text object that shows stays in each one's own group, +/// on its own layer, however the page draws it: in pieces, in another order, with a quote hung +/// outside its frame. +#[test] +fn type_from_the_text_document_stays_in_its_groups() { + let frames = [ + point_frame(10.0, 90.0), + point_frame(10.0, 78.0), + point_frame(55.0, 90.0), + area_frame(10.0, 40.0, 45.0, 55.0), + area_frame(55.0, 40.0, 90.0, 55.0), + ]; + let style = "/1 8.0"; + let doc = document_of( + &frames, + &[ + story("Alpha\\r", &[0], "/0 0", style), + story("Bravo\\r", &[1], "/0 0", style), + story("Charlie\\r", &[2], "/0 0", style), + story("\"Delta\"\\r", &[3], "/0 0", style), + story("\"Echo\"\\r", &[4], "/0 0", style), + ], + ); + let nested = |s: u32| format!("u\nu\n{}U\nU\n", frame_object(s, 0)); + let single = |s: u32| format!("u\n{}U\n", frame_object(s, 0)); + let words = layer("Words", true, &(nested(0) + &nested(1) + &single(3))); + let more = layer("More", true, &(single(2) + &nested(4))); + let art = native_with_text(&(words + &more), &doc); + // The page paints the third story before the first, each in two pieces, and hangs the area + // type's opening quotes outside their frames, painted last. + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 8 scalefont setfont \ + 55 90 moveto (Char) show 72.3 90 moveto (lie) show 10 90 moveto (Al) show 17.1 90 moveto (pha) show \ + 10 78 moveto (Bravo) show 10 48.5 moveto (Delta\") show 55 48.5 moveto (Echo\") show \ + 7.2 48.5 moveto (\") show 52.2 48.5 moveto (\") show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Words", "More"], "{:?}", r.warnings); + let some = |v: &[&str]| v.iter().map(|s| Some(s.to_string())).collect::<Vec<_>>(); + assert_eq!(lone_texts(&r.document.layers[0]), some(&["Alpha", "Bravo", "\"Delta\""]), "{:?}", r.warnings); + assert_eq!(lone_texts(&r.document.layers[1]), some(&["Charlie", "\"Echo\""]), "{:?}", r.warnings); + assert_eq!(all_texts(&r.document).len(), 5, "{:?}", r.warnings); +} + +/// The page's type isn't matched with the text objects when the text document makes the type of +/// every one: a file of more of them than are matched still comes in with its layers. +#[test] +fn six_thousand_point_stories_open_with_layers() { + let stories: Vec<(String, (f64, f64))> = + (0..6000).map(|i| (format!("S{i}\r"), (8150.0 + f64::from(i % 60), 8150.0 + f64::from(i / 60) * 0.8))).collect(); + let list: Vec<Story<'_>> = stories.iter().map(|(t, at)| (t.as_str(), 0, *at, (0.0, 0.0), 0.0)).collect(); + let doc = text_document(&list); + let objects: String = (0..6000).map(text_object).collect(); + let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Words", true, &objects)), &doc); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + assert_eq!(names(&d), ["Back", "Words"], "{notes:?}"); + assert_eq!(text_of(&d.layers[1]).len(), 6000, "{notes:?}"); +} + +/// A story in a frame of a kind this doesn't read takes the page's type for its own text object +/// only: the others keep the type made from the text document, in their groups, and the page's +/// type beside made type, with its letters, goes to the text object that can't be made. +#[test] +fn a_story_with_an_unknown_frame_kind_falls_back_for_that_slot_only() { + let doc = last_frame_unread(&text_document(&[ + ("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), + ("Low\r", 0, (8160.0, 8221.5), (0.0, 0.0), 0.0), + ("Hi\r", 0, (8200.0, 8191.5), (0.0, 0.0), 0.0), + ])); + let grouped = |s: u32| format!("u\n{}U\n", text_object(s)); + let art = native_with_text(&layer("Art", true, &(grouped(0) + &grouped(1) + &grouped(2))), &doc); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 18.5 20 moveto (Low) show \ + 58.5 50 moveto (Hi) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let some = |v: &[&str]| v.iter().map(|s| Some(s.to_string())).collect::<Vec<_>>(); + assert_eq!(lone_texts(&r.document.layers[0]), some(&["Hi there", "Low", "Hi"]), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("left out")), "{:?}", r.warnings); +} + +/// Type laid out from the text document that the page draws differently (in another font, where +/// the file's isn't installed) keeps the layers, with a note; art that differs still doesn't. +#[test] +fn type_drawn_in_another_font_keeps_the_layers() { + let lines = [("Hello\r", 8221.5), ("World\r", 8201.5), ("Again\r", 8181.5), ("Today\r", 8161.5)]; + let list: Vec<Story<'_>> = lines.iter().map(|(t, y)| (*t, 0, (8146.5, *y), (0.0, 0.0), 0.0)).collect(); + let doc = text_document(&list).replace("/1 14.0", "/1 20.0"); + let objects: String = (0..4).map(text_object).collect(); + // The page draws each line in capitals: a font that isn't this one. + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 20 scalefont setfont \ + 5 85 moveto (HELLO) show 5 65 moveto (WORLD) show 5 45 moveto (AGAIN) show 5 25 moveto (TODAY) show"; + let r = import(&eps(page, &native_with_text(&layer("Art", true, &objects), &doc))).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert_eq!(all_texts(&r.document), ["Hello", "World", "Again", "Today"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.starts_with("the type on the layers differs from the file's own page")), "{:?}", r.warnings); + // A square the page doesn't draw, away from the type: the file comes in as its page. + let block = "0 0 0 1 k\n80 5 m\n90 5 L\n90 15 L\n80 15 L\nf\n"; + let r = import(&eps(page, &native_with_text(&layer("Art", true, &format!("{block}{objects}")), &doc))).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("layers weren't read")), "{:?}", r.warnings); +} + +/// Type laid out from the text document where the page draws nothing is art the page lacks, even +/// with more such text objects than are weighed one by one against the page. +#[test] +fn type_the_page_doesnt_draw_on_bare_page_still_differs() { + let mut list: Vec<Story<'_>> = vec![("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]; + for i in 0..14 { + list.push(("Gm\r", 0, (8146.5 + f64::from(i % 4) * 22.0, 8216.5 + f64::from(i / 4) * 18.0), (0.0, 0.0), 0.0)); + } + let doc = text_document(&list); + let objects: String = (0..15).map(text_object).collect(); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show"; + let r = import(&eps(page, &native_with_text(&layer("Art", true, &objects), &doc))).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("layers weren't read")), "{:?}", r.warnings); +} + +/// A hidden text object whose type the text document can't make takes the page's hidden type, as +/// it does when some shown text object's type can't be made either, but not the page's hidden type +/// of one whose type is made. +#[test] +fn a_hidden_text_object_that_cant_be_made_takes_the_pages_hidden_type() { + let doc = last_frame_unread(&text_document(&[ + ("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), + ("Known\rMore\r", 0, (8200.0, 8200.0), (0.0, 0.0), 0.0), + ("Secret\r", 0, (8200.0, 8160.0), (0.0, 0.0), 0.0), + ])); + let spare = layer("Spare", false, &(text_object(1) + &text_object(2))); + let art = native_with_text(&(layer("Art", true, &format!("{}\n{}", square(10, 10), text_object(0))) + &spare), &doc); + let style = vectorcraft_doc::CharStyle { size: 14.0, ..Default::default() }; + let text = |d: &mut Document, s: &str, y: f64| { + Node::new(d.alloc_id(), NodeKind::Text(Box::new(vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(58.5, y), s, style.clone())))) + }; + // The last text object's type over "Known", in words or in marks only. + for secret in ["Secret", "?!"] { + let mut page = pdf_part(10.0, 86.0); + let shown = text(&mut page, "Hi there", 38.5); + let first = page.layers[0].id; + page.insert(Some(first), 1, shown).unwrap(); + let spare = page.add_layer(Some("Spare")); + // The two lines of "Known More" where its story puts them, and the other over them, painted + // first. + for (i, (s, y)) in [(secret, 60.0), ("Known", 58.5), ("More", 73.0)].into_iter().enumerate() { + let n = text(&mut page, s, y); + page.insert(Some(spare), i, n).unwrap(); + } + if let Some(l) = page.node_mut(spare) { + l.visible = false; + } + let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{secret}: {w:?}"); + assert_eq!(names(&d), ["Art", "Spare"], "{w:?}"); + let texts = |l: usize| text_of(&d.layers[l]).iter().map(|t| t.plain_text()).collect::<Vec<_>>(); + assert_eq!((texts(0), texts(1)), (vec!["Hi there".to_string()], vec!["Known\nMore".to_string(), secret.to_string()]), "{w:?}"); + } +} + +/// A small label the page draws where no text object of the layers has type differs too little to +/// send the file to its page: the import says it is left out. Type the page draws of a hidden +/// text object isn't counted. +#[test] +fn a_small_label_of_the_page_in_no_text_object_is_noted() { + let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Extra\r", 0, (8200.0, 8211.5), (0.0, 0.0), 0.0)]); + let art = native_with_text(&(layer("Art", true, &text_object(0)) + &layer("Spare", false, &text_object(1))), &doc); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 30 moveto (Extra) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art", "Spare"], "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("so it is left out")), "{:?}", r.warnings); + let label = format!("{page} /Helvetica findfont 3 scalefont setfont 10 90 moveto (no.) show"); + let r = import(&eps(&label, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art", "Spare"], "{:?}", r.warnings); + let note = r.warnings.iter().find(|w| *w == "some of the page's type has no text object in the layers, so it is left out"); + assert!(note.is_some_and(|w| crate::is_loss(w)), "{:?}", r.warnings); +} + +/// A line break inside a paragraph (`\x03` in the text document) stays a line break in it. +#[test] +fn a_soft_return_is_a_line_break_in_its_paragraph() { + let doc = text_document(&[("One\\003Two\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Words", true, &text_object(0))), &doc); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + let texts = text_of(&d.layers[1]); + assert_eq!(texts.len(), 1, "{notes:?}"); + assert_eq!(texts[0].plain_text(), "One\u{2028}Two"); + assert!(texts[0].paras.is_empty(), "one paragraph: {:?}", texts[0].paras); +} + +/// A Thai story is one text object however the page splits its type: by word, and its marks +/// above apart from their letters, above the top of its frame. +#[test] +fn a_thai_story_stays_one_text_object() { + let thai = "\u{0E2A}\u{0E38}\u{0E02}\u{0E2A}\u{0E31}\u{0E19}\u{0E15}\u{0E4C} \u{0E27}\u{0E31}\u{0E19}\u{0E40}\u{0E01}\u{0E34}\u{0E14}"; + let doc = document_of(&[area_frame(10.0, 30.0, 90.0, 60.0)], &[story(&utf16(&format!("{thai}\r")), &[0], "/0 0", "/1 14.0")]); + let art = native_with_text(&layer("Art", true, &format!("{}\nu\n{}U\n", square(10, 10), frame_object(0, 0))), &doc); + let mut page = pdf_part(10.0, 86.0); + let layer_id = page.layers[0].id; + let style = vectorcraft_doc::CharStyle { size: 14.0, ..Default::default() }; + // Doc y 40 is the frame's top: the words on its first line, the marks a little above it. + let pieces = [ + ("\u{0E2A}\u{0E38}\u{0E02}\u{0E2A}\u{0E19}\u{0E15}", 10.0, 53.0), + ("\u{0E27}\u{0E19}\u{0E40}\u{0E01}\u{0E14}", 50.0, 53.0), + ("\u{0E31}\u{0E4C}", 24.0, 41.0), + ("\u{0E31}\u{0E34}", 58.0, 41.0), + ]; + for (i, (text, x, y)) in pieces.iter().enumerate() { + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(*x, *y), text, style.clone()); + let n = Node::new(page.alloc_id(), NodeKind::Text(Box::new(t))); + page.insert(Some(layer_id), 1 + i, n).unwrap(); + } + let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{w:?}"); + assert_eq!(names(&d), ["Art"], "{w:?}"); + assert_eq!(all_texts(&d), [thai], "{w:?}"); + assert_eq!(lone_texts(&d.layers[0]).last(), Some(&Some(thai.to_string())), "{w:?}"); +} + /// A story of `text` on frame 0 whose layout sets glyphs `advance` wide round the outside of a /// circle of radius `radius`, the circle's length between their centres `fraction` of an advance. fn round_story(text: &str, advance: f64, radius: f64, fraction: f64) -> String { diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index ce464cc58c..c01f0005e5 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -84,8 +84,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. Where the text document can't say (a frame of another kind, or a document that doesn't agree with the page), type that shows comes from the page into its text object's place (no group around it), and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5%, where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. Where the text document can't say (a frame of another kind, or a document that doesn't agree with the page), type that shows comes from the page into its text object's place (no group around it), and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5%, where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. ## Format by format diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e7e1bbc5f6..97e9abf9f0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1033,11 +1033,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.svgz` file copied in a file manager pastes as its art, as a copied `.svg` file does. SVG export (Save As, Export As, Export for Screens, Asset Export and the clipboard share the writer) writes simple shapes as SVG basic shapes, as the reference app does (an ellipse is an `ellipse` tag until an anchor is added, [forum](https://community.adobe.com/t5/illustrator-discussions/trouble-exporting-shape-with-points-to-svg/td-p/10720325); rectangles come out as `<rect>` and `<polygon>`, [forum](https://community.adobe.com/t5/illustrator-discussions/force-svg-export-using-all-lt-rect-gt/td-p/11282378)): an axis-aligned rectangle as `<rect>`, a circle or ellipse drawn with four standard arcs as `<circle>`/`<ellipse>`, a straight line as `<line>`, and other straight-segment paths as `<polygon>`/`<polyline>`, at the written precision (#4652). A rectangle or ellipse with a dashed stroke, whose dashes would start elsewhere, a turned ellipse, curves and compound paths stay `<path>`. `crates/svg/tests/it/basic_shapes.rs` checks each element, that the picture renders as the canvas does and that the geometry reimports. SVG import keeps attributes in other applications' XML namespaces (`plotter:pen="2"`) on the objects and layers they belong to, as it keeps their `data-*` attributes: copies, duplicates and `.vectorcraft` files keep them, and SVG export writes them back with each namespace declared once on the root (the rest of #522; `crates/svg/tests/it/foreign_attributes.rs`, `tests/attributes.rs`). - In a `.ai` or EPS opened from its editing data, type has its text object's opacity and blend mode, whether it is made from the file's text document or taken from the page. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, that type is left out only when, for each piece of it, one of those text objects has the piece's Latin letters and digits in its text, in capitals or not; other such type is kept as the page's other type of no text object is. + In a `.ai` or EPS opened from its editing data, type has its text object's opacity and blend mode, whether it is made from the file's text document or taken from the page. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. + A `.ai` or EPS opened from its editing data whose text document makes the type of every text object that shows takes all its type from the text document: each text object stays in its own group, frame and layer, the page's type isn't matched with them, a file of more than 5,000 text objects still opens with its layers, and type the page draws differently (in another font) keeps the layers, with a warning. A line break inside a paragraph stays a line break in it (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ate.rs`). In SVG export without Fewer `<tspan>` Elements, each character of live type that justification or Mojikumi moves (the letter gaps of a Justify All line without word spaces, the gaps between the characters of a justified Japanese line, closed-up punctuation, the space between Japanese and Latin letters) starts its own positioned `<tspan>`, and type scaled horizontally on a justified line is stretched to its own width (`crates/svg/tests/it/text_layout.rs`). SVG export (live text), legacy `.ai` saves (text objects), DXF export (`TEXT` entities) and the CSS Properties panel write area type that Shrink Text to Fit scales down at the size it draws at, and scale its tracking, kerning, leading and baseline shifts the same way where the format holds them. A PDF saved with Illustrator's editing data opens through it as a PDF-compatible `.ai` does, with its layers and groups and with art reaching past its page unclipped; such a PDF holds the data in `AIPDFPrivateData` streams (part of #868). A shape a PDF or `.ai` paints with a gradient (a clip path round a shading) opens as one path filled with the gradient, not a clip group round a rectangle, so Shape Builder, Live Paint and Pathfinder work on its outline (#1304). - In a `.ai` opened from its editing data, a text object on a layer that shows and doesn't print stays on that layer, made from the file's text document, even where the page doesn't draw it (`crates/eps/src/import/tests_native.rs`). Such a `.ai` opens without the PDF part's warnings that text was kept as outlines when no outlined glyphs come in, and a warning counts the text objects that hold the page's type next to glyphs the page has only as outlines, which don't come in (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). Where the art of a `.ai` or EPS opened from its editing data differs a little from the file's page, the warning gives the share of the page that differs away from type. When that share is 0.2% or less, the warning names the type and gives the share of the page that differs where the type is (`crates/eps/src/import/tests_native.rs`). + In a `.ai` opened from its editing data, a text object on a layer that shows and doesn't print stays on that layer, made from the file's text document, even where the page doesn't draw it (`crates/eps/src/import/tests_native.rs`). Such a `.ai` opens without the PDF part's warnings that text was kept as outlines when no outlined glyphs come in, and a warning counts the text objects that hold the page's type next to glyphs the page has only as outlines, which don't come in (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). Where the art of a `.ai` or EPS opened from its editing data differs a little from the file's page, the warning gives the share of the page that differs away from type. When that share is 0.2% or less, the warning names the type and gives the share of the page that differs where the type is; when all the type is made from the text document, the type's share has a warning of its own beside the art's (`crates/eps/src/import/tests_native.rs`). PDF text opens with every glyph where the file draws it (#722): the font's kerning or none, whichever the file followed, word and character spacing, `TJ` adjustments and horizontal scaling kept per character as tracking, text rise as baseline shift within its line, vertical glyphs narrower than an em centred on their column (`/W2`, `/W`, `/DW`), justified text boxes with word spacing back as justified area type (`tests_text_placement`, fixtures written from ISO 32000-1 §9). A `.ai` or PDF whose editing data holds a variable library opens with a warning that its variables and data sets weren't read, with how many of each it has, whether its layers are read or it comes in as its PDF part (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). A PDF page whose `UserUnit` (PDF 1.6) is above 1 opens at its size in points, its numbers times the `UserUnit` (one above 75,000 counts as 75,000), and `document.pdfInfo` gives its size and boxes in points too. A `.ai` whose editing data has its artboards in the units of such a page opens from that data at the page's size, with its layers, and when the layers can't be read its pages still take the artboard layout of the data, scaled the same way (part of #1482). From ec8c1cb8d1f59563691017da8db96a52ddd22405 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 1 Nov 2026 00:36:29 +0700 Subject: [PATCH 115/260] Intertwine: a right-click where three or more objects overlap arranges the nearest one Squashed from #4862 onto main. --- crates/doc/src/hit.rs | 21 ++- crates/doc/src/intertwine.rs | 79 +++++++++--- crates/doc/src/mem.rs | 3 + crates/doc/src/node/extras.rs | 6 + crates/doc/src/node/ops.rs | 9 +- crates/doc/src/node/tests.rs | 17 +++ crates/doc/src/node/wire.rs | 37 +++++- crates/engine/src/cmd/intertwine.rs | 164 ++++++++++++++++-------- crates/engine/src/tests/intertwine.rs | 127 ++++++++++++++++++ crates/tools/src/intertwine.rs | 124 +++++++++++++++--- crates/ui-egui/src/canvas/context.rs | 13 +- crates/ui-egui/src/menus/context.rs | 23 +++- crates/ui-egui/src/state.rs | 8 ++ crates/ui-egui/src/tests/contextmenu.rs | 55 ++++++++ docs/gaps.md | 8 +- docs/mcp.md | 13 ++ 16 files changed, 592 insertions(+), 115 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 8379858745..eb436e9711 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -538,20 +538,15 @@ fn hit_children( } /// The order a click at `p` tries the children of `parent` in, front first: their stacking order -/// from the top, except that in an Intertwine group the members drawn over the others at `p` -/// come first (from the top among them too). +/// from the top, except that in an Intertwine group the members are tried in the order they are +/// drawn at `p`, from the top ([`crate::intertwine::tier_at`]). fn hit_order<'a>(parent: &Node, children: &'a [std::sync::Arc<Node>], p: Point) -> impl Iterator<Item = usize> + 'a { - let over: Vec<usize> = if matches!(parent.kind, NodeKind::Intertwine { .. }) { - let contains = |a: &vectorcraft_geom::PathData| fill_contains(&a.to_bezpath(), vectorcraft_geom::FillRule::NonZero, p); - (0..children.len()).rev().filter(|i| children.get(*i).and_then(|c| crate::intertwine::over_area(c)).is_some_and(contains)).collect() - } else { - vec![] - }; - let rest = (0..children.len()).rev().filter({ - let over = over.clone(); - move |i| !over.contains(i) - }); - over.into_iter().chain(rest) + let mut order: Vec<usize> = (0..children.len()).rev().collect(); + if matches!(parent.kind, NodeKind::Intertwine { .. }) { + let tier = |i: usize| children.get(i).map_or(0, |c| crate::intertwine::tier_at(c, p)); + order.sort_by_cached_key(|i| std::cmp::Reverse((tier(*i), *i))); + } + order.into_iter() } /// A click on the strokes of a path or compound path `n` along `bp`: what any visible stroke diff --git a/crates/doc/src/intertwine.rs b/crates/doc/src/intertwine.rs index e22ccbbaf3..8a6ab6786f 100644 --- a/crates/doc/src/intertwine.rs +++ b/crates/doc/src/intertwine.rs @@ -1,36 +1,51 @@ //! Object › Intertwine: objects that pass over and under each other. //! //! An Intertwine group ([`NodeKind::Intertwine`]) keeps its members as they are, in their own -//! stacking order. A member can be drawn over the other members in part of the group: that area -//! is the member's [`crate::node::NodeExtras::intertwine`], in document coordinates. The group -//! draws (and exports, and is hit) as its live expansion ([`expand`]): the members, then, for -//! each member with an area, a copy of it clipped to that area. Where several members are drawn -//! over the others in one place, the upper one in the stacking order ends on top. +//! stacking order. A member can be drawn over other members in part of the group, at a tier: the +//! area of tier 1 is the member's [`crate::node::NodeExtras::intertwine`], and the areas of tiers 2 +//! and up are its [`crate::node::NodeExtras::intertwine_tiers`], in document coordinates. In each +//! place the members are drawn by their tier there (0 outside their areas), and members of one +//! tier in their stacking order, so any order of the members can be set for each overlap area. +//! The group draws (and exports, and is hit) as its live expansion ([`expand`]): the members, +//! then, tier by tier, a copy of each member with an area of that tier clipped to it. //! //! The members stay editable, and Release gives them back as they were (the areas let go). //! Behaviour: <https://helpx.adobe.com/illustrator/using/intertwine-objects.html>. use std::sync::Arc; -use vectorcraft_geom::{FillRule, PathData}; +use vectorcraft_geom::hit::fill_contains; +use vectorcraft_geom::{FillRule, PathData, Point}; use crate::{Node, NodeId, NodeKind}; -/// The area where `n` is drawn over the other members of its Intertwine group (empty: nowhere). -pub fn over_area(n: &Node) -> Option<&PathData> { - n.extras().intertwine.as_deref().filter(|a| !a.is_empty()) +/// The areas where `n` is drawn over other members of its Intertwine group, each with its tier +/// (1 and up); empty ones are left out. +pub fn tier_areas(n: &Node) -> impl Iterator<Item = (usize, &PathData)> { + let e = n.extras(); + e.intertwine + .as_deref() + .map(|a| (1, a)) + .into_iter() + .chain(e.intertwine_tiers.iter().enumerate().map(|(k, a)| (k + 2, a))) + .filter(|(_, a)| !a.is_empty()) } -/// The members of an Intertwine group evaluated as plain art: the members (ids kept), then each -/// member with an area drawn over the others, as a clip group of that area around a copy of it -/// (ids 0: generated art). +/// The tier `n` is drawn at at `p`: the highest tier whose area holds `p` (0: none does). +pub fn tier_at(n: &Node, p: Point) -> usize { + tier_areas(n).filter(|(_, a)| fill_contains(&a.to_bezpath(), FillRule::NonZero, p)).map(|(t, _)| t).max().unwrap_or(0) +} + +/// The members of an Intertwine group evaluated as plain art: the members (ids kept), then, for +/// each tier from 1 up, each member with an area of that tier, as a clip group of that area +/// around a copy of it (ids 0: generated art). pub fn expand(children: &[Arc<Node>]) -> Vec<Node> { let mut out: Vec<Node> = children.iter().map(|c| plain(c)).collect(); - for c in children { - let Some(area) = over_area(c) else { continue }; - if !c.visible { - continue; - } + let mut over: Vec<(usize, usize, &PathData)> = + children.iter().enumerate().filter(|(_, c)| c.visible).flat_map(|(i, c)| tier_areas(c).map(move |(t, a)| (t, i, a))).collect(); + over.sort_by_key(|(t, i, _)| (*t, *i)); + for (_, i, area) in over { + let Some(c) = children.get(i) else { continue }; let mut clip = Node::new(NodeId(0), NodeKind::Path { path: area.clone(), rule: FillRule::NonZero, live: None, clipping: true, guide: false }); clip.appearance = crate::Appearance::default().into(); let mut copy = plain(c); @@ -40,11 +55,13 @@ pub fn expand(children: &[Arc<Node>]) -> Vec<Node> { out } -/// `n` without its Intertwine area (the expansion is plain art). +/// `n` without its Intertwine areas (the expansion is plain art). fn plain(n: &Node) -> Node { let mut n = n.clone(); - if n.extras().intertwine.is_some() { - n.extras_mut().intertwine = None; + if n.extras().intertwine.is_some() || !n.extras().intertwine_tiers.is_empty() { + let mut e = n.extras_mut(); + e.intertwine = None; + e.intertwine_tiers = Vec::new(); } n } @@ -88,6 +105,28 @@ mod tests { assert_eq!((out[2].id, children[1].id), (NodeId(0), NodeId(0)), "generated art has no ids of its own"); } + #[test] + fn copies_are_drawn_tier_by_tier() { + let over = || shapes::rectangle(Rect::new(5.0, 0.0, 10.0, 10.0)); + // The lower member at tier 2, the upper one at tier 1: the lower one ends on top. + let mut a = (*square(1, 0.0)).clone(); + a.extras_mut().intertwine_tiers = vec![over()]; + let mut b = (*square(2, 5.0)).clone(); + b.extras_mut().intertwine = Some(Box::new(over())); + let kids = vec![Arc::new(a), Arc::new(b)]; + assert_eq!((tier_at(&kids[0], Point::new(7.0, 5.0)), tier_at(&kids[1], Point::new(7.0, 5.0))), (2, 1)); + assert_eq!(tier_at(&kids[0], Point::new(2.0, 5.0)), 0); + let out = expand(&kids); + assert_eq!(out.len(), 4, "both members, then the copy of tier 1, then the one of tier 2"); + assert!(out.iter().all(|n| n.extras().intertwine.is_none() && n.extras().intertwine_tiers.is_empty()), "the expansion is plain art"); + let copied = |n: &Node| match &n.kind { + NodeKind::Group { children, clip: true } => children[1].path_data().cloned(), + k => panic!("a clip group: {k:?}"), + }; + assert_eq!(copied(&out[2]).as_ref(), kids[1].path_data()); + assert_eq!(copied(&out[3]).as_ref(), kids[0].path_data()); + } + #[test] fn a_hidden_member_is_not_drawn_over_the_others() { let mut a = (*square(1, 0.0)).clone(); diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index a971a383b5..bf9259943b 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -253,6 +253,9 @@ fn node_bytes(n: &Node, other: Option<&Node>) -> usize { b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize); b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::<Value>() + json_bytes(t)); b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::<PathData>() + path_bytes(a)); + if e.intertwine_tiers.capacity() > 0 { + b += ALLOC + e.intertwine_tiers.capacity() * size_of::<PathData>() + e.intertwine_tiers.iter().map(path_bytes).sum::<usize>(); + } b += e.objects_on_path.as_deref().map_or(0, |o| { ALLOC + size_of::<crate::objects_on_path::ObjectsOnPath>() + o.members.capacity() * size_of::<crate::objects_on_path::Member>() }); diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index 633f9b6967..93145985be 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -44,6 +44,11 @@ pub struct NodeExtras { /// Object › Intertwine: as a member of an Intertwine group, the area (document coordinates, /// filled non-zero) where this object is drawn over the group's other members. pub intertwine: Option<Box<PathData>>, + /// Object › Intertwine: as a member of an Intertwine group, the areas (document coordinates, + /// filled non-zero) where this object is drawn over members that are themselves drawn over + /// others there. Item `k` is the area of tier `k + 2`; [`NodeExtras::intertwine`] is tier 1 + /// (see [`crate::intertwine`]). + pub intertwine_tiers: Vec<PathData>, /// Live Paint group: its Gap Options (Object › Live Paint › Gap Options; `None`: the defaults). pub live_paint_gaps: Option<Box<crate::live_paint::GapOptions>>, /// Object › Objects on Path: the group's path and the objects attached to it (see @@ -76,6 +81,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras { perspective: None, dimension: None, intertwine: None, + intertwine_tiers: Vec::new(), live_paint_gaps: None, objects_on_path: None, colorize: None, diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index edab5f73c9..e5c98886a2 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -496,8 +496,13 @@ impl Node { Arc::make_mut(&mut m.art).transform_scaled(a, sc); } // The area where an Intertwine member is drawn over the others moves with it. - if let Some(area) = self.extras_if_any().and_then(|e| e.intertwine.as_mut()) { - area.transform(a); + if let Some(e) = self.extras_if_any() { + if let Some(area) = e.intertwine.as_mut() { + area.transform(a); + } + for area in &mut e.intertwine_tiers { + area.transform(a); + } } } diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index b4cc7b0722..df675580e2 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -484,6 +484,23 @@ fn objects_are_read_within_the_node_budget() { assert!(with_node_budget(3, read).is_ok()); } +/// An Intertwine member's areas of tier 2 and up are written and read back, and each one counts +/// against [`with_node_budget`] as an object does, so a file of many empty areas is refused. +#[test] +fn intertwine_tiers_are_read_within_the_node_budget() { + let mut n = Node::group(NodeId(1), vec![]); + let area = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)); + n.extras_mut().intertwine_tiers = vec![PathData::default(), area]; + let json = serde_json::to_string(&n).unwrap(); + assert!(json.contains("\"intertwine_tiers\""), "{json}"); + let read = || serde_json::from_str::<Node>(&json); + assert_eq!(with_node_budget(3, read).unwrap(), n, "the object and its two areas fit a budget of three"); + let why = with_node_budget(2, read).unwrap_err().to_string(); + assert!(why.contains("more than 2 objects"), "{why}"); + let plain = serde_json::to_string(&Node::group(NodeId(1), vec![])).unwrap(); + assert!(!plain.contains("intertwine_tiers"), "an object without tiers writes none: {plain}"); +} + /// #3587: fields read before an object's `type` are buffered value by value within /// [`with_buffered_value_budget`], each counted once: a group read back from the buffer buffers /// its own fields again without counting them twice. VectorCraft writes `type` first, which diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index 76d4c3c14a..3456b359e2 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -46,6 +46,7 @@ impl Serialize for Node { e.perspective.is_none(), e.dimension.is_none(), e.intertwine.is_none(), + e.intertwine_tiers.is_empty(), e.live_paint_gaps.is_none(), e.objects_on_path.is_none(), e.colorize.is_none(), @@ -85,6 +86,7 @@ impl Serialize for Node { field!("perspective", &e.perspective); field!("dimension", &e.dimension); field!("intertwine", &e.intertwine); + field!("intertwine_tiers", &e.intertwine_tiers); field!("live_paint_gaps", &e.live_paint_gaps); field!("objects_on_path", &e.objects_on_path); field!("colorize", &e.colorize); @@ -123,11 +125,39 @@ pub fn with_node_budget<T>(max: usize, f: impl FnOnce() -> T) -> T { /// each counts once, and the id usually comes first, before the node's children are read. fn counted_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result<NodeId, D::Error> { let id = NodeId::deserialize(d)?; + count_one()?; + Ok(id) +} + +/// Count one object against [`with_node_budget`]. +fn count_one<E: serde::de::Error>() -> Result<(), E> { if let Some((left, max)) = NODES_LEFT.get() { - let left = left.checked_sub(1).ok_or_else(|| serde::de::Error::custom(format!("the document has more than {max} objects")))?; + let left = left.checked_sub(1).ok_or_else(|| E::custom(format!("the document has more than {max} objects")))?; NODES_LEFT.set(Some((left, max))); } - Ok(id) + Ok(()) +} + +/// A member's Intertwine areas of tier 2 and up, each counting against [`with_node_budget`] as +/// an object does: a compressed file of repeated empty areas stays small while they take memory +/// once read. +fn counted_tiers<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<PathData>, D::Error> { + struct Tiers; + impl<'de> serde::de::Visitor<'de> for Tiers { + type Value = Vec<PathData>; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a list of areas") + } + fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<PathData>, A::Error> { + let mut out = Vec::new(); + while let Some(area) = seq.next_element::<PathData>()? { + count_one()?; + out.push(area); + } + Ok(out) + } + } + d.deserialize_seq(Tiers) } /// How a [`Node`] is read: the flat field list of the file format. Fields move into the node @@ -186,6 +216,8 @@ pub(super) struct NodeWire { dimension: Option<Box<crate::dimension::Dimension>>, #[serde(default)] intertwine: Option<Box<PathData>>, + #[serde(default, deserialize_with = "counted_tiers")] + intertwine_tiers: Vec<PathData>, #[serde(default)] live_paint_gaps: Option<Box<crate::live_paint::GapOptions>>, #[serde(default)] @@ -215,6 +247,7 @@ impl From<NodeWire> for Node { perspective: w.perspective, dimension: w.dimension, intertwine: w.intertwine, + intertwine_tiers: w.intertwine_tiers, live_paint_gaps: w.live_paint_gaps, objects_on_path: w.objects_on_path, colorize: w.colorize, diff --git a/crates/engine/src/cmd/intertwine.rs b/crates/engine/src/cmd/intertwine.rs index 27f1080e1f..23f1be1906 100644 --- a/crates/engine/src/cmd/intertwine.rs +++ b/crates/engine/src/cmd/intertwine.rs @@ -3,18 +3,19 @@ //! `object.intertwine.make` puts the selected objects in an Intertwine group //! (`NodeKind::Intertwine`), `object.intertwine.release` gives them back as they were. In between, //! `object.intertwine.arrange` picks overlap areas, by a click (`at`) or by an enclosed path drawn -//! around them (`area`), and changes which member is drawn on top there: each member keeps the -//! area where it is drawn over the others (`NodeExtras::intertwine`, see -//! `vectorcraft_doc::intertwine`). Object › Expand turns the group into a plain group of what it -//! draws ([`expand_intertwines`]), which Ungroup takes apart. +//! around them (`area`), and changes the order the members are drawn in there: each member keeps +//! the areas where it is drawn over others, by tier (`NodeExtras::intertwine` and +//! `NodeExtras::intertwine_tiers`, see `vectorcraft_doc::intertwine`). Object › Expand turns the +//! group into a plain group of what it draws ([`expand_intertwines`]), which Ungroup takes apart. //! //! An overlap area is a face of the planar arrangement of what the members paint (their fills and //! strokes, type outlined; other objects by their bounds): the part where two or more of them //! overlap, split wherever a member's edge crosses it. //! //! Behaviour: <https://helpx.adobe.com/illustrator/using/intertwine-objects.html> (Make, -//! Release, clicking or drawing around an overlap, Bring to Front and Send to Back where three or -//! more objects overlap). +//! Release, clicking or drawing around an overlap, Bring to Front, Bring Forward, Send Backward +//! and Send to Back where three or more objects overlap: +//! <https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-intertwined-objects.html>). use std::sync::Arc; @@ -62,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> { "Arrange Intertwine Area", [], None, - "{id?: Intertwine group (default: the selected one), at?: [x,y] (the overlap area under this point, as a click picks it) | area?: [[x,y]…] (a closed polygon drawn around overlap areas: every area whose inside it encloses), order?: toggle|front|back (toggle: the object drawn right below the top comes to the front, so two objects swap), member?: id (front and back: the object to move; default: front brings the object right below the top, back sends the top one)} → {count: areas changed, top: [id of the object now on top in each area]}", + "{id?: Intertwine group (default: the selected one), at?: [x,y] (the overlap area under this point, as a click picks it) | area?: [[x,y]…] (a closed polygon drawn around overlap areas: every area whose inside it encloses), order?: toggle|front|forward|backward|back (toggle: the object drawn right below the top comes to the front, so two objects swap; forward and backward move an object one place up or down among the objects in that area; the others keep their order there), member?: id (front, forward, backward and back: the object to move; default: front and forward move the object right below the top, back and backward the top one)} → {count: areas changed (an area already in that order is not changed, and with none changed there is no undo step), top: [id of the object now on top in each changed area]}", has_doc, arrange ), @@ -173,7 +174,10 @@ fn release(s: &mut Session, _: &Value) -> Result<Value> { .flatten() .map(|c| { let mut c = (**c).clone(); - c.extras_mut().intertwine = None; + let mut e = c.extras_mut(); + e.intertwine = None; + e.intertwine_tiers = Vec::new(); + drop(e); c }) .collect(); @@ -228,6 +232,8 @@ pub(crate) fn expand_intertwines(d: &mut Document, roots: &[NodeId]) -> Result<u enum Order { Toggle, Front, + Forward, + Backward, Back, } @@ -244,39 +250,86 @@ fn polygon(v: &Value) -> Option<PathData> { Some(PathData::single(SubPath::polyline(&pts, true))) } -/// `n`'s area with `face` added (`add`) or taken out. -fn with_area(n: &mut Node, face: &PathData, add: bool) { - let old = n.extras().intertwine.as_deref().cloned(); - let new = match (old, add) { +/// Area `old` with `face` added (`add`) or taken out. +fn with_face(old: Option<PathData>, face: &PathData, add: bool) -> Option<PathData> { + match (old, add) { (None, true) => nonempty(face.clone()), (None, false) => None, (Some(a), true) => nonempty(po::boolean(&a, FillRule::NonZero, face, FillRule::NonZero, po::BoolOp::Union)), (Some(a), false) => nonempty(po::boolean(&a, FillRule::NonZero, face, FillRule::NonZero, po::BoolOp::Difference)), - }; - if new.as_ref() != n.extras().intertwine.as_deref() { - n.extras_mut().intertwine = new.map(Box::new); } } -/// Bring member `x` to the front of `face` (`front`) or send it to the back there; returns the -/// member now on top there. -fn arrange_face(children: &mut [Arc<Node>], face: &Face, x: usize, front: bool) -> Option<usize> { - let lowest = face.members.iter().min().copied()?; - let highest = face.members.iter().max().copied()?; - for &i in &face.members { - let Some(c) = children.get_mut(i) else { continue }; - let c = Arc::make_mut(c); - if front { - // Only `x` is drawn over the others here, unless it is on top in its own order. - with_area(c, &face.path, i == x && x != highest); - } else if i == x { - with_area(c, &face.path, false); - } else if x != lowest { - // Every other member is drawn over `x`, keeping their own order among them. - with_area(c, &face.path, true); +/// Draw `n` at `tier` in `face` (0: in its own order): `face` joins its area of that tier and +/// leaves its areas of the other tiers. +fn set_tier(n: &mut Node, face: &PathData, tier: usize) { + let e = n.extras(); + let mut areas: Vec<Option<PathData>> = + std::iter::once(e.intertwine.as_deref().cloned()).chain(e.intertwine_tiers.iter().map(|a| (!a.is_empty()).then(|| a.clone()))).collect(); + if areas.len() < tier { + areas.resize(tier, None); + } + for (k, a) in areas.iter_mut().enumerate() { + *a = with_face(a.take(), face, k + 1 == tier); + } + while areas.len() > 1 && areas.last().is_some_and(Option::is_none) { + areas.pop(); + } + let mut areas = areas.into_iter(); + let first = areas.next().flatten(); + let rest: Vec<PathData> = areas.map(Option::unwrap_or_default).collect(); + if first.as_ref() != n.extras().intertwine.as_deref() || rest != n.extras().intertwine_tiers { + let mut e = n.extras_mut(); + e.intertwine = first.map(Box::new); + e.intertwine_tiers = rest; + } +} + +/// The tiers that draw members in `order` (bottom first): each member one tier above the member +/// below it when it comes before that member in the group's order, else at the same tier. +fn tiers(order: &[usize]) -> Vec<(usize, usize)> { + let mut tier = 0; + let mut below: Option<usize> = None; + order + .iter() + .map(|&i| { + if below.is_some_and(|b| i < b) { + tier += 1; + } + below = Some(i); + (i, tier) + }) + .collect() +} + +/// Draw the members of `face` in `order` there (bottom first), leaving the other areas as they +/// are. +fn arrange_face(children: &mut [Arc<Node>], face: &Face, order: &[usize]) { + for (i, tier) in tiers(order) { + if let Some(c) = children.get_mut(i) { + set_tier(Arc::make_mut(c), &face.path, tier); } } - drawn_order(children, face).last().copied() +} + +/// `drawn` (the members of an area, bottom first) with member `x` moved as `order` says. +fn moved(drawn: &[usize], x: usize, order: Order) -> Vec<usize> { + let mut out = drawn.to_vec(); + let Some(at) = out.iter().position(|i| *i == x) else { return out }; + match order { + Order::Toggle | Order::Front => { + out.remove(at); + out.push(x); + } + Order::Back => { + out.remove(at); + out.insert(0, x); + } + Order::Forward if at + 1 < out.len() => out.swap(at, at + 1), + Order::Backward if at > 0 => out.swap(at - 1, at), + Order::Forward | Order::Backward => {} + } + out } fn arrange(s: &mut Session, p: &Value) -> Result<Value> { @@ -309,15 +362,17 @@ fn arrange(s: &mut Session, p: &Value) -> Result<Value> { let order = match str_param(p, "order").unwrap_or("toggle") { "toggle" => Order::Toggle, "front" => Order::Front, + "forward" => Order::Forward, + "backward" => Order::Backward, "back" => Order::Back, - o => return Err(bad(C, format!("unknown order `{o}`: toggle, front or back"))), + o => return Err(bad(C, format!("unknown order `{o}`: toggle, front, forward, backward or back"))), }; let member = match p.get("member") { Some(v) => Some(checked_id(s, v, C)?), None => None, }; if member.is_some() && order == Order::Toggle { - return Err(bad(C, "member is for order front or back")); + return Err(bad(C, "member is for order front, forward, backward or back")); } let children: Vec<Arc<Node>> = s.doc()?.doc.node(group).and_then(Node::children).cloned().unwrap_or_default(); let member = match member { @@ -345,25 +400,32 @@ fn arrange(s: &mut Session, p: &Value) -> Result<Value> { { return Err(bad(C, "that object is not in the overlap")); } - let tops = s.edit("Intertwine", |d, _| { + // The new order of each area that changes; areas already in that order are left out. + let mut plans: Vec<(&Face, Vec<usize>)> = vec![]; + for face in found.iter().filter(|f| member.is_none_or(|m| f.members.contains(&m))) { + let drawn = drawn_order(&children, face); + let x = match (order, member) { + (_, Some(m)) => Some(m), + (Order::Toggle | Order::Front | Order::Forward, None) => drawn.iter().rev().nth(1).copied(), + (Order::Back | Order::Backward, None) => drawn.last().copied(), + }; + let Some(x) = x else { continue }; + let new = moved(&drawn, x, order); + if new != drawn { + plans.push((face, new)); + } + } + let tops: Vec<u64> = plans.iter().filter_map(|(_, new)| children.get(*new.last()?)).map(|c| c.id.0).collect(); + if plans.is_empty() { + return Ok(json!({ "count": 0, "top": tops })); + } + s.edit("Intertwine", |d, _| { let n = d.node_mut(group).ok_or(EngineError::NoNode(group))?; let NodeKind::Intertwine { children } = &mut n.kind else { return Err(EngineError::NoNode(group)) }; - let mut tops = vec![]; - for face in found.iter().filter(|f| member.is_none_or(|m| f.members.contains(&m))) { - let drawn = drawn_order(children, face); - let (x, front) = match (order, member) { - (Order::Toggle, _) => (drawn.iter().rev().nth(1).copied(), true), - (Order::Front, m) => (m.or(drawn.iter().rev().nth(1).copied()), true), - (Order::Back, m) => (m.or(drawn.last().copied()), false), - }; - let Some(x) = x else { continue }; - if let Some(top) = arrange_face(children, face, x, front) - && let Some(c) = children.get(top) - { - tops.push(c.id.0); - } + for (face, new) in &plans { + arrange_face(children, face, new); } - Ok(tops) + Ok(()) })?; - Ok(json!({ "count": tops.len(), "top": tops })) + Ok(json!({ "count": plans.len(), "top": tops })) } diff --git a/crates/engine/src/tests/intertwine.rs b/crates/engine/src/tests/intertwine.rs index bdd3455f7f..6895d74a07 100644 --- a/crates/engine/src/tests/intertwine.rs +++ b/crates/engine/src/tests/intertwine.rs @@ -135,6 +135,133 @@ fn front_and_back_choose_the_member_where_three_objects_overlap() { assert!(e.to_string().contains("999"), "{e}"); } +/// The rings with a green bar across their top crossing, in front of both, made into an +/// Intertwine group: (group, a, b, c). A, B and C overlap at (50, 30); only A and B at (50, 70). +fn rings_and_bar(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) { + let (a, b) = rings(s); + let c = id_of(&s.execute("shape.rectangle", &json!({"x": 46, "y": 20, "width": 8, "height": 20})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#00ff00"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [c.0], "none": true})).unwrap(); + select(s, &[a, b, c]); + let g = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap()); + (g, a, b, c) +} + +/// The members of the overlap area of Intertwine group `g` at (x, y), in the order they are drawn +/// there, bottom first. +fn order_at(d: &Document, g: NodeId, x: f64, y: f64) -> Vec<NodeId> { + use vectorcraft_tools::intertwine::{drawn_order, face_at, faces}; + let children = d.node(g).unwrap().children().unwrap(); + let face = face_at(&faces(children), vectorcraft_geom::Point::new(x, y)).unwrap(); + drawn_order(children, &face).into_iter().map(|i| children[i].id).collect() +} + +/// Bring Forward and Send Backward move an object one place among the objects of one overlap +/// area, keeping the others' order, so every order of three objects can be set there (C, B, A +/// included); the other areas stay as they are. +#[test] +fn forward_and_backward_move_an_object_one_place_in_an_area() { + let mut s = session(); + let (g, a, b, c) = rings_and_bar(&mut s); + let order = |s: &Session| order_at(&s.doc().unwrap().doc, g, 50.0, 30.0); + let v = arrange(&mut s, json!({"at": [50, 30], "order": "forward", "member": a.0})); + assert_eq!((&v["count"], &v["top"]), (&json!(1), &json!([c.0]))); + assert_eq!(order(&s), [b, a, c]); + arrange(&mut s, json!({"at": [50, 30], "order": "backward", "member": c.0})); + assert_eq!(order(&s), [b, c, a]); + assert!(red(&render(&s), 50, 30), "A is on top"); + let v = arrange(&mut s, json!({"at": [50, 30], "order": "forward", "member": b.0})); + assert_eq!(v["top"], json!([a.0])); + assert_eq!(order(&s), [c, b, a], "the reverse of the group's order"); + assert_eq!(hit(&s, 50.0, 30.0), Some(a), "a click picks the object drawn on top"); + // Without a member: forward moves the object right below the top, backward the top one. + arrange(&mut s, json!({"at": [50, 30], "order": "backward"})); + assert_eq!(order(&s), [c, a, b]); + assert!(blue(&render(&s), 50, 30)); + assert_eq!(hit(&s, 50.0, 30.0), Some(b)); + arrange(&mut s, json!({"at": [50, 30], "order": "forward"})); + assert_eq!(order(&s), [c, b, a]); + // Bring to Front and Send to Back keep the order of the others. + arrange(&mut s, json!({"at": [50, 30], "order": "front", "member": c.0})); + assert_eq!(order(&s), [b, a, c]); + arrange(&mut s, json!({"at": [50, 30], "order": "back", "member": a.0})); + assert_eq!(order(&s), [a, b, c]); + // The crossing where only the rings overlap is as it was. + assert_eq!(order_at(&s.doc().unwrap().doc, g, 50.0, 70.0), [a, b]); + assert!(blue(&render(&s), 50, 70)); + // There only the rings count: forward moves A over B, and C is not in that area. + let v = arrange(&mut s, json!({"at": [50, 70], "order": "forward"})); + assert_eq!(v["top"], json!([a.0])); + assert!(red(&render(&s), 50, 70)); + let e = s.execute("object.intertwine.arrange", &json!({"at": [50, 70], "order": "backward", "member": c.0})).unwrap_err(); + assert!(e.to_string().contains("not in the overlap"), "{e}"); + assert_eq!(order(&s), [a, b, c]); +} + +/// An object already at the end it is moved to is not moved: no area changes and no undo step is +/// recorded. One move is one undo step, and undo, redo and a saved file keep the order. +#[test] +fn a_move_that_changes_nothing_records_nothing_and_orders_survive_undo_and_save() { + let mut s = session(); + let (g, a, b, c) = rings_and_bar(&mut s); + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = undo(&s); + for (order, member) in [("forward", c), ("front", c), ("backward", a), ("back", a)] { + let v = arrange(&mut s, json!({"at": [50, 30], "order": order, "member": member.0})); + assert_eq!((&v["count"], &v["top"]), (&json!(0), &json!([])), "{order}"); + } + assert_eq!(undo(&s), before, "nothing to undo"); + arrange(&mut s, json!({"at": [50, 30], "order": "forward", "member": b.0})); + arrange(&mut s, json!({"at": [50, 30], "order": "backward", "member": c.0})); + arrange(&mut s, json!({"at": [50, 30], "order": "forward", "member": a.0})); + assert_eq!(undo(&s), before + 3, "one undo step a move"); + let order = |s: &Session| order_at(&s.doc().unwrap().doc, g, 50.0, 30.0); + assert_eq!(order(&s), [c, b, a]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(order(&s), [c, a, b]); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(order(&s), [c, b, a]); + let data = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].clone(); + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "rings.vectorcraft", "dataBase64": data})).unwrap(); + assert_eq!(order_at(&o.doc().unwrap().doc, g, 50.0, 30.0), [c, b, a]); + assert!(red(&render(&o), 50, 30) && blue(&render(&o), 50, 70)); + // Expand draws the same. + s.execute("object.expand", &json!({"fill": false, "stroke": false})).unwrap(); + assert!(red(&render(&s), 50, 30) && blue(&render(&s), 50, 70)); +} + +/// Where three or more objects overlap, hovering highlights the outline of the object nearest to +/// the pointer. +#[test] +fn hovering_where_three_overlap_highlights_the_nearest_object() { + use kurbo::Shape; + let mut s = session(); + let view = ViewInfo::default(); + // Squares from x = 0, 20 and 40, 60 wide: all three overlap from x = 40 to 60. + let ids: Vec<NodeId> = + [0, 20, 40].iter().map(|x| id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 60, "height": 60})).unwrap())).collect(); + select(&mut s, &ids); + s.execute("object.intertwine.make", &json!({})).unwrap(); + let highlighted = |s: &mut Session, x: f64| { + s.pointer(&vectorcraft_tools::PointerEvent::new(vectorcraft_tools::PointerKind::Move, x, 30.0), view).unwrap(); + let o = s.overlays(view); + let [vectorcraft_tools::Overlay::Path { path, .. }] = o.as_slice() else { panic!("one highlight: {o:?}") }; + let r = path.bounding_box(); + (r.x0, r.x1) + }; + // Within the half point a 1 pt stroke reaches past each edge. + let near = |(x0, x1): (f64, f64), (e0, e1): (f64, f64)| (x0 - e0).abs() <= 0.6 && (x1 - e1).abs() <= 0.6; + // By the left edge of the third square, then by the right edge of the first one. + let h = highlighted(&mut s, 41.0); + assert!(near(h, (40.0, 100.0)), "{h:?}"); + let h = highlighted(&mut s, 59.0); + assert!(near(h, (0.0, 60.0)), "{h:?}"); + // Where two overlap, the area is highlighted. + let h = highlighted(&mut s, 30.0); + assert!(near(h, (20.0, 40.0)), "{h:?}"); +} + #[test] fn release_gives_the_objects_back_as_they_were() { let mut s = session(); diff --git a/crates/tools/src/intertwine.rs b/crates/tools/src/intertwine.rs index 984b272e6e..fb292ea37c 100644 --- a/crates/tools/src/intertwine.rs +++ b/crates/tools/src/intertwine.rs @@ -7,7 +7,9 @@ //! which member is drawn on top there. //! //! The Intertwine tool is what `object.intertwine.make` and `object.intertwine.edit` leave the -//! canvas in: hovering highlights the overlap area under the pointer, a click arranges it, a drag +//! canvas in: hovering highlights the overlap area under the pointer (where three or more members +//! overlap, the outline of the member nearest to the pointer, which the right-click menu +//! arranges: [`menu_target`]), a click arranges it, a drag //! draws a path around overlap areas (Shift: a rectangle) and arranges every one inside it. //! Esc or Enter goes back to the tool chosen before. Behaviour: //! <https://helpx.adobe.com/illustrator/using/intertwine-objects.html>. @@ -16,7 +18,7 @@ use std::sync::Arc; use kurbo::BezPath; use serde_json::{Value, json}; -use vectorcraft_doc::intertwine::over_area; +use vectorcraft_doc::intertwine::tier_at; use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind}; use vectorcraft_effects as effects; use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath, shapes}; @@ -101,8 +103,18 @@ pub struct Face { /// Every overlap area of `children`. pub fn faces(children: &[Arc<Node>]) -> Vec<Face> { + faces_of(&painted_areas(children)) +} + +/// What each of `children` paints ([`painted_area`]), by child index. +pub fn painted_areas(children: &[Arc<Node>]) -> Vec<Option<PathData>> { + children.iter().map(|c| painted_area(c)).collect() +} + +/// Every overlap area of the members that paint `areas` ([`painted_areas`]). +pub fn faces_of(areas: &[Option<PathData>]) -> Vec<Face> { let shapes: Vec<po::Shape> = - children.iter().enumerate().filter_map(|(i, c)| Some(po::Shape::new(painted_area(c)?, FillRule::NonZero, i as u64))).collect(); + areas.iter().enumerate().filter_map(|(i, a)| Some(po::Shape::new(a.clone()?, FillRule::NonZero, i as u64))).collect(); let key = |k: usize| shapes.get(k).map(|s| s.key as usize); po::regions(&shapes) .into_iter() @@ -124,15 +136,37 @@ pub fn faces_in(faces: &[Face], lasso: &PathData) -> Vec<Face> { faces.iter().filter(|f| contains(lasso, f.inside)).cloned().collect() } -/// The members of `face` in the order they are drawn there, bottom first: those drawn in their -/// own order, then those drawn over the others there, each run in the group's order. +/// The members of `face` in the order they are drawn there, bottom first: by their tier there +/// ([`tier_at`]), and members of one tier in the group's order. pub fn drawn_order(children: &[Arc<Node>], face: &Face) -> Vec<usize> { - let over = |i: &usize| children.get(*i).and_then(|c| over_area(c)).is_some_and(|a| contains(a, face.inside)); + let tier = |i: usize| children.get(i).map_or(0, |c| tier_at(c, face.inside)); let mut order = face.members.clone(); - order.sort_by_key(|i| (over(i), *i)); + order.sort_by_cached_key(|i| (tier(*i), *i)); order } +/// The fewest members an overlap area needs for the right-click menu that arranges one of them. +pub const MENU_MEMBERS: usize = 3; + +/// The member of `face` whose outline (what it paints, `areas` from [`painted_areas`]) is nearest +/// to `p`. +pub fn nearest_member(areas: &[Option<PathData>], face: &Face, p: Point) -> Option<usize> { + let dist = |i: usize| areas.get(i).and_then(Option::as_ref).map(|a| vectorcraft_geom::hit::distance_to_outline(&a.to_bezpath(), p)); + face.members.iter().filter_map(|i| Some((*i, dist(*i)?))).filter(|(_, d)| d.is_finite()).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i) +} + +/// What a right-click at `p` arranges with the Intertwine tool: the Intertwine group of the +/// selection, and the member nearest to `p` (by id) in the overlap area under `p`, when +/// [`MENU_MEMBERS`] or more members overlap there. +pub fn menu_target(doc: &Document, selected: &[NodeId], p: Point) -> Option<(NodeId, NodeId)> { + let g = selected_group(doc, selected)?; + let children = doc.node(g)?.children()?; + let areas = painted_areas(children); + let face = face_at(&faces_of(&areas), p).filter(|f| f.members.len() >= MENU_MEMBERS)?; + let m = nearest_member(&areas, &face, p)?; + Some((g, children.get(m)?.id)) +} + /// The Intertwine group the selection is in, or is (the innermost one around the first selected /// object that is in one). pub fn selected_group(doc: &Document, selected: &[NodeId]) -> Option<NodeId> { @@ -149,6 +183,8 @@ pub fn is_intertwine(n: &Node) -> bool { struct Found { revision: (u64, u64), group: NodeId, + /// What each member paints, by child index. + areas: Arc<Vec<Option<PathData>>>, faces: Arc<Vec<Face>>, } @@ -159,7 +195,8 @@ pub struct IntertwineTool { prev: Option<String>, /// The overlap areas of the group, for the document revision they were found in. cache: Option<Found>, - /// The overlap area under the pointer. + /// What the pointer highlights: the overlap area under it, or where [`MENU_MEMBERS`] or more + /// members overlap, the outline of the member nearest to it. hover: Option<BezPath>, /// A drag's points (document space); the first is where it started. points: Vec<Point>, @@ -170,17 +207,31 @@ pub struct IntertwineTool { impl IntertwineTool { fn faces(&mut self, cx: &ToolContext) -> Option<(NodeId, Arc<Vec<Face>>)> { + self.found(cx).map(|c| (c.group, c.faces.clone())) + } + + /// The overlap areas of the selection's group, found again when the document changed. + fn found(&mut self, cx: &ToolContext) -> Option<&Found> { let g = selected_group(cx.doc, &cx.selection.objects)?; - if let Some(c) = &self.cache - && c.revision == cx.revision - && c.group == g - { - return Some((g, c.faces.clone())); + if !self.cache.as_ref().is_some_and(|c| c.revision == cx.revision && c.group == g) { + let children = cx.doc.node(g)?.children()?; + let areas = painted_areas(children); + let faces = Arc::new(faces_of(&areas)); + self.cache = Some(Found { revision: cx.revision, group: g, areas: Arc::new(areas), faces }); } - let children = cx.doc.node(g)?.children()?; - let f = Arc::new(faces(children)); - self.cache = Some(Found { revision: cx.revision, group: g, faces: f.clone() }); - Some((g, f)) + self.cache.as_ref() + } + + /// What hovering `p` highlights ([`IntertwineTool::hover`]). + fn highlight(&mut self, cx: &ToolContext, p: Point) -> Option<BezPath> { + let found = self.found(cx)?; + let face = face_at(&found.faces, p)?; + if face.members.len() >= MENU_MEMBERS + && let Some(a) = nearest_member(&found.areas, &face, p).and_then(|m| found.areas.get(m)).and_then(Option::as_ref) + { + return Some(a.to_bezpath()); + } + Some(face.path.to_bezpath()) } /// The closed path the drag drew. @@ -209,7 +260,7 @@ impl Tool for IntertwineTool { let p = ev.pos; match ev.kind { PointerKind::Move => { - self.hover = self.faces(cx).and_then(|(_, f)| face_at(&f, p)).map(|f| f.path.to_bezpath()); + self.hover = self.highlight(cx, p); vec![] } PointerKind::Down => { @@ -332,6 +383,43 @@ mod tests { assert_eq!(drawn_order(&kids, &f[0]), [1, 0]); } + #[test] + fn members_drawn_at_higher_tiers_are_drawn_later() { + // Three squares over one another; the bottom one at tier 2, the middle one at tier 1. + let over = || shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + let mut a = (*square(1, 0.0)).clone(); + a.extras_mut().intertwine_tiers = vec![over()]; + let mut b = (*square(2, 0.0)).clone(); + b.extras_mut().intertwine = Some(Box::new(over())); + let kids = vec![Arc::new(a), Arc::new(b), square(3, 0.0)]; + let f = faces(&kids); + assert_eq!(f.len(), 1); + assert_eq!(drawn_order(&kids, &f[0]), [2, 1, 0]); + } + + #[test] + fn the_member_nearest_to_the_pointer_is_picked_where_three_overlap() { + // Squares 20 wide from x = 0, 4 and 8: all three overlap from x = 8 to 20. + let wide = + |id: u64, x: f64| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 20.0)), Appearance::default_art())); + let kids = vec![wide(1, 0.0), wide(2, 4.0), wide(3, 8.0)]; + let areas = painted_areas(&kids); + let all = faces_of(&areas); + let face = face_at(&all, Point::new(14.0, 10.0)).unwrap(); + assert_eq!(face.members, [0, 1, 2]); + // By the left edge of the third square, then by the right edge of the first one. + assert_eq!(nearest_member(&areas, &face, Point::new(8.5, 10.0)), Some(2)); + assert_eq!(nearest_member(&areas, &face, Point::new(19.5, 10.0)), Some(0)); + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let g = d.alloc_id(); + d.insert(Some(l), 0, Node::new(g, NodeKind::Intertwine { children: kids })).unwrap(); + assert_eq!(menu_target(&d, &[g], Point::new(8.5, 10.0)), Some((g, NodeId(3)))); + assert_eq!(menu_target(&d, &[g], Point::new(19.5, 10.0)), Some((g, NodeId(1)))); + assert_eq!(menu_target(&d, &[g], Point::new(6.0, 10.0)), None, "only two overlap there"); + assert_eq!(menu_target(&d, &[], Point::new(8.5, 10.0)), None, "no Intertwine group selected"); + } + #[test] fn a_lasso_takes_the_areas_whose_inside_it_encloses() { let kids = vec![square(1, 0.0), square(2, 5.0)]; diff --git a/crates/ui-egui/src/canvas/context.rs b/crates/ui-egui/src/canvas/context.rs index 8db01d4223..38311b773d 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -4,7 +4,9 @@ use super::{Ui, VectorcraftApp, Xf, json, widgets}; /// Right-click: the object under the pointer is selected first unless it already is, then the /// context menu lists what applies to the selection ([`crate::menus::context_items`]). The locked /// objects under the pointer ([`vectorcraft_doc::hit::locked_objects_at`]) are kept in -/// `ui.context_locked` while the menu is open, for its Unlock submenu. +/// `ui.context_locked` while the menu is open, for its Unlock submenu. With the Intertwine tool, a +/// right-click where three or more objects of the group overlap keeps the selection and puts what +/// it arranges in `ui.context_intertwine` ([`vectorcraft_tools::intertwine::menu_target`]). pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: &Xf) { if resp.secondary_clicked() && let Some(p) = resp.interact_pointer_pos() @@ -12,7 +14,13 @@ pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: let p = xf.to_doc(p); let locked = hit_with(app, p, xf.zoom, |doc, p, opt| Some(vectorcraft_doc::hit::locked_objects_at(doc, p, opt))); app.ui.context_locked = app.session.active().map(|st| st.uid).zip(locked); - if let Some(st) = app.session.active() + app.ui.context_intertwine = app + .session + .active() + .filter(|_| app.session.tool_id() == "intertwine") + .and_then(|st| vectorcraft_tools::intertwine::menu_target(&st.doc, &st.selection.objects, p).map(|(g, m)| (st.uid, g, p, m))); + if app.ui.context_intertwine.is_none() + && let Some(st) = app.session.active() && let Some(top) = selection_hit_at(app, p, xf.zoom).map(|h| h.top_object(st.isolation)) && !st.selection.contains(top) { @@ -23,6 +31,7 @@ pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: let mut clicked = None; if resp.context_menu(|ui| crate::menus::context_menu_body(app, ui, &mut clicked)).is_none() { app.ui.context_locked = None; + app.ui.context_intertwine = None; } if let Some((id, p)) = clicked { crate::menus::invoke(app, &id, p); diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index 9a4284bb17..3af95c6074 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -15,6 +15,21 @@ pub fn context_items(app: &VectorcraftApp) -> Vec<Item> { if st.isolation.is_some() { v.extend([c("Exit Isolation Mode", "object.exitIsolation"), Sep]); } + // With the Intertwine tool, where three or more objects overlap: the object nearest to the + // right-click moves in that overlap area only (`object.intertwine.arrange`), in place of the + // Arrange submenu, which moves objects in the whole group. + let intertwine = app.ui.context_intertwine.filter(|(uid, ..)| *uid == st.uid && app.session.tool_id() == "intertwine"); + if let Some((_, group, at, member)) = intertwine { + let item = + |label, order| cp(label, "object.intertwine.arrange", json!({"id": group.0, "at": [at.x, at.y], "order": order, "member": member.0})); + v.extend([ + item("Bring to Front", "front"), + item("Bring Forward", "forward"), + item("Send Backward", "backward"), + item("Send to Back", "back"), + Sep, + ]); + } // Managing artboards from the canvas: with the Artboard tool, the menu locks and unlocks them // (`artboard.setProps` with `locked` for each artboard named; an entry with none to change is left out). if app.session.tool_id() == "artboard" { @@ -107,11 +122,11 @@ pub fn context_items(app: &VectorcraftApp) -> Vec<Item> { if crate::panels::character::text_style(app).is_some() { v.push(sub("Bullets and Numbering", vec![c("Apply Bullets", "type.applyBullets"), c("Apply Numbers", "type.applyNumbers")])); } + v.extend([c("Make Guides", "view.guides.make"), Sep, sub("Transform", transform_items())]); + if intertwine.is_none() { + v.push(sub("Arrange", arrange_items())); + } v.extend([ - c("Make Guides", "view.guides.make"), - Sep, - sub("Transform", transform_items()), - sub("Arrange", arrange_items()), sub( "Select", vec![c("Next Object Above", "select.nextAbove"), c("Next Object Below", "select.nextBelow"), Sep, c("Deselect", "select.none")], diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index c85f6e6686..2b5c9c379c 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -357,6 +357,13 @@ pub struct UiState { /// saved. #[serde(skip)] pub context_locked: Option<(u64, Vec<vectorcraft_doc::NodeId>)>, + /// What the last right-click on the canvas with the Intertwine tool arranges, with the + /// document's `uid`: the Intertwine group, the point and the object nearest to it where three + /// or more objects overlap ([`vectorcraft_tools::intertwine::menu_target`]). The context menu + /// lists Bring to Front, Bring Forward, Send Backward and Send to Back for that object while it + /// is open. Not saved. + #[serde(skip)] + pub context_intertwine: Option<(u64, vectorcraft_doc::NodeId, vectorcraft_geom::Point, vectorcraft_doc::NodeId)>, /// Last tool shown in each toolbar slot (keyed by the slot's first tool id). #[serde(default)] pub slot_tool: std::collections::BTreeMap<String, String>, @@ -833,6 +840,7 @@ impl Default for UiState { task_bar: true, task_bar_place: TaskBarPlace::default(), context_locked: None, + context_intertwine: None, slot_tool: Default::default(), floating_flyouts: vec![], toolbar_edits: ToolbarEdits::default(), diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index 74e5c27854..e4445ca343 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -288,6 +288,61 @@ fn selected_type_has_apply_numbers() { assert_eq!(text.para_at(0).list.and_then(|l| l.number), Some(vectorcraft_doc::text::NumberStyle::Arabic)); } +/// The members of the overlap area of Intertwine group `g` at (x, y), in the order they are drawn +/// there, bottom first. +fn intertwine_order(app: &VectorcraftApp, g: NodeId, x: f64, y: f64) -> Vec<NodeId> { + use vectorcraft_tools::intertwine::{drawn_order, face_at, faces}; + let st = app.session.active().unwrap(); + let children = st.doc.node(g).unwrap().children().unwrap(); + let face = face_at(&faces(children), Point::new(x, y)).unwrap(); + drawn_order(children, &face).into_iter().map(|i| children[i].id).collect() +} + +/// With the Intertwine tool, a right-click where three or more objects of the group overlap lists +/// Bring to Front, Bring Forward, Send Backward and Send to Back for the object nearest to the +/// pointer in place of the Arrange submenu, and they move it in that overlap area only. Elsewhere +/// the menu is the usual one. +#[test] +fn right_click_where_three_intertwined_objects_overlap_arranges_the_nearest_one() { + let mut app = app(); + // Rectangles from x = 50, 90 and 130, 120 wide: all three overlap from x = 130 to 170. + let wide = |app: &mut VectorcraftApp, x: f64| { + NodeId(app.run("shape.rectangle", json!({"x": x, "y": 50, "width": 120, "height": 100})).unwrap()["id"].as_u64().unwrap()) + }; + let (a, b, c) = (wide(&mut app, 50.0), wide(&mut app, 90.0), wide(&mut app, 130.0)); + app.run("select.set", json!({"ids": [a.0, b.0, c.0]})).unwrap(); + let g = NodeId(app.run("object.intertwine.make", json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(app.session.tool_id(), "intertwine"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let items = ["Bring to Front", "Bring Forward", "Send Backward", "Send to Back"]; + // By the right edge of A (the first rectangle), where all three overlap. + let p = screen(&app, 169.0, 100.0); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert_eq!(app.session.active().unwrap().selection.objects, [g], "the selection stays the group"); + for label in items { + assert!(has(&texts, label), "{label} in {texts:?}"); + } + assert!(!has(&texts, "Arrange"), "no Arrange submenu: {texts:?}"); + let rows: Vec<f32> = items.iter().map(|l| at(&texts, l).y).collect(); + assert!(rows.windows(2).all(|w| w[0] < w[1]), "in that order: {rows:?}"); + let Some(Item::Cmd(_, id, params)) = menus::context_items(&app).into_iter().find(|i| matches!(i, Item::Cmd("Bring Forward", ..))) else { + panic!("no Bring Forward item") + }; + assert_eq!(id, "object.intertwine.arrange"); + assert_eq!((¶ms["id"], ¶ms["order"], ¶ms["member"]), (&json!(g.0), &json!("forward"), &json!(a.0))); + // Bring Forward moves A one place up in that area only. + assert_eq!(intertwine_order(&app, g, 150.0, 100.0), [a, b, c]); + let texts = click(&mut app, &ctx, at(&texts, "Bring Forward"), PointerButton::Primary); + assert!(!has(&texts, "Bring Forward"), "the menu closes"); + assert_eq!(intertwine_order(&app, g, 150.0, 100.0), [b, a, c]); + assert_eq!(intertwine_order(&app, g, 110.0, 100.0), [a, b], "where only A and B overlap"); + // Where only two overlap, the menu is the usual one. + let p = screen(&app, 110.0, 100.0); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert!(has(&texts, "Arrange") && !has(&texts, "Bring Forward"), "{texts:?}"); +} + /// Every label the context menu can show is a menu string, so complete catalogs must translate it. #[test] fn every_context_label_is_a_menu_string() { diff --git a/docs/gaps.md b/docs/gaps.md index eb8d42b54e..b7ffe7f758 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -439,9 +439,11 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done:** Object › Intertwine (#1763): Make, Edit and Release; the Intertwine tool highlights the overlap area under the pointer, a click swaps which object is on top there, and a path (Shift: a rectangle) drawn around overlaps - arranges each one inside it; `object.intertwine.arrange` also brings an object to the front or sends it to the back - where three or more overlap. The group renders, saves and exports through its live expansion. Still missing: the - right-click Bring Forward / Send Backward menu where three or more objects overlap; adding objects to the group by + arranges each one inside it. Where three or more objects overlap, hovering highlights the object nearest to the + pointer, and a right-click offers Bring to Front, Bring Forward, Send Backward and Send to Back for it in that area + (`object.intertwine.arrange` with `order` front, forward, backward or back; + <https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-intertwined-objects.html>). + The group renders, saves and exports through its live expansion. Still missing: adding objects to the group by dragging them in the Layers panel is untested. - **Done (from users' reports):** Object › Create Gradient Mesh on an embedded image turns it into a mesh over its rectangle, with the image's transform kept; each point takes the average colour and opacity of the picture around it diff --git a/docs/mcp.md b/docs/mcp.md index 89afecd0dd..d4898b5170 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1433,6 +1433,19 @@ Group. Construction mode ends when the group was in it. outside the bounds the group's original shapes had before the move, in the move's undo step. A shape whose bounds still overlap them only moves. The Selection tool sends it at the end of a move in Construction mode. +## Intertwine + +`object.intertwine.arrange {id?, at?|area?, order?, member?}` changes the order the objects of an Intertwine group are +drawn in, in the overlap areas under `at` or enclosed by the polygon `area`. `order` is `toggle` (the default: the +object right below the top comes to the front), `front`, `forward`, `backward` or `back`. `forward` and `backward` move +`member` one place up or down among the objects that overlap in that area, and `front` and `back` move it to the top or +the bottom there; the other objects keep their order. Without `member`, `front` and `forward` move the object right +below the top, and `back` and `backward` move the top one. The command returns `{count, top}`: the number of areas +whose order changed and the id of the object now on top in each. A move that changes no area returns +`{count: 0, top: []}` and records no undo step. With the Intertwine tool, a right-click where three or more objects +overlap offers Bring to Front, Bring Forward, Send Backward and Send to Back, which run this command for the object +nearest to the pointer. + ## Global Edit Select › Start Global Edit is `select.globalEdit {appearance?, size?, artboards?, includeCanvas?}`. With one path, From 9bb6d0f51d8bda8a12902ad406966a681eecf94f Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 00:58:52 -0700 Subject: [PATCH 116/260] Eyedropper: Shift-click samples the color of a pattern or gradient mesh Shift-click with the Eyedropper sampled solid colors, gradients and images only; on a pattern fill or a gradient mesh it sampled nothing. - A pattern gives the color of the front-most tile art at the point, placed by the pattern's transform, at any tile size. Tile art that is itself a gradient, image, mesh, symbol or pattern is sampled the same way, and a pattern inside tile art moves with its tile. A gap between the tile art gives the color of what lies below. - A gradient mesh gives the patch color interpolated at the point. - A symbol instance gives the color of its symbol's art at the point. The Live Paint Bucket's Eyedropper sampling and Brush Options' Key Color eyedropper use the same sampling. --- crates/tools/src/xform/eyedropper.rs | 323 ++++++++++++++++++++++++--- 1 file changed, 298 insertions(+), 25 deletions(-) diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 5586b987df..1e612a6cb5 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -4,9 +4,10 @@ //! selection and the paint defaults (`appearance.copyFrom`); Alt-click: the selection's attributes //! onto the clicked object (`reverse`); Shift+Alt-click: add the clicked object's appearance to the //! selection's (`append`). Shift-click: sample only the colour under the cursor into the active -//! fill/stroke (`paint.sampleColor`; in a CMYK document an RGB color is stored as CMYK). Clicking -//! an image samples its pixels (averaged over the options' raster sample size; a CMYK image gives -//! its ink amounts). +//! fill/stroke (`paint.sampleColor`; in a CMYK document an RGB color is stored as CMYK): a +//! gradient's color at that point, a pattern's tile art there (after the pattern's transform), or +//! a gradient mesh's interpolated patch color. Clicking an image samples its pixels (averaged over +//! the options' raster sample size; a CMYK image gives its ink amounts). //! //! The Gradient panel's eyedropper sets the `stop` option (the tool to return to): the next click //! samples the colour under the cursor into the selected gradient stop (`paint.sampleColor @@ -17,9 +18,10 @@ use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::hit::{HitKind, hit_test, hit_test_visible}; -use vectorcraft_doc::{Node, NodeKind}; -use vectorcraft_geom::Point; +use vectorcraft_doc::hit::{HitKind, HitOptions, hit_test, hit_test_visible}; +use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_geom::hit::fill_contains; +use vectorcraft_geom::{Affine, Point, Rect}; use super::paint_owner; use crate::params::color_json; @@ -49,18 +51,83 @@ pub fn paint_color_at(paint: &Paint, bounds: Option<vectorcraft_geom::Rect>, p: } } +/// How many patterns and symbols deep a sample follows art inside art (tile art painted with a +/// pattern, a symbol whose art holds an instance of another): as deep as a document draws. +const MAX_NESTING: usize = vectorcraft_doc::depth::MAX_DRAWN_DEPTH; + +/// Most tiles of one pattern a sample looks at, front to back, for art that paints the point. +const MAX_TILES: usize = 1_000; + +/// The Eyedropper's hit options: a click inside a fill or among characters samples it too, +/// whatever Object and Type Object Selection by Path Only say. +fn sample_options(cx: &ToolContext) -> HitOptions { + HitOptions { path_only: false, type_path_only: false, ..cx.hit_options() } +} + /// The visible object under `p`, using the Eyedropper's source selection rules. pub(crate) fn sample_source(cx: &ToolContext, p: Point) -> Option<(vectorcraft_doc::NodeId, HitKind)> { - let opts = vectorcraft_doc::hit::HitOptions { path_only: false, type_path_only: false, ..cx.hit_options() }; - let h = hit_test_visible(cx.doc, p, opts)?; + let h = hit_test_visible(cx.doc, p, sample_options(cx))?; Some((paint_owner(cx.doc, h.leaf), h.kind)) } -/// The visible color under `p`, including image pixels and intermediate gradient colors. +/// The visible color under `p`, including image pixels, pattern tiles, mesh colors and +/// intermediate gradient colors. pub(crate) fn sample_color_at(cx: &ToolContext, p: Point) -> Option<Color> { - let (id, kind) = sample_source(cx, p)?; - let n = cx.doc.node(id)?; - if matches!(n.kind, NodeKind::Image(_)) { image_color_at(cx, n, p) } else { paint_sample(n, kind == HitKind::Stroke, p) } + color_under(cx, cx.doc, p, sample_options(cx), 0) +} + +/// The color the front-most object of `doc` hit at `p` with `opts` shows there. Where a stroke +/// gives no color at `p` (a gap between its pattern's tiles), the object's own fill there does; +/// an object that gives none at all is passed over for the ones below it. +fn color_under(cx: &ToolContext, doc: &Document, p: Point, opts: HitOptions, depth: usize) -> Option<Color> { + let mut rest: Option<Document> = None; + loop { + let d = rest.as_ref().unwrap_or(doc); + let h = hit_test_visible(d, p, opts)?; + let id = paint_owner(d, h.leaf); + let n = d.node(id)?; + let on_stroke = h.kind == HitKind::Stroke; + let fill = || if on_stroke && fill_covers(n, p) { node_color_at(cx, d, n, false, p, depth) } else { None }; + if let Some(c) = node_color_at(cx, d, n, on_stroke, p, depth).or_else(fill) { + return Some(c); + } + rest.get_or_insert_with(|| doc.clone()).remove(id).ok()?; + } +} + +/// Whether the fill of path or compound path `n` covers `p`. +fn fill_covers(n: &Node, p: Point) -> bool { + match &n.kind { + NodeKind::Path { path, rule, .. } => fill_contains(&path.to_bezpath(), *rule, p), + NodeKind::Compound { rule, .. } => n.stroke_path().is_some_and(|bp| fill_contains(&bp, *rule, p)), + _ => false, + } +} + +/// The color `n` (in `doc`) shows at `p`: an image's pixels, a mesh's interpolated patch color, a +/// symbol instance's art, or the color of its fill (or its stroke, when the stroke was hit or there +/// is no fill) there. `depth` counts the patterns and symbols the sample is already inside. +fn node_color_at(cx: &ToolContext, doc: &Document, n: &Node, on_stroke: bool, p: Point, depth: usize) -> Option<Color> { + match &n.kind { + NodeKind::Image(_) => image_color_at(cx, doc, n, p), + NodeKind::Mesh(m) => { + let (r, c, u, v) = m.locate(p)?; + Some(m.color_at(r, c, u, v).0) + } + NodeKind::SymbolInstance { symbol, xf } => { + symbol_color_at(cx, doc, symbol, *xf, p, depth).or_else(|| paint_sample(cx, doc, n, on_stroke, p, depth)) + } + _ => paint_sample(cx, doc, n, on_stroke, p, depth), + } +} + +/// The color the art of symbol `name` of `doc`, placed in the document by `xf`, shows at `p`. +fn symbol_color_at(cx: &ToolContext, doc: &Document, name: &str, xf: Affine, p: Point, depth: usize) -> Option<Color> { + if xf.determinant().abs() < 1e-12 { + return None; + } + let sym = doc.symbols.iter().find(|s| s.name == name)?; + art_color_at(cx, doc, [(*sym.art).clone()], xf.inverse() * p, depth) } /// Whether the source has fill or stroke paint for an attribute sample. @@ -69,24 +136,82 @@ pub(crate) fn has_sampleable_paint(cx: &ToolContext, id: vectorcraft_doc::NodeId } /// The colour of `n`'s fill (or its stroke, when the stroke was hit or there is no fill) at `p`, -/// sampled in the paint's own space (text space for type runs) and box. -fn paint_sample(n: &Node, on_stroke: bool, p: Point) -> Option<Color> { +/// sampled in the paint's own space (text space for type runs) and box. A pattern gives the color +/// of its tile art at `p` ([`pattern_color_at`]). +fn paint_sample(cx: &ToolContext, doc: &Document, n: &Node, on_stroke: bool, p: Point, depth: usize) -> Option<Color> { let fill_none = n.proxy_paint(false, None).is_none_or(|(p, ..)| p.is_none()); let (paint, to_doc, bounds) = n.proxy_paint(on_stroke || fill_none, None)?; + if let Paint::Pattern { pattern, xf } = paint { + return pattern_color_at(cx, doc, pattern, to_doc * *xf, p, depth); + } let p = if to_doc.determinant().abs() > 1e-12 { to_doc.inverse() * p } else { p }; paint_color_at(paint, Some(bounds), p) } -/// The color of image `n`'s pixels at `p`, averaged over the raster sample size: a CMYK image's -/// ink amounts as they are, other images' sRGB pixels in the working RGB space (the color that -/// shows as that pixel). -fn image_color_at(cx: &ToolContext, n: &Node, p: Point) -> Option<Color> { +/// The color pattern `name` of `doc`, placed in the document by `xf`, shows at `p`: the color of +/// the front-most tile art there. A point the tiles leave empty has no color. +fn pattern_color_at(cx: &ToolContext, doc: &Document, name: &str, xf: Affine, p: Point, depth: usize) -> Option<Color> { + if xf.determinant().abs() < 1e-12 { + return None; + } + let def = doc.patterns.iter().find(|d| d.name == name)?; + // Sampled in pattern space, one tile at a time from the front, among the tiles whose art reaches + // the point (or meets it at an edge). The art moves by whole tiles, and the patterns it is + // painted with move with it. + let q = xf.inverse() * p; + let near = Rect::from_points(q, q).inflate(1e-6, 1e-6); + let bounds: Vec<Option<Rect>> = def.art.iter().map(|a| a.visual_bounds()).collect(); + let reaches = |m: Affine| bounds.iter().any(|b| b.is_none_or(|b| m.transform_rect_bbox(b).inflate(1e-6, 1e-6).contains(q))); + let scaling = vectorcraft_doc::Scaling { patterns: true, ..Default::default() }; + def.offsets_covering(near).into_iter().rev().map(|o| def.instance_xf(o)).filter(|m| reaches(*m)).take(MAX_TILES).find_map(|m| { + let art = def.art.iter().map(|a| { + let mut n = (**a).clone(); + vectorcraft_doc::pattern::place_art(&mut n, m, scaling); + n + }); + art_color_at(cx, doc, art, q, depth) + }) +} + +/// The color the front-most of `art` (in paint order, in the space of `p`) shows at `p`, sampled +/// as [`node_color_at`] samples an object. The art is hit in a scratch document with the images, +/// symbols and patterns of `doc`, with no tolerance around outlines and strokes: only what it +/// paints at `p` counts. +fn art_color_at(cx: &ToolContext, doc: &Document, art: impl IntoIterator<Item = Node>, p: Point, depth: usize) -> Option<Color> { + if depth >= MAX_NESTING { + return None; + } + let mut scratch = Document::new(1.0, 1.0); + scratch.images = doc.images.clone(); + scratch.symbols = doc.symbols.clone(); + scratch.patterns = doc.patterns.clone(); + let layer = scratch.layers.first()?.id; + for mut n in art { + renumber(&mut scratch, &mut n); + scratch.insert(Some(layer), usize::MAX, n).ok()?; + } + let opts = HitOptions { scope: None, tol: 0.0, outline: false, ..sample_options(cx) }; + color_under(cx, &scratch, p, opts, depth + 1) +} + +/// Gives `n` and everything in it new ids from `doc` (pattern instances all have id 0). +fn renumber(doc: &mut Document, n: &mut Node) { + n.id = doc.alloc_id(); + for c in n.children_mut().into_iter().flatten() { + renumber(doc, std::sync::Arc::make_mut(c)); + } +} + +/// The color of image `n`'s pixels (in `doc`) at `p`, averaged over the raster sample size: a CMYK +/// image's ink amounts as they are, other images' sRGB pixels in the working RGB space (the color +/// that shows as that pixel). +fn image_color_at(cx: &ToolContext, doc: &Document, n: &Node, p: Point) -> Option<Color> { let NodeKind::Image(im) = &n.kind else { return None }; if im.xf.determinant().abs() < 1e-12 { return None; } let px = im.xf.inverse() * p; - let blob = cx.doc.images.get(&im.key)?; + let blob = doc.images.get(&im.key)?; let object = (im.width, im.height); if let Some(inks) = blob.sample_cmyk_object(px.x, px.y, object, cx.raster_sample) { let [c, m, y, k] = inks.map(|v| f32::from(v) / 255.0); @@ -106,9 +231,7 @@ impl Tool for EyedropperTool { if ev.kind != PointerKind::Down { return vec![]; } - // A click inside a fill or among characters samples it too, whatever Object and Type - // Object Selection by Path Only say. - let opts = vectorcraft_doc::hit::HitOptions { path_only: false, type_path_only: false, ..cx.hit_options() }; + let opts = sample_options(cx); if self.brush_key_color { let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] }; let back = self.stop.clone().unwrap_or_else(|| "selection".to_string()); @@ -124,7 +247,7 @@ impl Tool for EyedropperTool { } else { sample_source(cx, ev.pos) }; - let Some((src, kind)) = source else { return vec![] }; + let Some((src, _)) = source else { return vec![] }; let Some(n) = cx.doc.node(src) else { return vec![] }; if ev.mods.alt && stop.is_none() { let how = if ev.mods.shift { "append" } else { "reverse" }; @@ -134,8 +257,7 @@ impl Tool for EyedropperTool { if !(ev.mods.shift || stop.is_some() || image) { return vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": src.0 }))]; } - let sampled = if image { image_color_at(cx, n, ev.pos) } else { paint_sample(n, kind == HitKind::Stroke, ev.pos) }; - let Some(c) = sampled else { return vec![] }; + let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] }; let color = color_json(&c); let Some((back, i)) = stop else { return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color }))] }; let out = vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stop": i })), Action::SwitchTool(back.clone())]; @@ -389,6 +511,157 @@ mod tests { ); } + /// An unstroked rectangle filled with `fill`, with id 0 (as pattern and symbol art is). + fn filled_rect(r: vectorcraft_geom::Rect, fill: Paint) -> std::sync::Arc<Node> { + let mut a = vectorcraft_doc::Appearance::default(); + a.set_fill(fill); + std::sync::Arc::new(Node::path(vectorcraft_doc::NodeId(0), vectorcraft_geom::shapes::rectangle(r), a)) + } + + /// [`doc_with_rect`] plus the pattern "Halves": a 20 × 10 tile, red on its left half and blue + /// on its right half. + fn doc_with_halves() -> (vectorcraft_doc::Document, vectorcraft_doc::NodeId) { + use vectorcraft_geom::Rect; + let (mut d, id) = doc_with_rect(); + let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + let mut def = vectorcraft_doc::PatternDef::new( + "Halves", + vec![filled_rect(Rect::new(0.0, 0.0, 10.0, 10.0), red), filled_rect(Rect::new(10.0, 0.0, 20.0, 10.0), blue)], + ); + def.tile = Rect::new(0.0, 0.0, 20.0, 10.0); + d.patterns.push(def); + (d, id) + } + + /// Shift-click on a pattern fill samples the color of the tile art under the cursor, where the + /// pattern's own transform puts it, however small the tiles are. + #[test] + fn shift_click_samples_the_pattern_tile_under_the_cursor() { + use vectorcraft_geom::Affine; + let (mut d, id) = doc_with_halves(); + d.node_mut(id).unwrap().appearance.set_fill(Paint::Pattern { pattern: "Halves".into(), xf: Affine::translate((5.0, 0.0)) }); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let at = |d: &vectorcraft_doc::Document, x: f64| { + EyedropperTool::default().pointer(&cx(d, &s, &p), &PointerEvent::new(PointerKind::Down, x, 155.0).with_mods(shift)) + }; + // Pattern space x 128 (8 into a tile), then x 137 (17 into a tile). + assert_eq!(sampled_hex(&at(&d, 133.0)), "#ff0000"); + assert_eq!(sampled_hex(&at(&d, 142.0)), "#0000ff"); + assert_eq!(crate::xform::eyedropper::sample_color_at(&cx(&d, &s, &p), Point::new(142.0, 155.0)).map(|c| c.to_hex()), Some("#0000ff".into())); + // Art 300 pt wide on a 1 pt tile: about 90,000 tiles reach every point. + let mut wide = vectorcraft_doc::PatternDef::new( + "Wide", + vec![filled_rect(vectorcraft_geom::Rect::new(0.0, 0.0, 300.0, 300.0), Paint::solid(Color::rgb(0.0, 1.0, 0.0)))], + ); + wide.tile = vectorcraft_geom::Rect::new(0.0, 0.0, 1.0, 1.0); + let mut wide_doc = d.clone(); + wide_doc.patterns.push(wide); + wide_doc.node_mut(id).unwrap().appearance.set_fill(vectorcraft_doc::pattern::pattern_paint("Wide")); + assert_eq!(sampled_hex(&at(&wide_doc, 142.0)), "#00ff00"); + // Pattern space x 140, on the edge between two tiles. + let edge = sampled_hex(&at(&d, 145.0)); + assert!(edge == "#ff0000" || edge == "#0000ff", "{edge}"); + // Tiles 0.2 × 0.1 pt, 0.05 pt down: pattern space y 15495, x 15005 (5 into a tile), then + // x 15015 (15 into a tile). + let tiny = Affine::translate((0.0, 0.05)) * Affine::scale(0.01); + d.node_mut(id).unwrap().appearance.set_fill(Paint::Pattern { pattern: "Halves".into(), xf: tiny }); + assert_eq!(sampled_hex(&at(&d, 150.05)), "#ff0000"); + assert_eq!(sampled_hex(&at(&d, 150.15)), "#0000ff"); + } + + /// Tile art painted with another pattern is sampled where that tile draws it: the inner + /// pattern moves with each tile. A symbol instance is sampled from its symbol's art. + #[test] + fn shift_click_samples_patterns_and_symbols_inside_art() { + use vectorcraft_geom::{Affine, Rect}; + let (mut d, id) = doc_with_halves(); + // A 30 pt tile filled with "Halves": every other tile starts halfway through a "Halves" tile. + let mut outer = vectorcraft_doc::PatternDef::new( + "Outer", + vec![filled_rect(Rect::new(0.0, 0.0, 30.0, 10.0), vectorcraft_doc::pattern::pattern_paint("Halves"))], + ); + outer.tile = Rect::new(0.0, 0.0, 30.0, 10.0); + d.patterns.push(outer); + d.node_mut(id).unwrap().appearance.set_fill(vectorcraft_doc::pattern::pattern_paint("Outer")); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + // The tile at x 150 draws "Halves" from x 150: x 165 is 15 into it. + let a = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 165.0, 155.0).with_mods(shift)); + assert_eq!(sampled_hex(&a), "#0000ff"); + // A symbol of a green square, placed at (300, 300) and doubled. + d.symbols.push(vectorcraft_doc::Symbol { + name: "Green".into(), + art: filled_rect(Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(Color::rgb(0.0, 1.0, 0.0))), + }); + let l = d.layers[0].id; + let inst = d.alloc_id(); + let kind = NodeKind::SymbolInstance { symbol: "Green".into(), xf: Affine::translate((300.0, 300.0)) * Affine::scale(2.0) }; + d.insert(Some(l), usize::MAX, Node::new(inst, kind)).unwrap(); + let a = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 310.0, 310.0).with_mods(shift)); + assert_eq!(sampled_hex(&a), "#00ff00"); + } + + /// A gap between a pattern's tile art shows what lies below it, in the document and in the tile + /// art of another pattern. + #[test] + fn a_gap_in_a_pattern_samples_what_lies_below() { + use vectorcraft_doc::pattern::pattern_paint; + use vectorcraft_geom::Rect; + // The white rectangle (100, 100)–(200, 200), under one filled with red 10 pt squares 20 pt apart. + let (mut d, _) = doc_with_rect(); + let mut gappy = + vectorcraft_doc::PatternDef::new("Gappy", vec![filled_rect(Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)))]); + gappy.tile = Rect::new(0.0, 0.0, 20.0, 10.0); + d.patterns.push(gappy); + let (l, top) = (d.layers[0].id, d.alloc_id()); + let mut over = (*filled_rect(Rect::new(100.0, 100.0, 200.0, 200.0), pattern_paint("Gappy"))).clone(); + over.id = top; + d.insert(Some(l), usize::MAX, over).unwrap(); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let at = |d: &vectorcraft_doc::Document, x: f64| { + sampled_hex(&EyedropperTool::default().pointer(&cx(d, &s, &p), &PointerEvent::new(PointerKind::Down, x, 155.0).with_mods(shift))) + }; + // x 125 is 5 into a tile, on a red square; x 133 is 13 into one, between them. + assert_eq!((at(&d, 125.0), at(&d, 133.0)), ("#ff0000".to_string(), "#ffffff".to_string())); + // Tile art: a green rectangle behind one filled with "Gappy". + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + let mut lined = vectorcraft_doc::PatternDef::new( + "Lined", + vec![filled_rect(Rect::new(0.0, 0.0, 20.0, 10.0), green), filled_rect(Rect::new(0.0, 0.0, 20.0, 10.0), pattern_paint("Gappy"))], + ); + lined.tile = Rect::new(0.0, 0.0, 20.0, 10.0); + d.patterns.push(lined); + d.node_mut(top).unwrap().appearance.set_fill(pattern_paint("Lined")); + assert_eq!((at(&d, 125.0), at(&d, 133.0)), ("#ff0000".to_string(), "#00ff00".to_string())); + // A blue fill under a 20 pt stroke of "Gappy", 5 pt left: x 107 is 12 into a tile, in a gap + // of the stroke over the fill. + let shape = &mut d.node_mut(top).unwrap().appearance; + shape.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + shape.set_stroke(Paint::Pattern { pattern: "Gappy".into(), xf: vectorcraft_geom::Affine::translate((-5.0, 0.0)) }); + shape.stroke_mut().unwrap().width = 20.0; + assert_eq!((at(&d, 103.0), at(&d, 107.0)), ("#ff0000".to_string(), "#0000ff".to_string())); + } + + /// Shift-click on a gradient mesh samples the patch color interpolated at the cursor. + #[test] + fn shift_click_samples_the_mesh_color_under_the_cursor() { + use vectorcraft_doc::{Document, GradientMesh}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + // Black on the left edge, white on the right edge. + let mesh = GradientMesh::from_surface(1, 1, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|u, _| { + if u < 0.5 { Color::rgb(0.0, 0.0, 0.0) } else { Color::rgb(1.0, 1.0, 1.0) } + }); + d.insert(Some(l), 0, Node::new(id, NodeKind::Mesh(mesh))).unwrap(); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let a = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 125.0, 150.0).with_mods(shift)); + assert_eq!(sampled_hex(&a), "#404040"); + } + #[test] fn gradient_sampled_along_vector() { let g = vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default()); From 034a327f5b87197a5b94c2207c90be190c778de6 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 07:47:48 -0700 Subject: [PATCH 117/260] Eyedropper: bound the work of one color sample A sample now shares one work limit, counted in objects looked at, across hit tests, pattern tiles and the tile or symbol art it places for hit testing, and gives no color when the limit runs out. Objects that give no color are skipped by id instead of cloning the document for each retry, each nesting level reuses one scratch document that holds only the symbols, and patterns and images are looked up in the sampled document. The sample runs on a deep stack and follows art inside art at most 16 levels deep. A symbol instance is now sampled as it draws: its art is stained by the instance's fill and placed by the instance's transform without moving the patterns in it or scaling its strokes. Between the shapes of its art the sample shows what lies below instead of the stain, and a pattern tile holding an instance is sampled wherever the symbol's art reaches. --- Cargo.lock | 1 + crates/doc/src/hit.rs | 6 + crates/tools/Cargo.toml | 1 + crates/tools/src/xform/eyedropper.rs | 313 ++++++++++++++++++++++----- 4 files changed, 264 insertions(+), 57 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index aeec6db30e..9362671b07 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6499,6 +6499,7 @@ dependencies = [ "kurbo 0.13.1", "serde", "serde_json", + "vectorcraft-brush", "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index eb436e9711..b754e0d565 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -110,6 +110,12 @@ pub fn hit_test_visible(doc: &Document, p: Point, opt: HitOptions) -> Option<Hit hit_test_skipping(doc, p, opt, &|_| false, false) } +/// [`hit_test_visible`] passing over the nodes `skip` names (and their contents): what lies below +/// them at `p`. A skipped clipping path still clips. +pub fn hit_test_visible_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool) -> Option<Hit> { + hit_test_skipping(doc, p, opt, skip, false) +} + /// The object of `selected` (topmost first) whose own art lies under `p` where a clipping mask /// hides it: a clip group (or a layer with a clipping mask) holding it doesn't clip to `p`. A /// click there hits nothing ([`hit_test`]), so the selection tools grab the selection by that diff --git a/crates/tools/Cargo.toml b/crates/tools/Cargo.toml index 1a0f8e6335..042a6f5174 100644 --- a/crates/tools/Cargo.toml +++ b/crates/tools/Cargo.toml @@ -12,6 +12,7 @@ workspace = true vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } vectorcraft-doc = { workspace = true } +vectorcraft-brush = { workspace = true } vectorcraft-pathops = { workspace = true } vectorcraft-effects = { workspace = true } vectorcraft-text = { workspace = true } diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 1e612a6cb5..5620be4d54 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -16,10 +16,12 @@ //! Brush Options' Key Color eyedropper sets `brushKeyColor` and `stop`: the next click samples into //! the open dialog (`brushKeyColor` UI request) and switches back. +use std::collections::HashSet; + use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::hit::{HitKind, HitOptions, hit_test, hit_test_visible}; -use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_doc::hit::{HitKind, HitOptions, hit_test, hit_test_visible, hit_test_visible_skipping}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use vectorcraft_geom::hit::fill_contains; use vectorcraft_geom::{Affine, Point, Rect}; @@ -52,12 +54,47 @@ pub fn paint_color_at(paint: &Paint, bounds: Option<vectorcraft_geom::Rect>, p: } /// How many patterns and symbols deep a sample follows art inside art (tile art painted with a -/// pattern, a symbol whose art holds an instance of another): as deep as a document draws. -const MAX_NESTING: usize = vectorcraft_doc::depth::MAX_DRAWN_DEPTH; +/// pattern, a symbol whose art holds an instance of another). +const MAX_NESTING: usize = 16; /// Most tiles of one pattern a sample looks at, front to back, for art that paints the point. const MAX_TILES: usize = 1_000; +/// Most work one sample does, in objects looked at: each hit test after the first in a document +/// counts the objects of the document and of its symbols, each pattern tile or symbol instance +/// sampled counts the objects of its art, and every hundred tile positions checked count one. +/// Art inside art multiplies them; a sample that would need more gives no color. +const MAX_WORK: usize = 1_000_000; + +/// One color sample: the document, the hit options, the raster sample size and the work left. +struct Sampler<'a> { + doc: &'a Document, + opts: HitOptions, + raster_sample: u32, + /// The objects in the art of the document's symbols, which a hit test may measure. + symbol_nodes: usize, + work: usize, + /// The work ran out: the sample gives no color. + exhausted: bool, +} + +impl Sampler<'_> { + /// Count `n` units of work, or `None` when that is more than is left. + fn spend(&mut self, n: usize) -> Option<()> { + match self.work.checked_sub(n) { + Some(left) => { + self.work = left; + Some(()) + } + None => { + self.work = 0; + self.exhausted = true; + None + } + } + } +} + /// The Eyedropper's hit options: a click inside a fill or among characters samples it too, /// whatever Object and Type Object Selection by Path Only say. fn sample_options(cx: &ToolContext) -> HitOptions { @@ -73,25 +110,45 @@ pub(crate) fn sample_source(cx: &ToolContext, p: Point) -> Option<(vectorcraft_d /// The visible color under `p`, including image pixels, pattern tiles, mesh colors and /// intermediate gradient colors. pub(crate) fn sample_color_at(cx: &ToolContext, p: Point) -> Option<Color> { - color_under(cx, cx.doc, p, sample_options(cx), 0) + let (doc, opts, raster_sample) = (cx.doc, sample_options(cx), cx.raster_sample); + vectorcraft_doc::depth::with_deep_stack(|| { + let symbol_nodes = doc.symbols.iter().map(|s| s.art.count()).sum(); + let mut s = Sampler { doc, opts, raster_sample, symbol_nodes, work: MAX_WORK, exhausted: false }; + let mut levels: Vec<Option<Document>> = (0..MAX_NESTING).map(|_| None).collect(); + let c = color_under(&mut s, doc, &mut levels, p, opts); + c.filter(|_| !s.exhausted) + }) } /// The color the front-most object of `doc` hit at `p` with `opts` shows there. Where a stroke /// gives no color at `p` (a gap between its pattern's tiles), the object's own fill there does; -/// an object that gives none at all is passed over for the ones below it. -fn color_under(cx: &ToolContext, doc: &Document, p: Point, opts: HitOptions, depth: usize) -> Option<Color> { - let mut rest: Option<Document> = None; +/// an object that gives none at all is passed over for the ones below it. `levels` holds the +/// scratch documents for art inside art, one for each level deeper. +fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option<Document>], p: Point, opts: HitOptions) -> Option<Color> { + let mut passed: HashSet<NodeId> = HashSet::new(); + let mut size = None; loop { - let d = rest.as_ref().unwrap_or(doc); - let h = hit_test_visible(d, p, opts)?; - let id = paint_owner(d, h.leaf); - let n = d.node(id)?; + // The first hit test is the one a click makes anyway; each one after it may visit every + // object again. + let cost = + if passed.is_empty() { 1 } else { *size.get_or_insert_with(|| s.symbol_nodes + doc.layers.iter().map(|l| l.count()).sum::<usize>()) }; + s.spend(cost)?; + let h = hit_test_visible_skipping(doc, p, opts, &|id| passed.contains(&id))?; + let id = paint_owner(doc, h.leaf); + let n = doc.node(id)?; let on_stroke = h.kind == HitKind::Stroke; - let fill = || if on_stroke && fill_covers(n, p) { node_color_at(cx, d, n, false, p, depth) } else { None }; - if let Some(c) = node_color_at(cx, d, n, on_stroke, p, depth).or_else(fill) { + if let Some(c) = node_color_at(s, levels, n, on_stroke, p) { return Some(c); } - rest.get_or_insert_with(|| doc.clone()).remove(id).ok()?; + if on_stroke + && fill_covers(n, p) + && let Some(c) = node_color_at(s, levels, n, false, p) + { + return Some(c); + } + if !passed.insert(id) { + return None; + } } } @@ -104,30 +161,34 @@ fn fill_covers(n: &Node, p: Point) -> bool { } } -/// The color `n` (in `doc`) shows at `p`: an image's pixels, a mesh's interpolated patch color, a -/// symbol instance's art, or the color of its fill (or its stroke, when the stroke was hit or there -/// is no fill) there. `depth` counts the patterns and symbols the sample is already inside. -fn node_color_at(cx: &ToolContext, doc: &Document, n: &Node, on_stroke: bool, p: Point, depth: usize) -> Option<Color> { +/// The color `n` shows at `p`: an image's pixels, a mesh's interpolated patch color, a symbol +/// instance's art, or the color of its fill (or its stroke, when the stroke was hit or there is no +/// fill) there. Images, symbols and patterns are looked up in the sampled document. +fn node_color_at(s: &mut Sampler, levels: &mut [Option<Document>], n: &Node, on_stroke: bool, p: Point) -> Option<Color> { match &n.kind { - NodeKind::Image(_) => image_color_at(cx, doc, n, p), + NodeKind::Image(_) => image_color_at(s, n, p), NodeKind::Mesh(m) => { let (r, c, u, v) = m.locate(p)?; Some(m.color_at(r, c, u, v).0) } - NodeKind::SymbolInstance { symbol, xf } => { - symbol_color_at(cx, doc, symbol, *xf, p, depth).or_else(|| paint_sample(cx, doc, n, on_stroke, p, depth)) - } - _ => paint_sample(cx, doc, n, on_stroke, p, depth), + // The instance's fill only stains its art: where the art paints nothing, nothing shows. + NodeKind::SymbolInstance { symbol, xf } => symbol_color_at(s, levels, n, symbol, *xf, p), + _ => paint_sample(s, levels, n, on_stroke, p), } } -/// The color the art of symbol `name` of `doc`, placed in the document by `xf`, shows at `p`. -fn symbol_color_at(cx: &ToolContext, doc: &Document, name: &str, xf: Affine, p: Point, depth: usize) -> Option<Color> { +/// The color the art of symbol `name` shows at `p` as instance `inst` draws it: stained by the +/// instance's fill and placed in the document by `xf`, its strokes and patterns unscaled. +fn symbol_color_at(s: &mut Sampler, levels: &mut [Option<Document>], inst: &Node, name: &str, xf: Affine, p: Point) -> Option<Color> { if xf.determinant().abs() < 1e-12 { return None; } + let doc = s.doc; let sym = doc.symbols.iter().find(|s| s.name == name)?; - art_color_at(cx, doc, [(*sym.art).clone()], xf.inverse() * p, depth) + s.spend(sym.art.count())?; + let mut art = vectorcraft_brush::instance_art(&sym.art, inst); + art.transform(xf, false); + art_color_at(s, levels, [art], p) } /// Whether the source has fill or stroke paint for an attribute sample. @@ -138,60 +199,83 @@ pub(crate) fn has_sampleable_paint(cx: &ToolContext, id: vectorcraft_doc::NodeId /// The colour of `n`'s fill (or its stroke, when the stroke was hit or there is no fill) at `p`, /// sampled in the paint's own space (text space for type runs) and box. A pattern gives the color /// of its tile art at `p` ([`pattern_color_at`]). -fn paint_sample(cx: &ToolContext, doc: &Document, n: &Node, on_stroke: bool, p: Point, depth: usize) -> Option<Color> { +fn paint_sample(s: &mut Sampler, levels: &mut [Option<Document>], n: &Node, on_stroke: bool, p: Point) -> Option<Color> { let fill_none = n.proxy_paint(false, None).is_none_or(|(p, ..)| p.is_none()); let (paint, to_doc, bounds) = n.proxy_paint(on_stroke || fill_none, None)?; if let Paint::Pattern { pattern, xf } = paint { - return pattern_color_at(cx, doc, pattern, to_doc * *xf, p, depth); + return pattern_color_at(s, levels, pattern, to_doc * *xf, p); } let p = if to_doc.determinant().abs() > 1e-12 { to_doc.inverse() * p } else { p }; paint_color_at(paint, Some(bounds), p) } -/// The color pattern `name` of `doc`, placed in the document by `xf`, shows at `p`: the color of -/// the front-most tile art there. A point the tiles leave empty has no color. -fn pattern_color_at(cx: &ToolContext, doc: &Document, name: &str, xf: Affine, p: Point, depth: usize) -> Option<Color> { +/// The color pattern `name`, placed in the document by `xf`, shows at `p`: the color of the +/// front-most tile art there. A point the tiles leave empty has no color. +fn pattern_color_at(s: &mut Sampler, levels: &mut [Option<Document>], name: &str, xf: Affine, p: Point) -> Option<Color> { if xf.determinant().abs() < 1e-12 { return None; } + let doc = s.doc; let def = doc.patterns.iter().find(|d| d.name == name)?; // Sampled in pattern space, one tile at a time from the front, among the tiles whose art reaches // the point (or meets it at an edge). The art moves by whole tiles, and the patterns it is // painted with move with it. let q = xf.inverse() * p; let near = Rect::from_points(q, q).inflate(1e-6, 1e-6); - let bounds: Vec<Option<Rect>> = def.art.iter().map(|a| a.visual_bounds()).collect(); + let (mut art_nodes, mut instances) = (0, false); + for a in &def.art { + a.walk(&mut |n| { + art_nodes += 1; + instances |= matches!(n.kind, NodeKind::SymbolInstance { .. }); + }); + } + // Symbol instances in the art are measured by their symbols' art. + s.spend(1 + art_nodes + if instances { s.symbol_nodes } else { 0 })?; + let symbols = doc.symbol_boxes(); + let bounds: Vec<Option<Rect>> = def.art.iter().map(|a| a.visual_bounds_with(&symbols)).collect(); let reaches = |m: Affine| bounds.iter().any(|b| b.is_none_or(|b| m.transform_rect_bbox(b).inflate(1e-6, 1e-6).contains(q))); let scaling = vectorcraft_doc::Scaling { patterns: true, ..Default::default() }; - def.offsets_covering(near).into_iter().rev().map(|o| def.instance_xf(o)).filter(|m| reaches(*m)).take(MAX_TILES).find_map(|m| { + let offsets = def.offsets_covering(near); + // Each tile position is checked against each piece of art: a hundred checks count as one unit. + s.spend(offsets.len().saturating_mul(bounds.len().max(1)) / 100)?; + for m in offsets.into_iter().rev().map(|o| def.instance_xf(o)).filter(|m| reaches(*m)).take(MAX_TILES) { + s.spend(1 + art_nodes)?; let art = def.art.iter().map(|a| { let mut n = (**a).clone(); vectorcraft_doc::pattern::place_art(&mut n, m, scaling); n }); - art_color_at(cx, doc, art, q, depth) - }) + if let Some(c) = art_color_at(s, levels, art, q) { + return Some(c); + } + } + None } /// The color the front-most of `art` (in paint order, in the space of `p`) shows at `p`, sampled -/// as [`node_color_at`] samples an object. The art is hit in a scratch document with the images, -/// symbols and patterns of `doc`, with no tolerance around outlines and strokes: only what it -/// paints at `p` counts. -fn art_color_at(cx: &ToolContext, doc: &Document, art: impl IntoIterator<Item = Node>, p: Point, depth: usize) -> Option<Color> { - if depth >= MAX_NESTING { - return None; +/// as [`node_color_at`] samples an object, with no tolerance around outlines and strokes: only +/// what it paints at `p` counts. The art is hit in the first of `levels`, a scratch document with +/// the sampled document's symbols, made on first use and emptied for each new piece of art; art +/// inside it uses the levels after it. With no level left, the art gives no color. +fn art_color_at(s: &mut Sampler, levels: &mut [Option<Document>], art: impl IntoIterator<Item = Node>, p: Point) -> Option<Color> { + let (slot, deeper) = levels.split_first_mut()?; + let doc = s.doc; + let scratch = slot.get_or_insert_with(|| { + let mut d = Document::new(1.0, 1.0); + d.symbols = doc.symbols.clone(); + d + }); + let layer = scratch.layers.first()?; + let (layer, placed) = (layer.id, layer.children().map(|c| c.iter().map(|n| n.id).collect::<Vec<_>>()).unwrap_or_default()); + for id in placed { + scratch.remove(id).ok()?; } - let mut scratch = Document::new(1.0, 1.0); - scratch.images = doc.images.clone(); - scratch.symbols = doc.symbols.clone(); - scratch.patterns = doc.patterns.clone(); - let layer = scratch.layers.first()?.id; for mut n in art { - renumber(&mut scratch, &mut n); + renumber(scratch, &mut n); scratch.insert(Some(layer), usize::MAX, n).ok()?; } - let opts = HitOptions { scope: None, tol: 0.0, outline: false, ..sample_options(cx) }; - color_under(cx, &scratch, p, opts, depth + 1) + let opts = HitOptions { scope: None, tol: 0.0, outline: false, ..s.opts }; + color_under(s, scratch, deeper, p, opts) } /// Gives `n` and everything in it new ids from `doc` (pattern instances all have id 0). @@ -202,22 +286,22 @@ fn renumber(doc: &mut Document, n: &mut Node) { } } -/// The color of image `n`'s pixels (in `doc`) at `p`, averaged over the raster sample size: a CMYK -/// image's ink amounts as they are, other images' sRGB pixels in the working RGB space (the color -/// that shows as that pixel). -fn image_color_at(cx: &ToolContext, doc: &Document, n: &Node, p: Point) -> Option<Color> { +/// The color of image `n`'s pixels at `p`, averaged over the raster sample size: a CMYK image's ink +/// amounts as they are, other images' sRGB pixels in the working RGB space (the color that shows +/// as that pixel). +fn image_color_at(s: &Sampler, n: &Node, p: Point) -> Option<Color> { let NodeKind::Image(im) = &n.kind else { return None }; if im.xf.determinant().abs() < 1e-12 { return None; } let px = im.xf.inverse() * p; - let blob = doc.images.get(&im.key)?; + let blob = s.doc.images.get(&im.key)?; let object = (im.width, im.height); - if let Some(inks) = blob.sample_cmyk_object(px.x, px.y, object, cx.raster_sample) { + if let Some(inks) = blob.sample_cmyk_object(px.x, px.y, object, s.raster_sample) { let [c, m, y, k] = inks.map(|v| f32::from(v) / 255.0); return Some(Color::cmyk(c, m, y, k)); } - let [r, g, b, _] = blob.sample_object(px.x, px.y, object, cx.raster_sample)?; + let [r, g, b, _] = blob.sample_object(px.x, px.y, object, s.raster_sample)?; let [r, g, b] = vectorcraft_color::cms::active().srgb_to_rgb([r, g, b].map(|v| f32::from(v) / 255.0)); Some(Color::rgb(r, g, b)) } @@ -602,6 +686,121 @@ mod tests { assert_eq!(sampled_hex(&a), "#00ff00"); } + /// A symbol instance is sampled as it draws: its art stained by the instance's fill, and a + /// pattern in its art left where the document puts it when the instance moves. + #[test] + fn symbol_samples_follow_the_instances_stain_and_placement() { + use vectorcraft_geom::{Affine, Rect}; + let (mut d, _) = doc_with_halves(); + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + d.symbols.push(vectorcraft_doc::Symbol { name: "Red".into(), art: filled_rect(Rect::new(0.0, 0.0, 20.0, 10.0), red) }); + d.symbols.push(vectorcraft_doc::Symbol { + name: "Tiled".into(), + art: filled_rect(Rect::new(0.0, 0.0, 20.0, 10.0), vectorcraft_doc::pattern::pattern_paint("Halves")), + }); + let l = d.layers[0].id; + let place = |d: &mut vectorcraft_doc::Document, name: &str, at: (f64, f64), stain: Option<Color>| { + let id = d.alloc_id(); + let mut n = Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::translate(at) }); + if let Some(c) = stain { + n.appearance.set_fill(Paint::solid(c)); + } + d.insert(Some(l), usize::MAX, n).unwrap(); + }; + place(&mut d, "Red", (300.0, 300.0), Some(Color::rgb(0.0, 0.0, 1.0))); + place(&mut d, "Tiled", (310.0, 400.0), None); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let at = |x: f64, y: f64| { + sampled_hex(&EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift))) + }; + assert_eq!(at(305.0, 305.0), "#0000ff", "stained"); + // Document x 312 is 12 into a "Halves" tile, though only 2 into the instance's art. + assert_eq!(at(312.0, 405.0), "#0000ff", "pattern in place"); + } + + /// Between the shapes of a stained instance's art, the eyedropper samples what lies below, not + /// the stain; and a pattern tile is sampled wherever its symbol art reaches. + #[test] + fn symbol_art_decides_where_an_instance_paints() { + use std::sync::Arc; + use vectorcraft_doc::NodeId; + use vectorcraft_geom::{Affine, Rect}; + let (mut d, id) = doc_with_rect(); + let red = || Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let pair = + Node::group(NodeId(0), vec![filled_rect(Rect::new(0.0, 0.0, 10.0, 10.0), red()), filled_rect(Rect::new(20.0, 0.0, 30.0, 10.0), red())]); + d.symbols.push(vectorcraft_doc::Symbol { name: "Pair".into(), art: Arc::new(pair) }); + let (l, inst) = (d.layers[0].id, d.alloc_id()); + let mut n = Node::new(inst, NodeKind::SymbolInstance { symbol: "Pair".into(), xf: Affine::translate((100.0, 140.0)) }); + n.appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + d.insert(Some(l), usize::MAX, n).unwrap(); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let at = |d: &vectorcraft_doc::Document, x: f64, y: f64| { + sampled_hex(&EyedropperTool::default().pointer(&cx(d, &s, &p), &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift))) + }; + assert_eq!((at(&d, 105.0, 145.0), at(&d, 115.0, 145.0)), ("#0000ff".to_string(), "#ffffff".to_string())); + // A 200 pt tile holding an instance of a 180 pt green bar, which reaches far past the + // square an instance is measured by without its symbol. + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + d.symbols.push(vectorcraft_doc::Symbol { name: "Bar".into(), art: filled_rect(Rect::new(0.0, 0.0, 180.0, 10.0), green) }); + let bar = Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::IDENTITY })); + let mut bars = vectorcraft_doc::PatternDef::new("Bars", vec![bar]); + bars.tile = Rect::new(0.0, 0.0, 200.0, 10.0); + d.patterns.push(bars); + d.node_mut(id).unwrap().appearance.set_fill(vectorcraft_doc::pattern::pattern_paint("Bars")); + assert_eq!(at(&d, 150.0, 155.0), "#00ff00"); + } + + /// Patterns whose tile art is painted with the next one, on tiles far smaller than their art, + /// symbols whose art holds four instances of the next, and symbols nested far deeper than a + /// sample follows: each sample stops within its work limit and gives no color, instead of + /// trying every tile or instance at every level or running out of stack. + #[test] + fn nested_patterns_and_symbols_sample_within_the_work_limit() { + use std::sync::Arc; + use vectorcraft_doc::pattern::pattern_paint; + use vectorcraft_doc::{NodeId, Symbol}; + use vectorcraft_geom::{Affine, Rect}; + let (mut d, id) = doc_with_rect(); + // "Nest0" to "Nest7": 300 pt art on 1 pt tiles, each painted with the next. "Nest8" doesn't + // exist, so no tile gives a color and every one is tried. + for i in 0..8 { + let mut def = vectorcraft_doc::PatternDef::new( + &format!("Nest{i}"), + vec![filled_rect(Rect::new(0.0, 0.0, 300.0, 300.0), pattern_paint(&format!("Nest{}", i + 1)))], + ); + def.tile = Rect::new(0.0, 0.0, 1.0, 1.0); + d.patterns.push(def); + } + d.node_mut(id).unwrap().appearance.set_fill(pattern_paint("Nest0")); + // "Fan0" to "Fan11": four instances of the next symbol; "Fan12" a square filled with "Nest8". + let instance = |name: String| Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name, xf: Affine::IDENTITY })); + for i in 0..12 { + let art = Node::group(NodeId(0), (0..4).map(|_| instance(format!("Fan{}", i + 1))).collect()); + d.symbols.push(Symbol { name: format!("Fan{i}"), art: Arc::new(art) }); + } + d.symbols.push(Symbol { name: "Fan12".into(), art: filled_rect(Rect::new(300.0, 300.0, 400.0, 400.0), pattern_paint("Nest8")) }); + // "Deep0" to "Deep99": one instance of the next; "Deep100" a green square. + for i in 0..100 { + d.symbols.push(Symbol { name: format!("Deep{i}"), art: instance(format!("Deep{}", i + 1)) }); + } + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + d.symbols.push(Symbol { name: "Deep100".into(), art: filled_rect(Rect::new(300.0, 0.0, 400.0, 100.0), green) }); + let l = d.layers[0].id; + for name in ["Fan0", "Deep0"] { + let inst = d.alloc_id(); + d.insert(Some(l), usize::MAX, Node::new(inst, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap(); + } + let (s, p) = (Selection::default(), paint()); + let start = std::time::Instant::now(); + for at in [Point::new(150.0, 150.0), Point::new(350.0, 350.0), Point::new(350.0, 50.0)] { + assert_eq!(sample_color_at(&cx(&d, &s, &p), at), None, "{at:?}"); + } + assert!(start.elapsed() < std::time::Duration::from_secs(60), "{:?}", start.elapsed()); + } + /// A gap between a pattern's tile art shows what lies below it, in the document and in the tile /// art of another pattern. #[test] From a8b3786f8c291d0264a8fcf8b1f9cf626c306720 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 01:07:45 -0700 Subject: [PATCH 118/260] Symbols: Delete Symbol asks first, and Alt-click deletes an unused symbol without asking The Symbols panel's Delete Symbol button and menu item now ask before deleting. A symbol no instance uses gets "Delete the selected symbol?" with Yes and No. A symbol with placed instances gets Expand Instances, which turns the instances into ordinary art, Delete Instances, which removes them, and Cancel; either Instances button deletes the symbol in one undo step. Alt-click on the button deletes an unused symbol at once and still asks about one with instances. The question is bound to the document it was asked in: once another document is active, or the symbol is gone, Yes deletes nothing, and a symbol that gained instances while the question was open gets the in-use question instead. symbol.delete itself does not ask. The shared dialog frame takes a Cancel label (DialogSpec::cancel) for the No button. The new strings have rows in every catalog. --- crates/ui-egui/src/dialogs.rs | 9 +- crates/ui-egui/src/dialogs/symbol_delete.rs | 100 ++++++++++ crates/ui-egui/src/i18n/bg.tsv | 6 + crates/ui-egui/src/i18n/bs.tsv | 6 + crates/ui-egui/src/i18n/ca.tsv | 6 + crates/ui-egui/src/i18n/cs.tsv | 6 + crates/ui-egui/src/i18n/da.tsv | 6 + crates/ui-egui/src/i18n/de.tsv | 6 + crates/ui-egui/src/i18n/el.tsv | 6 + crates/ui-egui/src/i18n/es.tsv | 6 + crates/ui-egui/src/i18n/fi.tsv | 6 + crates/ui-egui/src/i18n/fr.tsv | 6 + crates/ui-egui/src/i18n/hu.tsv | 6 + crates/ui-egui/src/i18n/id.tsv | 6 + crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/ja.tsv | 6 + crates/ui-egui/src/i18n/ka.tsv | 6 + crates/ui-egui/src/i18n/ko.tsv | 6 + crates/ui-egui/src/i18n/nl.tsv | 7 + crates/ui-egui/src/i18n/pl.tsv | 6 + crates/ui-egui/src/i18n/pt-br.tsv | 6 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/sv.tsv | 6 + crates/ui-egui/src/i18n/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + crates/ui-egui/src/i18n/vi.tsv | 6 + crates/ui-egui/src/i18n/zh-hans.tsv | 6 + crates/ui-egui/src/i18n/zh-hant.tsv | 6 + crates/ui-egui/src/panels/symbols.rs | 208 +++++++++++++++++++- docs/target-app-parity.md | 1 + 30 files changed, 471 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/symbol_delete.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 83e7850f4e..488cd1d956 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -106,6 +106,7 @@ pub mod spot_colors; pub(crate) mod svg_options; pub mod swatch_conflict; pub mod swatch_options; +pub mod symbol_delete; pub mod symbol_options; pub mod symbolism_options; mod text_export; @@ -175,6 +176,8 @@ pub(crate) struct DialogSpec { pub confirm: fn(&mut VectorcraftApp, &Dialog) -> DialogResult, /// The OK button's label. None: no OK button, Enter does nothing and Cancel reads "Close". pub ok: Option<&'static str>, + /// The Cancel button's label when it is not "Cancel" ("No"). Only with an `ok`. + pub cancel: Option<&'static str>, /// An extra button left of Cancel that sets `discard: true` and confirms ("Don't Save"). pub discard: Option<&'static str>, /// A button left of Cancel, as (label, field), that sets `field: true` and confirms, as OK @@ -217,6 +220,7 @@ impl DialogSpec { Ok(Value::Null) }, ok: Some("OK"), + cancel: None, discard: None, alternate: None, reset: None, @@ -371,6 +375,8 @@ registry! { ShapeBuilderOptions: [shape_builder_options::KIND] => shape_builder_options::SPEC, FlareOptions: [flare_options::KIND] => flare_options::SPEC, SymbolOptions: [symbol_options::KIND] => symbol_options::SPEC, + DeleteSymbol: [symbol_delete::KIND] => symbol_delete::SPEC, + DeleteUsedSymbol: [symbol_delete::USED] => symbol_delete::USED_SPEC, SymbolismOptions: [symbolism_options::KIND] => symbolism_options::SPEC, PerspectiveGridPresets: [perspective_presets::KIND] => perspective_presets::SPEC, PerspectiveGridOptions: [perspective_options::KIND] => perspective_options::SPEC, @@ -397,6 +403,7 @@ pub fn button_labels() -> Vec<&'static str> { let mut v = vec!["Cancel", "Close"]; for spec in std::iter::once(&DialogSpec::FORM).chain(DialogKind::ALL.iter().map(|k| k.spec())) { v.extend(spec.ok); + v.extend(spec.cancel); v.extend(spec.discard); v.extend(spec.alternate.map(|(label, _)| label)); v.extend(spec.reset.map(|_| "Reset")); @@ -638,7 +645,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let label = if resets { "Reset" } else if spec.ok.is_some() { - "Cancel" + spec.cancel.unwrap_or("Cancel") } else { "Close" }; diff --git a/crates/ui-egui/src/dialogs/symbol_delete.rs b/crates/ui-egui/src/dialogs/symbol_delete.rs new file mode 100644 index 0000000000..730c00cb4d --- /dev/null +++ b/crates/ui-egui/src/dialogs/symbol_delete.rs @@ -0,0 +1,100 @@ +//! The Symbols panel's Delete Symbol question ([`ask`]). A symbol no instance uses gets "Delete the +//! selected symbol?" with Yes and No ([`KIND`]); a symbol with placed instances gets Expand +//! Instances, Delete Instances and Cancel ([`USED`]). +//! +//! Fields: `name` (the symbol) and `doc` (the [`vectorcraft_engine::DocState::uid`] of the document +//! it was asked in). Yes or either Instances button deletes the symbol only while that document is +//! the active one and still has the symbol; an unused symbol that has gained instances since asks +//! the in-use question instead. + +use serde_json::{Value, json}; + +use super::{DialogResult, DialogSpec}; +use crate::VectorcraftApp; +use crate::state::Dialog; + +/// The dialog kind of the question for a symbol no instance uses. +pub const KIND: &str = "deleteSymbol"; + +/// The dialog kind of the question for a symbol with placed instances. +pub const USED: &str = "deleteUsedSymbol"; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Delete the selected symbol?").into(), + body: |_, _, _| false, + confirm: confirm_unused, + ok: Some("Yes"), + cancel: Some("No"), + max_width: Some(420.0), + ..DialogSpec::FORM +}; + +pub(super) const USED_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted.").into(), + body: |_, _, _| false, + confirm: confirm_used, + ok: Some("Expand Instances"), + discard: Some("Delete Instances"), + max_width: Some(420.0), + ..DialogSpec::FORM +}; + +/// Delete Symbol for symbol `name` of the active document. A symbol with instances always asks +/// what becomes of them; an unused one is deleted at once with `now` (Alt-click on the panel's +/// button) and asked about otherwise. +pub(crate) fn ask(app: &mut VectorcraftApp, name: &str, now: bool) { + let Some(uid) = app.session.active().map(|st| st.uid) else { return }; + match instances(app, uid, name) { + None => {} + Some(0) if now => { + if let Err(e) = app.run("symbol.delete", json!({ "name": name })) { + app.status(e); + } + } + Some(n) => open(app, if n == 0 { KIND } else { USED }, name, uid), + } +} + +fn open(app: &mut VectorcraftApp, kind: &str, name: &str, uid: u64) { + app.ui.dialog = Some(Dialog::new(kind, json!({ "name": name, "doc": uid }))); +} + +/// How many instances symbol `name` has, while the document `uid` is the active one and has the +/// symbol; `None` otherwise. +fn instances(app: &mut VectorcraftApp, uid: u64, name: &str) -> Option<u64> { + if app.session.active().map(|st| st.uid) != Some(uid) { + return None; + } + let list = app.run("symbol.list", json!({})).ok()?; + list["symbols"].as_array()?.iter().find(|s| s["name"].as_str() == Some(name)).map(|s| s["instances"].as_u64().unwrap_or(0)) +} + +/// The document and symbol `d` asks about. +fn target(d: &Dialog) -> (u64, String) { + (d.fields.get("doc").and_then(Value::as_u64).unwrap_or(0), d.str("name")) +} + +/// Yes: deletes the symbol, or asks the in-use question when it has gained instances. +fn confirm_unused(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + app.ui.dialog = None; + let (uid, name) = target(d); + match instances(app, uid, &name) { + None => Ok(Value::Null), + Some(0) => app.run("symbol.delete", json!({ "name": name })), + Some(_) => { + open(app, USED, &name, uid); + Ok(Value::Null) + } + } +} + +/// Expand Instances (OK) turns the instances into ordinary art; Delete Instances (`discard`) +/// removes them. Either one deletes the symbol in one undo step. +fn confirm_used(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + app.ui.dialog = None; + let (uid, name) = target(d); + if instances(app, uid, &name).is_none() { + return Ok(Value::Null); + } + app.run("symbol.delete", json!({ "name": name, "expandInstances": !d.bool("discard") })) +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 5b65923a19..2048bbcc9c 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -735,6 +735,12 @@ font-technology Variable Променливи Delete Stop Изтриване на репер Delete Swatch Изтриване на образец Delete Symbol Изтриване на символ + Delete the selected symbol? Да се изтрие ли избраният символ? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Един или повече от символите се използват и не могат да бъдат изтрити, докато екземплярите им не бъдат разширени или изтрити. + Expand Instances Разширяване на екземплярите + Delete Instances Изтриване на екземплярите + Yes Да + No Не Delete Tab Изтриване на табулация Delete the graphic style “{name}”? Изтриване на графичния стил „{name}“? Delete Theme Изтриване на тема diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 5798a7a798..2ac957c9ac 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3046,6 +3046,12 @@ theme Appearance Izgled Current Symbol Trenutni simbol Delete Brush Izbriši četkicu Delete Symbol Izbriši simbol + Delete the selected symbol? Izbrisati odabrani simbol? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Jedan ili više simbola se koriste i ne mogu se izbrisati dok se njihove instance ne prošire ili izbrišu. + Expand Instances Proširi instance + Delete Instances Izbriši instance + Yes Da + No Ne Duplicate Brush Dupliciraj četkicu Duplicate Symbol Dupliciraj simbol Edit Symbol Uredi simbol diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index d93092418f..ea8d621822 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1052,6 +1052,12 @@ Delete Styles Suprimeix els estils Delete Swatch Suprimeix la mostra Delete Symbol Suprimeix el símbol + Delete the selected symbol? Voleu suprimir el símbol seleccionat? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Un o més dels símbols estan en ús i no es poden suprimir fins que se n’expandeixin o se’n suprimeixin les instàncies. + Expand Instances Expandeix les instàncies + Delete Instances Suprimeix les instàncies + Yes Sí + No No Delete Tab Suprimeix la tabulació Delete the graphic style “{name}”? Voleu suprimir l’estil gràfic “{name}”? Delete the library “{name}”? Voleu suprimir la biblioteca “{name}”? diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 50a8f953e1..93142cadb6 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3078,6 +3078,12 @@ theme Appearance Motiv Current Symbol Aktuální symbol Delete Brush Odstranit štětec Delete Symbol Odstranit symbol + Delete the selected symbol? Odstranit vybraný symbol? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Jeden nebo více symbolů se používá a nelze je odstranit, dokud jejich instance nerozložíte nebo neodstraníte. + Expand Instances Rozložit instance + Delete Instances Odstranit instance + Yes Ano + No Ne Duplicate Brush Duplikovat štětec Duplicate Symbol Duplikovat symbol Edit Symbol Upravit symbol diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 87249badf8..160abd6bf7 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2837,6 +2837,12 @@ theme Appearance Udseende Current Symbol Aktuelt symbol Delete Brush Slet pensel Delete Symbol Slet symbol + Delete the selected symbol? Vil du slette det markerede symbol? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Et eller flere af symbolerne er i brug og kan ikke slettes, før deres forekomster er udvidet eller slettet. + Expand Instances Udvid forekomster + Delete Instances Slet forekomster + Yes Ja + No Nej Duplicate Brush Duplikér pensel Duplicate Symbol Duplikér symbol Edit Symbol Redigér symbol diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 513ff8e4f4..08869d7652 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -729,6 +729,12 @@ font-technology Variable Variabel Delete Stop Farbstopp löschen Delete Swatch Farbfeld löschen Delete Symbol Symbol löschen + Delete the selected symbol? Ausgewähltes Symbol löschen? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Mindestens eines der Symbole wird verwendet und kann erst gelöscht werden, wenn seine Instanzen umgewandelt oder gelöscht wurden. + Expand Instances Instanzen umwandeln + Delete Instances Instanzen löschen + Yes Ja + No Nein Delete Tab Tabulator löschen Delete the graphic style “{name}”? Grafikstil „{name}“ löschen? Delete Theme Thema löschen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index ce282989f0..3d074c7167 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -709,6 +709,12 @@ font-technology Variable Μεταβλητές Delete Stop Διαγραφή στάσης ντεγκραντέ Delete Swatch Διαγραφή δείγματος χρώματος Delete Symbol Διαγραφή συμβόλου + Delete the selected symbol? Να διαγραφεί το επιλεγμένο σύμβολο; + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Ένα ή περισσότερα από τα σύμβολα χρησιμοποιούνται και δεν μπορούν να διαγραφούν μέχρι να επεκταθούν ή να διαγραφούν τα στιγμιότυπά τους. + Expand Instances Επέκταση στιγμιοτύπων + Delete Instances Διαγραφή στιγμιοτύπων + Yes Ναι + No Όχι Delete Tab Διαγραφή στηλοθέτη Delete the graphic style “{name}”? Να διαγραφεί το στυλ γραφικών «{name}»; Delete Theme Διαγραφή θέματος diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index fe945423e6..c3b905d18c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -750,6 +750,12 @@ font-technology Variable Variables Delete Stop Eliminar parada Delete Swatch Eliminar muestra Delete Symbol Eliminar símbolo + Delete the selected symbol? ¿Eliminar el símbolo seleccionado? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Uno o más de los símbolos están en uso y no se pueden eliminar hasta que se expandan o eliminen sus instancias. + Expand Instances Expandir instancias + Delete Instances Eliminar instancias + Yes Sí + No No Delete Tab Eliminar tabulación Delete the graphic style “{name}”? ¿Eliminar el estilo gráfico “{name}”? Delete Theme Eliminar tema diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 7ebd23d6bc..dd157932cf 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3018,6 +3018,12 @@ theme Appearance Ulkoasu Current Symbol Nykyinen symboli Delete Brush Poista sivellin Delete Symbol Poista symboli + Delete the selected symbol? Poistetaanko valittu symboli? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Yksi tai useampi symboleista on käytössä, eikä niitä voi poistaa ennen kuin niiden ilmentymät on laajennettu tai poistettu. + Expand Instances Laajenna ilmentymät + Delete Instances Poista ilmentymät + Yes Kyllä + No Ei Duplicate Brush Monista sivellin Duplicate Symbol Monista symboli Edit Symbol Muokkaa symbolia diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 859b2bfcd3..1ff18594a7 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -752,6 +752,12 @@ font-technology Variable Variables Delete Stop Supprimer l’étape de dégradé Delete Swatch Supprimer la nuance Delete Symbol Supprimer le symbole + Delete the selected symbol? Supprimer le symbole sélectionné ? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Un ou plusieurs symboles sont utilisés et ne peuvent pas être supprimés tant que leurs instances ne sont pas décomposées ou supprimées. + Expand Instances Décomposer les instances + Delete Instances Supprimer les instances + Yes Oui + No Non Delete Tab Supprimer la tabulation Delete the graphic style “{name}”? Supprimer le style graphique « {name} » ? Delete Theme Supprimer le thème diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 02e7303ed4..254eb37fcd 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -974,6 +974,12 @@ font-technology Variable Változó Delete Stop Színátmenet-pont törlése Delete Swatch Színminta törlése Delete Symbol Szimbólum törlése + Delete the selected symbol? Törli a kijelölt szimbólumot? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Egy vagy több szimbólum használatban van, és nem törölhető, amíg a példányait ki nem bontja vagy nem törli. + Expand Instances Példányok kibontása + Delete Instances Példányok törlése + Yes Igen + No Nem Delete Tab Tabulátor törlése Delete the graphic style “{name}”? Törlöd ezt a grafikai stílust: „{name}”? Delete the library “{name}”? Törlöd ezt a könyvtárat: „{name}”? diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c2d3695755..8e49c172b2 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2837,6 +2837,12 @@ theme Appearance Tampilan Current Symbol Simbol saat ini Delete Brush Hapus kuas Delete Symbol Hapus simbol + Delete the selected symbol? Hapus simbol yang dipilih? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Satu atau beberapa simbol sedang digunakan dan tidak dapat dihapus sampai instansinya diperluas atau dihapus. + Expand Instances Perluas instansi + Delete Instances Hapus instansi + Yes Ya + No Tidak Duplicate Brush Duplikatkan kuas Duplicate Symbol Duplikatkan simbol Edit Symbol Edit simbol diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8021409d21..39addf3619 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -750,6 +750,12 @@ font-technology Variable Variabili Delete Stop Elimina cursore colore Delete Swatch Elimina campione Delete Symbol Elimina simbolo + Delete the selected symbol? Eliminare il simbolo selezionato? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Uno o più simboli sono in uso e non possono essere eliminati finché le loro istanze non vengono espanse o eliminate. + Expand Instances Espandi istanze + Delete Instances Elimina istanze + Yes Sì + No No Delete Tab Elimina tabulazione Delete the graphic style “{name}”? Eliminare lo stile grafico “{name}”? Delete Theme Elimina tema diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 269651408f..d9106487d1 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1297,6 +1297,12 @@ font-technology Variable バリアブル Delete Stop 分岐点を削除 Delete Swatch スウォッチを削除 Delete Symbol シンボルを削除 + Delete the selected symbol? 選択したシンボルを削除しますか? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. 1 つ以上のシンボルが使用中のため、インスタンスを拡張または削除するまで削除できません。 + Expand Instances インスタンスを拡張 + Delete Instances インスタンスを削除 + Yes はい + No いいえ Delete Tab タブを削除 Delete Theme テーマを削除 Delete Transparency Flattener Preset 透明の分割・統合プリセットを削除 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index fd0eaae44a..9c4d6ff2fe 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2650,6 +2650,12 @@ theme Appearance იერსახე Current Symbol მიმდინარე სიმბოლო Delete Brush ფუნჯის წაშლა Delete Symbol სიმბოლოს წაშლა + Delete the selected symbol? წაიშალოს მონიშნული სიმბოლო? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. ერთი ან მეტი სიმბოლო გამოიყენება და მისი წაშლა შეუძლებელია, სანამ მისი ეგზემპლარები არ გაიშლება ან არ წაიშლება. + Expand Instances ეგზემპლარების გაშლა + Delete Instances ეგზემპლარების წაშლა + Yes დიახ + No არა Duplicate Brush ფუნჯის დუბლირება Duplicate Symbol სიმბოლოს დუბლირება Edit Symbol სიმბოლოს რედაქტირება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 00666a8401..f04039cdc7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1288,6 +1288,12 @@ font-technology Variable 가변 Delete Stop 정지점 삭제 Delete Swatch 견본 삭제 Delete Symbol 심볼 삭제 + Delete the selected symbol? 선택한 심볼을 삭제하시겠습니까? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. 하나 이상의 심볼이 사용 중이므로 인스턴스를 확장하거나 삭제하기 전에는 삭제할 수 없습니다. + Expand Instances 인스턴스 확장 + Delete Instances 인스턴스 삭제 + Yes 예 + No 아니요 Delete Tab 탭 삭제 Delete Theme 테마 삭제 Delete Transparency Flattener Preset 투명도 병합 프리셋 삭제 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f04ea4da45..01d80c460f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2851,6 +2851,13 @@ theme Appearance Vormgeving Current Symbol Huidig symbool Delete Brush Penseel verwijderen Delete Symbol Symbool verwijderen + Delete the selected symbol? Het geselecteerde symbool verwijderen? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Een of meer van de symbolen zijn in gebruik en kunnen pas worden verwijderd als hun exemplaren zijn uitgebreid of verwijderd. + Expand Instances Exemplaren uitbreiden + Delete Instances Exemplaren verwijderen + Yes Ja + No Nee + Duplicate Brush Kwast dupliceren Duplicate Brush Penseel dupliceren Duplicate Symbol Symbool dupliceren Edit Symbol Symbool bewerken diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 17810fe501..84ac64f406 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2958,6 +2958,12 @@ theme Appearance Wygląd Current Symbol Bieżący symbol Delete Brush Usuń pędzel Delete Symbol Usuń symbol + Delete the selected symbol? Usunąć zaznaczony symbol? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Co najmniej jeden z symboli jest używany i nie można go usunąć, dopóki jego wystąpienia nie zostaną rozszerzone lub usunięte. + Expand Instances Rozszerz wystąpienia + Delete Instances Usuń wystąpienia + Yes Tak + No Nie Duplicate Brush Powiel pędzel Duplicate Symbol Powiel symbol Edit Symbol Edytuj symbol diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e1fc3b3e6d..e48ef54bd6 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -663,6 +663,12 @@ Delete Stop Excluir Parada Delete Swatch Excluir Amostra Delete Symbol Excluir Símbolo + Delete the selected symbol? Excluir o símbolo selecionado? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Um ou mais símbolos estão em uso e não podem ser excluídos até que suas instâncias sejam expandidas ou excluídas. + Expand Instances Expandir Instâncias + Delete Instances Excluir Instâncias + Yes Sim + No Não Delete Tab Excluir Parada de Tabulação Delete Theme Excluir Tema Delete Transparency Flattener Preset Excluir Predefinido de Achatamento de Transparência diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 412d4d129b..c1567d10ca 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -748,6 +748,12 @@ font-technology Variable Вариативные Delete Stop Удалить точку перехода Delete Swatch Удалить образец Delete Symbol Удалить символ + Delete the selected symbol? Удалить выбранный символ? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Один или несколько символов используются, и их нельзя удалить, пока их экземпляры не будут разобраны или удалены. + Expand Instances Разобрать экземпляры + Delete Instances Удалить экземпляры + Yes Да + No Нет Delete Tab Удалить табуляцию Delete the graphic style “{name}”? Удалить графический стиль «{name}»? Delete Theme Удалить тему diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 08b0b8105c..c75c0f6ce8 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -737,6 +737,12 @@ font-technology Variable Variabla Delete Stop Radera stopp Delete Swatch Radera färgruta Delete Symbol Radera symbol + Delete the selected symbol? Vill du radera den markerade symbolen? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. En eller flera av symbolerna används och kan inte raderas förrän deras instanser har expanderats eller raderats. + Expand Instances Expandera instanser + Delete Instances Radera instanser + Yes Ja + No Nej Delete Tab Radera tabb Delete the graphic style “{name}”? Radera grafikstilen ”{name}”? Delete Theme Radera tema diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index fff0356575..21c15371a9 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -729,6 +729,12 @@ font-technology Variable Değişken Delete Stop Durdurmayı Sil Delete Swatch Renk Örneğini Sil Delete Symbol Sembolü Sil + Delete the selected symbol? Seçili sembol silinsin mi? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Sembollerden biri veya birkaçı kullanımda ve örnekleri genişletilene ya da silinene kadar silinemez. + Expand Instances Örnekleri Genişlet + Delete Instances Örnekleri Sil + Yes Evet + No Hayır Delete Tab Sekmeyi Sil Delete the graphic style “{name}”? “{name}” grafik stili silinsin mi? Delete Theme Temayı Sil diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 1c6f93e5d0..3117511dc8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -744,6 +744,12 @@ font-technology Variable Варіативні Delete Stop Видалити точку переходу Delete Swatch Видалити зразок Delete Symbol Видалити символ + Delete the selected symbol? Видалити вибраний символ? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Один або кілька символів використовуються, і їх не можна видалити, доки їхні екземпляри не буде розібрано або видалено. + Expand Instances Розібрати екземпляри + Delete Instances Видалити екземпляри + Yes Так + No Ні Delete Tab Видалити табуляцію Delete the graphic style “{name}”? Видалити графічний стиль «{name}»? Delete Theme Видалити тему diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 99d8437f89..b6d5604b37 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -870,6 +870,12 @@ font-technology Variable Biến thiên Delete Stop Xóa điểm dừng Delete Swatch Xóa mẫu màu Delete Symbol Xóa ký hiệu + Delete the selected symbol? Xóa ký hiệu đã chọn? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Một hoặc nhiều ký hiệu đang được sử dụng và không thể xóa cho đến khi các thực thể của chúng được mở rộng hoặc xóa. + Expand Instances Mở rộng thực thể + Delete Instances Xóa thực thể + Yes Có + No Không Delete Tab Xóa tab Delete the graphic style “{name}”? Xóa kiểu đồ họa “{name}”? Delete the library “{name}”? Xóa thư viện “{name}”? diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 6ecaf09308..7c50ba5773 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -693,6 +693,12 @@ Delete Stop 删除色标 Delete Swatch 删除色板 Delete Symbol 删除符号 + Delete the selected symbol? 要删除所选符号吗? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. 一个或多个符号正在使用中,在扩展或删除其实例之前无法删除。 + Expand Instances 扩展实例 + Delete Instances 删除实例 + Yes 是 + No 否 Delete Tab 删除制表位 Delete the graphic style “{name}”? 要删除图形样式“{name}”吗? Delete Theme 删除主题 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 75ee3a4134..2d61281dd2 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -712,6 +712,12 @@ font-technology Variable 可變 Delete Stop 刪除色標 Delete Swatch 刪除色票 Delete Symbol 刪除符號 + Delete the selected symbol? 要刪除選取的符號嗎? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. 一個或多個符號正在使用中,在展開或刪除其範例之前無法刪除。 + Expand Instances 展開範例 + Delete Instances 刪除範例 + Yes 是 + No 否 Delete Tab 刪除定位點 Delete the graphic style “{name}”? 要刪除繪圖樣式「{name}」嗎? Delete Theme 刪除主題 diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index e99a24bf66..bc77f8e4c1 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -273,10 +273,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let cmd = if ui.input(|i| i.modifiers.alt) { "symbol.new" } else { "ui.symbolOptions" }; app.run(cmd, json!({})).ok(); } + // Alt deletes an unused symbol without asking; a symbol with instances still asks. if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Symbol"), false, sel.is_some(), 24.0).clicked() && let Some(n) = &sel { - app.run("symbol.delete", json!({"name": n})).ok(); + crate::dialogs::symbol_delete::ask(app, n, super::alt_held(ui)); } }); } @@ -286,11 +287,23 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let has_sel = app.session.active().is_some_and(|d| !d.selection.is_empty()); let inst = has_instances_selected(app); let name = json!({"name": sel}); - let items: [(&str, bool, &str, Value); 10] = [ + let items: [(&str, bool, &str, Value); 3] = [ (tl!("New Symbol…"), has_sel, "ui.symbolOptions", json!({})), (tl!("Redefine Symbol"), has_sel && sel.is_some(), "symbol.update", name.clone()), (tl!("Duplicate Symbol"), sel.is_some(), "symbol.duplicate", name.clone()), - (tl!("Delete Symbol"), sel.is_some(), "symbol.delete", name.clone()), + ]; + for (label, enabled, cmd, params) in items { + if menu_item(ui, label, enabled, false) { + app.run(cmd, params).ok(); + } + } + // Asks first, as the panel's button does; the menu item has no Alt shortcut. + if menu_item(ui, tl!("Delete Symbol"), sel.is_some(), false) + && let Some(n) = &sel + { + crate::dialogs::symbol_delete::ask(app, n, false); + } + let items: [(&str, bool, &str, Value); 6] = [ (tl!("Symbol Options…"), sel.is_some(), "ui.symbolOptions", json!({"edit": true, "name": sel})), (tl!("Edit Symbol"), inst, "symbol.edit", json!({})), (tl!("Place Symbol Instance"), sel.is_some(), "symbol.place", name.clone()), @@ -738,6 +751,195 @@ mod tests { assert!(orange(3, 3) && orange(36, 36), "{:?} {:?}", thumb.pixels[3 * 40 + 3], thumb.pixels[36 * 40 + 36]); } + /// A document with symbol "Leaf", whose instance stands where its rectangle was, and symbol + /// "Dot", which no instance uses; "Dot" is current. + fn leaf_and_dot() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + for (name, x) in [("Leaf", 10), ("Dot", 150)] { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 30})).unwrap(); + app.run("symbol.new", json!({"name": name})).unwrap(); + } + // Dot's instance goes: no art uses Dot. + app.run("edit.clear", json!({})).unwrap(); + app.run("symbol.setCurrent", json!({"name": "Dot"})).unwrap(); + app + } + + /// The instances of symbol `name` in the active document, and the ordinary paths in it. + fn art(app: &VectorcraftApp, name: &str) -> (usize, usize) { + let (mut instances, mut paths) = (0, 0); + for l in &app.session.active().unwrap().doc.layers { + l.walk(&mut |n| match &n.kind { + NodeKind::SymbolInstance { symbol, .. } if symbol == name => instances += 1, + NodeKind::Path { .. } => paths += 1, + _ => {} + }); + } + (instances, paths) + } + + fn dialog_kind(app: &VectorcraftApp) -> Option<&str> { + app.ui.dialog.as_ref().map(|d| d.kind.as_str()) + } + + /// One frame of the panel with `modifiers` held, its output kept. + fn frame_held(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>, modifiers: egui::Modifiers) -> egui::FullOutput { + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(236.0, 400.0))); + let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect(); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out + } + + /// The labels of the clickable accessibility nodes of `out`, with their centers. + fn clickable(out: &egui::FullOutput) -> Vec<(String, Pos2)> { + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + nodes + .iter() + .filter(|(_, n)| n.supports_action(egui::accesskit::Action::Click)) + .filter_map(|(_, n)| { + let b = n.bounds()?; + Some((n.label()?.trim().to_string(), pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32))) + }) + .collect() + } + + /// Clicks the panel's Delete Symbol button with `modifiers` held. + fn click_delete(app: &mut VectorcraftApp, modifiers: egui::Modifiers) { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let out = frame_held(&ctx, app, vec![], modifiers); + let at = clickable(&out).into_iter().find(|(l, _)| l == "Delete Symbol").expect("a Delete Symbol button").1; + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; + frame_held(&ctx, app, vec![egui::Event::PointerMoved(at), press(true), press(false)], modifiers); + } + + /// Clicks the panel menu's Delete Symbol item. + fn menu_delete(app: &mut VectorcraftApp) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let labels = menu_frame(&ctx, app, vec![]); + let item = labels.iter().find(|(t, _)| t.trim() == "Delete Symbol").map(|(_, r)| r.center()).expect("Delete Symbol in the menu"); + menu_frame(&ctx, app, vec![egui::Event::PointerMoved(item), button(item, true)]); + menu_frame(&ctx, app, vec![button(item, false)]); + } + + /// Delete Symbol, from the panel's button or its menu, asks "Delete the selected symbol?" for a + /// symbol no instance uses, and the in-use question for one with instances, before changing + /// the document; No leaves it as it was and Yes deletes the symbol. Alt-click on the button + /// deletes an unused symbol without asking, and still asks for one with instances. + #[test] + fn delete_symbol_asks_first_and_alt_click_deletes_an_unused_symbol_at_once() { + let mut app = leaf_and_dot(); + let before = app.session.active().unwrap().doc.clone(); + let unchanged = |app: &VectorcraftApp| Arc::ptr_eq(&before, &app.session.active().unwrap().doc); + click_delete(&mut app, egui::Modifiers::NONE); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::KIND)); + assert!(unchanged(&app), "nothing changes while it asks"); + crate::dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert!(unchanged(&app), "No changes nothing"); + menu_delete(&mut app); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::KIND), "the menu item asks too"); + assert!(unchanged(&app)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(symbols(&mut app), ["Leaf"], "Yes deletes it"); + // Alt-click on the button: an unused symbol goes without a question. + app.run("edit.undo", json!({})).unwrap(); + app.run("symbol.setCurrent", json!({"name": "Dot"})).unwrap(); + click_delete(&mut app, egui::Modifiers::ALT); + assert!(app.ui.dialog.is_none()); + assert_eq!(symbols(&mut app), ["Leaf"]); + // A symbol with an instance asks, with Alt held too, from the button and from the menu. + app.run("symbol.setCurrent", json!({"name": "Leaf"})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + for alt in [egui::Modifiers::NONE, egui::Modifiers::ALT] { + click_delete(&mut app, alt); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::USED), "{alt:?}"); + crate::dialogs::cancel(&mut app); + } + menu_delete(&mut app); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::USED)); + crate::dialogs::cancel(&mut app); + assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc), "Cancel changes nothing"); + assert_eq!(art(&app, "Leaf"), (1, 0)); + } + + /// The in-use question: Expand Instances deletes the symbol and turns its instance into + /// ordinary art, Delete Instances deletes the symbol and its instance, each in one undo step. + #[test] + fn the_in_use_question_expands_or_deletes_the_instances() { + for (discard, left) in [(false, (0, 1)), (true, (0, 0))] { + let mut app = leaf_and_dot(); + crate::dialogs::symbol_delete::ask(&mut app, "Leaf", false); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::USED)); + if discard { + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + } + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(symbols(&mut app), ["Dot"], "discard {discard}"); + assert_eq!(art(&app, "Leaf"), left, "discard {discard}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!((symbols(&mut app), art(&app, "Leaf")), (vec!["Leaf".to_string(), "Dot".to_string()], (1, 0)), "one undo step"); + } + } + + /// A question asked in one document deletes nothing once another is active, and Yes for a + /// symbol that has gained an instance since asks the in-use question instead. + #[test] + fn a_stale_delete_symbol_question_deletes_nothing() { + let mut app = leaf_and_dot(); + crate::dialogs::symbol_delete::ask(&mut app, "Dot", false); + let asked = app.ui.dialog.clone(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + app.run("symbol.new", json!({"name": "Dot"})).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + app.ui.dialog = asked; + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(symbols(&mut app), ["Dot"], "the other document keeps its symbol"); + // Back in the first document: Dot gains an instance while the question is open. + app.run("document.activate", json!({"index": 0})).unwrap(); + crate::dialogs::symbol_delete::ask(&mut app, "Dot", false); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::KIND)); + app.run("symbol.place", json!({"name": "Dot"})).unwrap(); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::USED)); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"]); + assert_eq!(art(&app, "Dot"), (1, 0)); + } + + /// The questions' buttons: Yes and No for an unused symbol; Expand Instances, Delete Instances + /// and Cancel for one with instances. + #[test] + fn the_delete_symbol_questions_show_their_buttons() { + let mut app = leaf_and_dot(); + for (name, want) in [("Dot", &["Yes", "No"][..]), ("Leaf", &["Expand Instances", "Delete Instances", "Cancel"][..])] { + crate::dialogs::symbol_delete::ask(&mut app, name, false); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + // The window measures itself in its first frame and draws its buttons in the next. + let mut out = None; + for _ in 0..2 { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + let mut o = ctx.run_ui(raw, |ui| crate::dialogs::show(&mut app, ui.ctx())); + o.textures_delta.clear(); + out = Some(o); + } + let out = out.expect("a frame"); + let labels: Vec<String> = clickable(&out).into_iter().map(|(l, _)| l).collect(); + for w in want { + assert!(labels.iter().any(|l| l == w), "{name}: {w} in {labels:?}"); + } + assert!(!labels.iter().any(|l| l == "OK"), "{name}: {labels:?}"); + crate::dialogs::cancel(&mut app); + } + } + /// #4121: with symbol instances selected, the Control bar's Replace menu lists the document's /// symbols and shows the instance's own; picking another replaces it. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 97e9abf9f0..6d97e0097d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -597,6 +597,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - macOS: Finder opens every format File › Open reads with VectorCraft (double-click, Open With, a drop on the Dock icon, `open -a`), at launch or while it runs; the release and `cargo xtask bundle` apps share one `Info.plist` that declares those document types, owning only VectorCraft's own formats. The DMG opens on a designed Finder window, VectorCraft.app beside the `Applications` link over a background with the app icon (#493). - Swatch and graphic style libraries, Libraries panel files, presets and plug-ins open wherever they are dropped on the window, as File › Open opens them. - **Symbol libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own, as swatch and graphic style libraries do. The built-in library, Basic Shapes, is original art generated in code (`crates/engine/src/cmd/symbollib.rs`). A click on a symbol adds it to the document's Symbols as one undo step, with its Symbol Options (size, registration, export type, 9-slice guides) and every resource it uses (the symbols it nests, patterns, swatches, brushes, graphic styles, images), and makes it the current symbol; a symbol the document already has is not added again and another symbol of the same name keeps its name, the library's comes in numbered. Thumbnails, in the library panels and the Symbols panel, draw a symbol with the symbols it nests and the patterns and images it uses. Dragging a library symbol onto the canvas also places an instance there, in the same step ([placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)). Save Symbols (the library menu) and Save Symbol Library… (the Symbols panel menu) write the document's symbols as a `.vectorcraft` document holding only them, into the user library folder (listed under User Defined) or a file; Other Library… reads the symbols of any document VectorCraft opens; a file it can't read is an error and opens no panel. Tests: `crates/engine/src/tests/symbollib.rs`, `crates/ui-egui/src/panels/tests_symbol_libraries.rs`, `panels::symbols::tests::thumbnails_show_the_symbols_a_symbol_nests`, `canvas::tests::a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step`. + - **Delete Symbol asks first** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Alt-click Delete](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): the Symbols panel's Delete Symbol button and menu item ask "Delete the selected symbol?" with Yes and No for a symbol no instance uses. For a symbol with placed instances they ask with Expand Instances (the instances become ordinary art), Delete Instances and Cancel; either Instances button deletes the symbol in one undo step. Alt-click on the button deletes an unused symbol without asking and still asks about one with instances. A question left open while another document became active deletes nothing. `symbol.delete` itself does not ask. Tests: `panels::symbols::tests::delete_symbol_asks_first_and_alt_click_deletes_an_unused_symbol_at_once`, `the_in_use_question_expands_or_deletes_the_instances`, `a_stale_delete_symbol_question_deletes_nothing`, `the_delete_symbol_questions_show_their_buttons`. - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol. A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection), or the view commands on empty canvas. - A right-click over locked objects adds an Unlock submenu to the canvas context menu. The submenu lists up to 20 locked objects under the pointer, topmost first, by the name the Layers panel shows, and choosing one unlocks it (`layer.setProps`). A locked group is listed as one item. Objects on hidden, locked or template layers are not listed. From f4161a3ab75f08bb154005345665565337e0c36b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 01:25:05 -0700 Subject: [PATCH 119/260] Symbols: the French delete question keeps the no-break space before ? --- crates/ui-egui/src/i18n/fr.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 1ff18594a7..5747e2663d 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -752,7 +752,7 @@ font-technology Variable Variables Delete Stop Supprimer l’étape de dégradé Delete Swatch Supprimer la nuance Delete Symbol Supprimer le symbole - Delete the selected symbol? Supprimer le symbole sélectionné ? + Delete the selected symbol? Supprimer le symbole sélectionné ? One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Un ou plusieurs symboles sont utilisés et ne peuvent pas être supprimés tant que leurs instances ne sont pas décomposées ou supprimées. Expand Instances Décomposer les instances Delete Instances Supprimer les instances From 62555c224626535d6deb402744f266fa045e11f4 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 00:56:17 -0700 Subject: [PATCH 120/260] Contextual Task Bar: a basic shape shows its properties in place of Lock A live rectangle, rounded rectangle, ellipse or polygon selected with the Selection tool shows a Shape Properties button where Lock was. It opens a popup with the shape's rows from the Transform panel, which stays open while the fields are edited. Every other selection, and the Direct and Group Selection tools, keep Lock; Object > Lock and Cmd+2 still lock a shape. The Transform panel, the Properties panel and the popup draw the rows through one live_shape_rows function. --- crates/ui-egui/src/canvas/task_bar.rs | 34 +++++- crates/ui-egui/src/canvas/tests.rs | 15 ++- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/panels/properties.rs | 12 +- crates/ui-egui/src/panels/transform.rs | 47 +++++--- crates/ui-egui/src/tests/taskbar.rs | 146 +++++++++++++++++++++++- docs/target-app-parity.md | 1 + 32 files changed, 243 insertions(+), 38 deletions(-) diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 61c9719878..cf40955ee6 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -33,6 +33,7 @@ fn picked_artboards_bounds(app: &VectorcraftApp) -> Option<Rect> { /// The Contextual Task Bar: a floating pill under the selection with the most likely next actions. /// With the Artboard tool it sits under the selected artboards and offers Resize (Artboard /// Options), Duplicate, Rearrange All (with two or more artboards) and Export (Export for Screens). +/// A basic shape selected with the Selection tool shows a Shape Properties button in place of Lock. /// Its handle drags it anywhere on the canvas; unpinned it keeps that offset as it follows the /// selection, pinned it stays put ([`crate::state::TaskBarPlace`]). pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { @@ -67,6 +68,17 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { && first.as_ref().is_some_and(|f| { f.name.as_deref() == Some("Image Trace") && f.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_)))) }); + // A basic shape (a live rectangle, rounded rectangle, ellipse or polygon) selected whole with the + // Selection tool: its properties take the place of Lock, as in the reference app + // (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html>). + use vectorcraft_doc::LiveShape; + let shape = first.clone().filter(|f| { + n == 1 + && st.selection.anchors.is_empty() + && app.session.tool_id() == "selection" + && matches!(&f.kind, NodeKind::Path { live: Some(l), .. } + if matches!(**l, LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. })) + }); let mut items: Vec<(&str, &str, &str, serde_json::Value)> = vec![]; // (label, icon, command, params) let none = || json!({}); if on_artboards { @@ -228,7 +240,8 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { run = Some((*cmd, params.clone())); } } - // The selected objects' Fill, Stroke, Recolor Artwork and Lock, left out with the Artboard tool. + // The selected objects' Fill, Stroke, Recolor Artwork and Lock (a basic shape's + // properties instead), left out with the Artboard tool. if !on_artboards { let (r, resp) = ui.allocate_exact_size(vec2(26.0, 30.0), Sense::click()); let chip = egui::Rect::from_center_size(r.center(), vec2(16.0, 16.0)); @@ -251,10 +264,21 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { if colored && widgets::icon_button(ui, "palette", tl!("Recolor Artwork"), false, 30.0).clicked() { run = Some(("ui.recolorDialog", json!({}))); } - // The Lock button is off in isolation mode, as Object › Lock › Selection is. - let lockable = crate::menus::enabled(app, "object.lock"); - if widgets::icon_button_enabled(ui, "lock", tl!("Lock (⌘2)"), false, lockable, 30.0).clicked() { - run = Some(("object.lock", json!({}))); + if let Some(shape) = &shape + && let NodeKind::Path { live: Some(live), .. } = &shape.kind + { + // The shape's properties in a popup that stays open while its fields are edited. + let props = widgets::icon_button(ui, "shapes", tl!("Shape Properties"), false, 30.0); + egui::Popup::menu(&props).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + ui.set_min_width(250.0); + crate::panels::transform::live_shape_rows(app, ui, shape, live, "task-bar-shape", true); + }); + } else { + // The Lock button is off in isolation mode, as Object › Lock › Selection is. + let lockable = crate::menus::enabled(app, "object.lock"); + if widgets::icon_button_enabled(ui, "lock", tl!("Lock (⌘2)"), false, lockable, 30.0).clicked() { + run = Some(("object.lock", json!({}))); + } } } let more = widgets::icon_button(ui, "ellipsis", tl!("More Options"), false, 30.0); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index ed67da7129..17b05d72ee 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6839,7 +6839,8 @@ fn the_task_bar_shows_a_stroke_chip_beside_fill() { let mut out = ctx.run_ui(raw, |ui| show(&mut app, ui)); out.textures_delta.clear(); let bar = task_bar_rect(&ctx).expect("the task bar shows"); - // Right to left: the frame's margin, More Options, Lock, Recolor, then Stroke and Fill. + // Right to left: the frame's margin, More Options, Shape Properties (Lock's place), Recolor, + // then Stroke and Fill. let stroke_x = bar.right() - 8.0 - 3.0 * (30.0 + 6.0) - 13.0; let fill_x = stroke_x - 26.0 - 6.0; let blue = Color32::from_rgb(0x22, 0x44, 0xcc); @@ -6896,7 +6897,8 @@ fn the_task_bar_chips_follow_the_proxies_and_show_swatches_anywhere() { out.textures_delta.clear(); out.shapes }; - // Right to left: the frame's margin, More Options, Lock, Recolor, then Stroke and Fill. + // Right to left: the frame's margin, More Options, Shape Properties (Lock's place), Recolor, + // then Stroke and Fill. let stroke_x = |bar: egui::Rect| bar.right() - 8.0 - 3.0 * (30.0 + 6.0) - 13.0; let chip_with = |shapes: &[egui::epaint::ClippedShape], bar: egui::Rect, x: f32, color: Color32| { shapes.iter().any(|c| match &c.shape { @@ -6948,7 +6950,7 @@ fn the_task_bar_recolors_coloured_art() { frame(app, &ctx, vec![]); frame(app, &ctx, vec![]); let bar = task_bar_rect(&ctx).expect("the task bar shows"); - // Right to left: the frame's margin, More Options, Lock, then Recolor. + // Right to left: the frame's margin, More Options, Shape Properties (Lock's place), then Recolor. let at = pos2(bar.right() - 8.0 - 30.0 - 6.0 - 30.0 - 6.0 - 15.0, bar.center().y); let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; frame(app, &ctx, vec![egui::Event::PointerMoved(at)]); @@ -6975,8 +6977,11 @@ fn the_task_bar_recolors_coloured_art() { fn the_task_bar_lock_button_is_off_in_isolation_mode() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); - let a = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 130, "width": 40, "height": 40})).unwrap()["id"].clone(); - let b = app.session.execute("shape.rectangle", &json!({"x": 210, "y": 130, "width": 40, "height": 40})).unwrap()["id"].clone(); + // Plain paths: a basic shape shows its properties in Lock's place. + let square = + |x: f64| json!({"anchors": [{"x": x, "y": 130}, {"x": x + 40.0, "y": 130}, {"x": x + 40.0, "y": 170}, {"x": x, "y": 170}], "closed": true}); + let a = app.session.execute("path.create", &square(150.0)).unwrap()["id"].clone(); + let b = app.session.execute("path.create", &square(210.0)).unwrap()["id"].clone(); app.session.execute("select.set", &json!({"ids": [a.clone(), b]})).unwrap(); let g = app.session.execute("object.group", &json!({})).unwrap()["id"].clone(); app.select_tool("selection"); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2048bbcc9c..dabb1c8e9a 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2922,6 +2922,7 @@ font-technology Variable Променливи Shape Mode Режим на фигура Shape Modes: Режими на фигури: Shape Properties: Свойства на фигурата: + Shape Properties Свойства на фигурата Shaper Tool Инструмент „Shaper“ Shapes Фигури Shear Срязване diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 2ac957c9ac..da8c5d134e 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2014,6 +2014,7 @@ lighting Light Svjetlo Polygon Properties: Svojstva mnogougla: Rectangle Properties: Svojstva pravougaonika: Shape Properties: Svojstva oblika: + Shape Properties Svojstva oblika Sides: Stranice: Transform options Opcije transformacije Transform Both Transformiši oboje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index ea8d621822..59984a5192 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3753,6 +3753,7 @@ Shape Mode Mode de forma Shape Modes: Modes de forma: Shape Properties: Propietats de la forma: + Shape Properties Propietats de la forma Shape: Forma: Shaper Shaper Shaper Tool Eina Shaper diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 93142cadb6..11d38443b6 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2041,6 +2041,7 @@ lighting Light Světlo Polygon Properties: Vlastnosti mnohoúhelníku: Rectangle Properties: Vlastnosti obdélníku: Shape Properties: Vlastnosti tvaru: + Shape Properties Vlastnosti tvaru Sides: Strany: Transform options Možnosti transformace Transform Both Transformovat obojí diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 160abd6bf7..1203b3d366 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1852,6 +1852,7 @@ lighting Light Lys Polygon Properties: Polygonegenskaber: Rectangle Properties: Rektangelegenskaber: Shape Properties: Figuregenskaber: + Shape Properties Figuregenskaber Sides: Sider: Transform options Transformeringsindstillinger Transform Both Transformer begge diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 08869d7652..e832311b06 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2957,6 +2957,7 @@ mark-style Japanese Japanisch Shape Mode Formmodus Shape Modes: Formmodi: Shape Properties: Formeigenschaften: + Shape Properties Formeigenschaften Shaper Tool Shaper-Werkzeug Shapes Formen Shear Verbiegen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 3d074c7167..90709397af 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3428,6 +3428,7 @@ theme Appearance Εμφάνιση Shape Mode Λειτουργία σχήματος Shape Modes: Λειτουργίες σχημάτων: Shape Properties: Ιδιότητες σχήματος: + Shape Properties Ιδιότητες σχήματος Shaper Tool Διαμορφωτής σχημάτων (Shaper Tool) Shear Tool Διάτμηση (Shear Tool) Shift to Color… Μετατόπιση προς χρώμα… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c3b905d18c..f90a4b0471 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2992,6 +2992,7 @@ font-technology Variable Variables Shape Mode Modo de forma Shape Modes: Modos de forma: Shape Properties: Propiedades de forma: + Shape Properties Propiedades de forma Shaper Tool Herramienta Shaper Shapes Formas Shear Inclinar diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index dd157932cf..8c4bc1fc10 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2003,6 +2003,7 @@ lighting Light Valo Polygon Properties: Monikulmion ominaisuudet: Rectangle Properties: Suorakulmion ominaisuudet: Shape Properties: Muodon ominaisuudet: + Shape Properties Muodon ominaisuudet Sides: Sivut: Transform options Muunnosasetukset Transform Both Muunna molemmat diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 5747e2663d..7db8ee535a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2989,6 +2989,7 @@ font-technology Variable Variables Shape Effects Effets de forme Shape Mode Mode de forme Shape Modes: Modes de forme : + Shape Properties Propriétés de la forme Shape Properties: Propriétés de la forme : Shaper Tool Outil Shaper Shapes Formes diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 254eb37fcd..0aceab5ab4 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3602,6 +3602,7 @@ mark-style Japanese Japán Shape Mode Alakzatmód Shape Modes: Alakzatmódok: Shape Properties: Alakzat tulajdonságai: + Shape Properties Alakzat tulajdonságai Shape: Alak: Shaper Alakformáló Shaper Tool Alakformáló diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 8e49c172b2..95a3036337 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1852,6 +1852,7 @@ lighting Light Cahaya Polygon Properties: Properti poligon: Rectangle Properties: Properti persegi panjang: Shape Properties: Properti bentuk: + Shape Properties Properti bentuk Sides: Sisi: Transform options Opsi transformasi Transform Both Transformasikan keduanya diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 39addf3619..a9c16d3ba9 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3026,6 +3026,7 @@ mark-style Japanese Giapponese Shape Mode Metodo forma Shape Modes: Metodi forma: Shape Properties: Proprietà forma: + Shape Properties Proprietà forma Shaper Tool Strumento Sagomatore Shapes Forme Shear Inclina diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d9106487d1..01c25917b9 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2868,6 +2868,7 @@ mark-style Japanese 日本式 Shape Mode シェイプモード Shape Modes: シェイプモード: Shape Properties: シェイプのプロパティ: + Shape Properties シェイプのプロパティ Shaper Tool Shaper ツール Shapes シェイプ Shear シアー diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9c4d6ff2fe..e0e1a10953 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1754,6 +1754,7 @@ lighting Light სინათლე Polygon Properties: მრავალკუთხედის თვისებები: Rectangle Properties: მართკუთხედის თვისებები: Shape Properties: ფიგურის თვისებები: + Shape Properties ფიგურის თვისებები Sides: გვერდები: Transform options გარდაქმნის პარამეტრები Transform Both ორივეს გარდაქმნა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index f04039cdc7..45ce73252c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2858,6 +2858,7 @@ mark-style Japanese 일본식 Shape Mode 모양 모드 Shape Modes: 모양 모드: Shape Properties: 모양 속성: + Shape Properties 모양 속성 Shaper Tool 셰이퍼 도구 Shapes 모양 Shear 기울이기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 7fb221d3ed..e4cca253f8 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1866,6 +1866,7 @@ lighting Light Licht Polygon Properties: Veelhoekeigenschappen: Rectangle Properties: Rechthoekeigenschappen: Shape Properties: Vormeigenschappen: + Shape Properties Vormeigenschappen Sides: Zijden: Transform options Transformatieopties Transform Both Beide transformeren diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 84ac64f406..027f7198e2 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1962,6 +1962,7 @@ lighting Light Światło Polygon Properties: Właściwości wielokąta: Rectangle Properties: Właściwości prostokąta: Shape Properties: Właściwości kształtu: + Shape Properties Właściwości kształtu Sides: Boki: Transform options Opcje przekształcania Transform Both Przekształć oba diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e48ef54bd6..e9ee07994f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2483,6 +2483,7 @@ Shape Mode Modo de Forma Shape Modes: Modos de Forma: Shape Properties: Propriedades da Forma: + Shape Properties Propriedades da Forma Shaper Tool Ferramenta Formador Shapes Formas Shear Cisalhar diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index c1567d10ca..dea1bee849 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3022,6 +3022,7 @@ mark-style Japanese Японский Shape Mode Режим фигуры Shape Modes: Режимы фигур: Shape Properties: Свойства фигуры: + Shape Properties Свойства фигуры Shaper Tool Инструмент «Формообразование» Shapes Фигуры Shear Наклонить diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c75c0f6ce8..fcd0427a77 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2922,6 +2922,7 @@ font-technology Variable Variabla Shape Mode Formläge Shape Modes: Formlägen: Shape Properties: Formegenskaper: + Shape Properties Formegenskaper Shaper Tool Formningsverktyg Shapes Former Shear Skjuva diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 21c15371a9..7a1ea36471 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2833,6 +2833,7 @@ shape Open Açık Shape Mode Şekil Modu Shape Modes: Şekil Modları: Shape Properties: Şekil Özellikleri: + Shape Properties Şekil Özellikleri Shaper Tool Şekillendirici Aracı Shapes Şekiller Shear Kesme diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 3117511dc8..58693ddfd1 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3018,6 +3018,7 @@ mark-style Japanese Японський Shape Mode Режим фігури Shape Modes: Режими фігур: Shape Properties: Властивості фігури: + Shape Properties Властивості фігури Shaper Tool Інструмент «Формоутворення» Shapes Фігури Shear Нахилити diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index b6d5604b37..aaa74d0e7c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3346,6 +3346,7 @@ mark-style Japanese Kiểu Nhật Shape Mode Chế độ hình dạng Shape Modes: Chế độ hình dạng: Shape Properties: Thuộc tính hình dạng: + Shape Properties Thuộc tính hình dạng Shape: Hình dạng: Shaper Tạo hình Shaper Tool Công cụ Tạo hình diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 7c50ba5773..71b1fead14 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2859,6 +2859,7 @@ font-script Japanese 汉字 Shape Mode 形状模式 Shape Modes: 形状模式: Shape Properties: 形状属性: + Shape Properties 形状属性 Shaper Tool Shaper 工具 Shapes 形状 Shear 倾斜 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 2d61281dd2..a89fd28cce 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3833,6 +3833,7 @@ font-script Japanese 漢字 Shape Mode 形狀模式 Shape Modes: 形狀模式: Shape Properties: 形狀內容: + Shape Properties 形狀內容 Shaper Tool Shaper 工具 Shapes 形狀 Shear 傾斜 diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index a10f5c1334..c0ab7f5e9a 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -6,7 +6,7 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{LiveCorners, LiveShape, NodeKind, Unit, WidthProfile}; use vectorcraft_engine::cmd::newdoc; -use super::{corner_radius_row, first_selected, pstate, set_pstate}; +use super::{first_selected, pstate, set_pstate}; use crate::theme::Tokens; use crate::widgets::{self, dim_label, divider, section_header}; use crate::{VectorcraftApp, icons}; @@ -798,15 +798,7 @@ pub fn transform_section(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(n) = first_selected(app) && let NodeKind::Path { live: Some(live), .. } = &n.kind { - match &**live { - vectorcraft_doc::LiveShape::Rectangle { .. } => corner_radius_row(app, ui, &n, "radius"), - vectorcraft_doc::LiveShape::Polygon { .. } => super::transform::polygon_rows(app, ui, &n, live, "props-polygon"), - vectorcraft_doc::LiveShape::Ellipse { pie, .. } => { - widgets::subheader(ui, tl!("Ellipse Properties:")); - super::transform::pie_rows(app, ui, *pie, "props-pie"); - } - _ => {} - } + super::transform::live_shape_rows(app, ui, &n, live, "props", false); } } diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index 95f1488408..df8683a012 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -345,23 +345,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { && !matches!(**live, vectorcraft_doc::LiveShape::Path { .. }) { widgets::divider(ui); - match &**live { - vectorcraft_doc::LiveShape::Rectangle { .. } => { - widgets::subheader(ui, tl!("Rectangle Properties:")); - corner_radius_row(app, ui, &n, "xfp-radius"); - } - vectorcraft_doc::LiveShape::Polygon { .. } => { - widgets::subheader(ui, tl!("Polygon Properties:")); - polygon_rows(app, ui, &n, live, "xfp-polygon"); - } - vectorcraft_doc::LiveShape::Ellipse { pie, .. } => { - widgets::subheader(ui, tl!("Ellipse Properties:")); - pie_rows(app, ui, *pie, "xfp-pie"); - } - _ => { - widgets::subheader(ui, tl!("Shape Properties:")); - widgets::dim_label(ui, tl!(n.kind_label())); - } + if !live_shape_rows(app, ui, &n, live, "xfp", true) { + widgets::subheader(ui, tl!("Shape Properties:")); + widgets::dim_label(ui, tl!(n.kind_label())); } } if pstate::<bool>(ui.ctx(), "xf-hide-options") { @@ -377,6 +363,33 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// A live rectangle's, polygon's or ellipse's properties (Transform and Properties panels, and the +/// Contextual Task Bar), their widget ids under `id`. `headed` adds the Rectangle and Polygon +/// Properties headings; an ellipse's heading always shows. Returns false, drawing nothing, for +/// other live shapes. +pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShape, id: &str, headed: bool) -> bool { + match live { + LiveShape::Rectangle { .. } => { + if headed { + widgets::subheader(ui, tl!("Rectangle Properties:")); + } + corner_radius_row(app, ui, n, &format!("{id}-radius")); + } + LiveShape::Polygon { .. } => { + if headed { + widgets::subheader(ui, tl!("Polygon Properties:")); + } + polygon_rows(app, ui, n, live, &format!("{id}-polygon")); + } + LiveShape::Ellipse { pie, .. } => { + widgets::subheader(ui, tl!("Ellipse Properties:")); + pie_rows(app, ui, *pie, &format!("{id}-pie")); + } + _ => return false, + } + true +} + /// An ellipse's Pie Start and End Angle (degrees, counterclockwise from 3 o'clock; 0 to 360 is the /// whole ellipse) and Invert Pie, which shows the other part of it (Transform and Properties panels). pub(crate) fn pie_rows(app: &mut VectorcraftApp, ui: &mut Ui, pie: (f64, f64), id: &str) { diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 27c49ac5e3..2cc79e6daa 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -1,6 +1,7 @@ //! The Contextual Task Bar's actions for each kind of selection: open paths offer Join and Edit //! Path, compound paths and clipping masks their Release, images selected with vector art Make -//! Clipping Mask, and type converts between point and area type. +//! Clipping Mask, type converts between point and area type, and a basic shape shows its +//! properties in place of Lock. use egui::{Event, PointerButton, Pos2, Rect, vec2}; use serde_json::json; @@ -219,6 +220,149 @@ fn direct_selected_anchors_still_offer_remove_and_cut() { assert!(!has(&texts, "Edit Path"), "{texts:?}"); } +/// Click the task bar's button left of More Options (Lock, or a basic shape's Shape Properties), +/// and return the context and what the frame after the click draws. +fn click_lock_slot(app: &mut VectorcraftApp) -> (egui::Context, Vec<(String, Rect)>) { + let (ctx, _) = bar(app); + let r = canvas::task_bar_rect(&ctx).expect("the task bar shows"); + // Right to left: the frame's margin, More Options, then the button. + let p = Pos2::new(r.right() - 8.0 - 30.0 - 6.0 - 15.0, r.center().y); + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, &ctx, vec![Event::PointerMoved(p)]); + frame(app, &ctx, vec![press(true)]); + frame(app, &ctx, vec![press(false)]); + let texts = frame(app, &ctx, vec![]); + (ctx, texts) +} + +/// Type `value` into the field showing `field` and press Enter. +fn type_into(app: &mut VectorcraftApp, ctx: &egui::Context, texts: &[(String, Rect)], field: &str, value: &str) { + let p = at(texts, field); + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![Event::PointerMoved(p), press(true), press(false)]); + // Focus selected the whole field: typing replaces it. + frame(app, ctx, vec![]); + frame(app, ctx, vec![Event::Text(value.into())]); + let enter = Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + frame(app, ctx, vec![enter]); + frame(app, ctx, vec![]); +} + +fn live(app: &VectorcraftApp, id: u64) -> vectorcraft_doc::LiveShape { + match kind(app, id) { + NodeKind::Path { live: Some(l), .. } => *l, + k => panic!("not a live shape: {k:?}"), + } +} + +fn locked(app: &VectorcraftApp, id: u64) -> bool { + app.session.active().unwrap().doc.node(NodeId(id)).unwrap().locked +} + +/// A basic shape selected with the Selection tool shows Shape Properties in place of Lock: a +/// rectangle, rounded rectangle, ellipse or polygon, each under its own heading. +#[test] +fn a_basic_shape_shows_its_properties_in_place_of_lock() { + let mut app = app(); + let shapes = [ + (id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60})).unwrap()), "Rectangle Properties:"), + (id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60, "radius": 10})).unwrap()), "Rectangle Properties:"), + (id(app.run("shape.ellipse", json!({"x": 40, "y": 40, "width": 80, "height": 60})).unwrap()), "Ellipse Properties:"), + (id(app.run("shape.polygon", json!({"cx": 100, "cy": 100, "radius": 40, "sides": 6})).unwrap()), "Polygon Properties:"), + ]; + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + for (shape, heading) in shapes { + select(&mut app, &[shape]); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, heading), "the popup starts closed: {texts:?}"); + let (_, texts) = click_lock_slot(&mut app); + assert!(has(&texts, heading), "{heading}: {texts:?}"); + assert!(!locked(&app, shape), "the button doesn't lock the shape"); + } +} + +/// The popup's fields edit the shape through `object.setLiveShape`, and Undo restores it. +#[test] +fn the_shape_properties_popup_edits_the_shape() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let corners = |app: &VectorcraftApp, id: u64| match live(app, id) { + vectorcraft_doc::LiveShape::Rectangle { radii, .. } => radii, + l => panic!("{l:?}"), + }; + let rect = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60, "radius": 10})).unwrap()); + select(&mut app, &[rect]); + let (ctx, texts) = click_lock_slot(&mut app); + type_into(&mut app, &ctx, &texts, "10 pt", "20"); + assert_eq!(corners(&app, rect), [20.0; 4]); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(corners(&app, rect), [10.0; 4]); + + let ellipse = id(app.run("shape.ellipse", json!({"x": 40, "y": 40, "width": 80, "height": 60})).unwrap()); + select(&mut app, &[ellipse]); + let pie = |app: &VectorcraftApp| match live(app, ellipse) { + vectorcraft_doc::LiveShape::Ellipse { pie, .. } => pie, + l => panic!("{l:?}"), + }; + let (ctx, texts) = click_lock_slot(&mut app); + type_into(&mut app, &ctx, &texts, "360°", "180"); + assert_eq!(pie(&app), (0.0, 180.0)); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(pie(&app), (0.0, 360.0)); + + let polygon = id(app.run("shape.polygon", json!({"cx": 100, "cy": 100, "radius": 40, "sides": 6})).unwrap()); + select(&mut app, &[polygon]); + let sides = |app: &VectorcraftApp| match live(app, polygon) { + vectorcraft_doc::LiveShape::Polygon { sides, .. } => sides, + l => panic!("{l:?}"), + }; + let (ctx, texts) = click_lock_slot(&mut app); + type_into(&mut app, &ctx, &texts, "6", "5"); + assert_eq!(sides(&app), 5); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(sides(&app), 6); +} + +/// Every other selection keeps Lock: a plain closed path, a star (a plain path), a path with live +/// corners, a group and several objects. The Direct Selection tool keeps it for a basic shape. +#[test] +fn other_selections_keep_lock() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let closed = json!({"anchors": [{"x": 50, "y": 200}, {"x": 150, "y": 80}, {"x": 250, "y": 200}], "closed": true}); + let path = id(app.run("path.create", closed).unwrap()); + let star = id(app.run("shape.star", json!({"cx": 200, "cy": 150, "radius1": 40})).unwrap()); + let rounded = id(app.run("shape.star", json!({"cx": 300, "cy": 150, "radius1": 40})).unwrap()); + select(&mut app, &[rounded]); + app.run("object.setLiveShape", json!({"radius": 4})).unwrap(); + assert!(matches!(live(&app, rounded), vectorcraft_doc::LiveShape::Path { .. })); + let a = id(app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 30, "height": 30})).unwrap()); + let b = id(app.run("shape.ellipse", json!({"x": 60, "y": 20, "width": 30, "height": 30})).unwrap()); + select(&mut app, &[a, b]); + let several = [a, b]; + let c = id(app.run("shape.rectangle", json!({"x": 20, "y": 250, "width": 30, "height": 30})).unwrap()); + let d = id(app.run("shape.rectangle", json!({"x": 60, "y": 250, "width": 30, "height": 30})).unwrap()); + select(&mut app, &[c, d]); + let group = id(app.run("object.group", json!({})).unwrap()); + let headings = ["Rectangle Properties:", "Ellipse Properties:", "Polygon Properties:"]; + for ids in [vec![path], vec![star], vec![rounded], vec![group], several.to_vec()] { + select(&mut app, &ids); + let (_, texts) = click_lock_slot(&mut app); + assert!(!headings.iter().any(|h| has(&texts, h)), "{ids:?}: {texts:?}"); + assert!(ids.iter().all(|i| locked(&app, *i)), "{ids:?} locks"); + app.run("object.unlockAll", json!({})).unwrap(); + } + let shape = id(app.run("shape.rectangle", json!({"x": 300, "y": 40, "width": 30, "height": 30})).unwrap()); + for tool in ["directSelection", "groupSelection"] { + app.run("tool.select", json!({ "tool": tool })).unwrap(); + select(&mut app, &[shape]); + let (_, texts) = click_lock_slot(&mut app); + assert!(!has(&texts, "Rectangle Properties:"), "{tool}: {texts:?}"); + assert!(locked(&app, shape), "{tool} keeps Lock"); + app.run("object.unlockAll", json!({})).unwrap(); + } +} + /// A compound path under the Direct Selection tool isn't offered Edit Path, which would only switch /// to the tool already in use; the Selection tool still offers it. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6d97e0097d..cc2b987b3f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -572,6 +572,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With one image selected, the contextual task bar offers Image Trace, which traces the image at once with the Default preset (the Image Trace panel is left as it was), and Crop Image; with an Image Trace object it offers Expand, which keeps only the traced paths. This follows Illustrator's bar: for a selected image it includes Image Trace, Retype and Crop Image, and traced artwork can be expanded from it ([Contextual Task Bar announcement](https://community.adobe.com/announcements-651/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580)). Offset Path and Simplify, which don't apply to an image, aren't offered for one. Not done: Retype, which the app doesn't have. - With the Artboard tool, the contextual task bar sits under the selected artboards and offers Resize (Artboard Options for the active artboard), Duplicate (each selected artboard, in one undo step, the copies then selected), Rearrange All (with two or more artboards) and Export (Export for Screens with the selected artboards checked). This follows Illustrator's bar: while the Artboard tool is in use, it has options for resizing, duplicating and exporting artboards (the [Contextual Task Bar announcement](https://community.adobe.com/questions-652/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580); Rearrange and Export on the bar: [Managing Artboards in Illustrator](https://creativepro.com/managing-artboards-in-illustrator/)). - The contextual task bar offers more next steps by selection (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html>): an open path Join and Edit Path (the Direct Selection tool), a closed path Edit Path, a compound path Edit Path and Release Compound Path, a clipping group Edit Clipping Path and Release Clipping Mask instead of Ungroup and Isolate, an image selected with vector art Make Clipping Mask instead of Unite, and point or area type Convert To Area Type or Convert To Point Type beside Create Outlines. Evidence: `crates/ui-egui/src/tests/taskbar.rs`. + - With a live rectangle, rounded rectangle, ellipse or polygon selected with the Selection tool, the contextual task bar shows a Shape Properties button in place of Lock. It opens a popup with the shape's rows from the Transform panel (corner radius, pie angles, or sides, angle, corner and radius), which edit it through `object.setLiveShape`. The overview says: "For a basic shape created with tools such as the Rectangle tool and the Star tool, you get the option to adjust its properties instead of Lock Object" ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Object › Lock and ⌘2 still lock the shape. Not done: stars, which the app draws as plain paths. Evidence: `a_basic_shape_shows_its_properties_in_place_of_lock`, `the_shape_properties_popup_edits_the_shape` and `other_selections_keep_lock` in `crates/ui-egui/src/tests/taskbar.rs`. - The contextual task bar has a Stroke chip beside the Fill chip, drawn with the paint the Stroke proxy shows (a "?" when the selected objects' strokes differ, as on the Fill chip); a click brings the Stroke proxy forward and shows the Swatches panel wherever it is docked, floating or closed, as a click on the Fill chip does for the Fill proxy. The reference app's bar has Fill and Stroke controls for changing an object's colors ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Evidence: `the_task_bar_shows_a_stroke_chip_beside_fill` and `the_task_bar_chips_follow_the_proxies_and_show_swatches_anywhere` in `crates/ui-egui/src/canvas/tests.rs`. - With anchor points selected with Direct Selection, the contextual task bar offers Remove Anchor Points, Connect (`path.join`), Cut Path, Corner and Smooth (`path.convertAnchors` with `to` set to `corner` or `smooth`), the commands of the Control bar's anchor buttons. As in Illustrator, whose bar has items that delete the selected anchors, join selected end points, split the path at the selected anchors, and make the selected anchors corner or smooth points ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Not done: Simplify, which the bar offers only while no anchors are selected, and the bar's Smooth item that adjusts a path's curvature, a command the app doesn't have (Object › Path › Smooth). - Tool flyouts tear off: dragging or clicking the tear-off bar on a flyout's right side (or releasing the long press over it) floats its group as a strip of tool buttons, moved by the same bar and put back in the toolbar by the × at its top (`window.floatTools`). While a group floats, the presses that would open its flyout raise the strip instead. Floating strips are kept with the preferences and in user workspaces. Not done: turning a strip vertical, docking it. From 5a00238a0c55bd78eea027d6fb6c2042f9650bc4 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 03:26:59 -0700 Subject: [PATCH 121/260] Docs: describe the Shape Properties overview line in our own words The evidence line for the Shape Properties button quoted the reference app's overview. It now paraphrases it and keeps the citation. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cc2b987b3f..e950d73e70 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -572,7 +572,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With one image selected, the contextual task bar offers Image Trace, which traces the image at once with the Default preset (the Image Trace panel is left as it was), and Crop Image; with an Image Trace object it offers Expand, which keeps only the traced paths. This follows Illustrator's bar: for a selected image it includes Image Trace, Retype and Crop Image, and traced artwork can be expanded from it ([Contextual Task Bar announcement](https://community.adobe.com/announcements-651/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580)). Offset Path and Simplify, which don't apply to an image, aren't offered for one. Not done: Retype, which the app doesn't have. - With the Artboard tool, the contextual task bar sits under the selected artboards and offers Resize (Artboard Options for the active artboard), Duplicate (each selected artboard, in one undo step, the copies then selected), Rearrange All (with two or more artboards) and Export (Export for Screens with the selected artboards checked). This follows Illustrator's bar: while the Artboard tool is in use, it has options for resizing, duplicating and exporting artboards (the [Contextual Task Bar announcement](https://community.adobe.com/questions-652/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580); Rearrange and Export on the bar: [Managing Artboards in Illustrator](https://creativepro.com/managing-artboards-in-illustrator/)). - The contextual task bar offers more next steps by selection (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html>): an open path Join and Edit Path (the Direct Selection tool), a closed path Edit Path, a compound path Edit Path and Release Compound Path, a clipping group Edit Clipping Path and Release Clipping Mask instead of Ungroup and Isolate, an image selected with vector art Make Clipping Mask instead of Unite, and point or area type Convert To Area Type or Convert To Point Type beside Create Outlines. Evidence: `crates/ui-egui/src/tests/taskbar.rs`. - - With a live rectangle, rounded rectangle, ellipse or polygon selected with the Selection tool, the contextual task bar shows a Shape Properties button in place of Lock. It opens a popup with the shape's rows from the Transform panel (corner radius, pie angles, or sides, angle, corner and radius), which edit it through `object.setLiveShape`. The overview says: "For a basic shape created with tools such as the Rectangle tool and the Star tool, you get the option to adjust its properties instead of Lock Object" ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Object › Lock and ⌘2 still lock the shape. Not done: stars, which the app draws as plain paths. Evidence: `a_basic_shape_shows_its_properties_in_place_of_lock`, `the_shape_properties_popup_edits_the_shape` and `other_selections_keep_lock` in `crates/ui-egui/src/tests/taskbar.rs`. + - With a live rectangle, rounded rectangle, ellipse or polygon selected with the Selection tool, the contextual task bar shows a Shape Properties button in place of Lock. It opens a popup with the shape's rows from the Transform panel (corner radius, pie angles, or sides, angle, corner and radius), which edit it through `object.setLiveShape`. The overview describes this: when a shape drawn with a shape tool (Rectangle, Star) is selected, the bar offers to change its properties where Lock Object would be ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Object › Lock and ⌘2 still lock the shape. Not done: stars, which the app draws as plain paths. Evidence: `a_basic_shape_shows_its_properties_in_place_of_lock`, `the_shape_properties_popup_edits_the_shape` and `other_selections_keep_lock` in `crates/ui-egui/src/tests/taskbar.rs`. - The contextual task bar has a Stroke chip beside the Fill chip, drawn with the paint the Stroke proxy shows (a "?" when the selected objects' strokes differ, as on the Fill chip); a click brings the Stroke proxy forward and shows the Swatches panel wherever it is docked, floating or closed, as a click on the Fill chip does for the Fill proxy. The reference app's bar has Fill and Stroke controls for changing an object's colors ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Evidence: `the_task_bar_shows_a_stroke_chip_beside_fill` and `the_task_bar_chips_follow_the_proxies_and_show_swatches_anywhere` in `crates/ui-egui/src/canvas/tests.rs`. - With anchor points selected with Direct Selection, the contextual task bar offers Remove Anchor Points, Connect (`path.join`), Cut Path, Corner and Smooth (`path.convertAnchors` with `to` set to `corner` or `smooth`), the commands of the Control bar's anchor buttons. As in Illustrator, whose bar has items that delete the selected anchors, join selected end points, split the path at the selected anchors, and make the selected anchors corner or smooth points ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Not done: Simplify, which the bar offers only while no anchors are selected, and the bar's Smooth item that adjusts a path's curvature, a command the app doesn't have (Object › Path › Smooth). - Tool flyouts tear off: dragging or clicking the tear-off bar on a flyout's right side (or releasing the long press over it) floats its group as a strip of tool buttons, moved by the same bar and put back in the toolbar by the × at its top (`window.floatTools`). While a group floats, the presses that would open its flyout raise the strip instead. Floating strips are kept with the preferences and in user workspaces. Not done: turning a strip vertical, docking it. From b46cdc4e4ddfca13f00b45a398b1548d3e87165c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 1 Nov 2026 00:37:24 +0700 Subject: [PATCH 122/260] Isolation mode: Lock, Unlock All, Hide and Show All work on the isolated art Squashed from #4849 onto main. --- crates/engine/src/cmd.rs | 28 +- crates/engine/src/cmd/edit.rs | 22 +- crates/engine/src/cmd/menucmds.rs | 71 ++- crates/engine/src/cmd/object/arrange.rs | 40 +- crates/engine/src/cmd/object/commands.rs | 18 +- crates/engine/src/tests/menucmds.rs | 482 +++++++++++++----- crates/ui-egui/src/canvas/tests.rs | 12 +- crates/ui-egui/src/menus/tests.rs | 10 +- crates/ui-egui/src/panels/properties/tests.rs | 17 +- crates/ui-egui/src/shortcuts/tests.rs | 8 +- docs/mcp.md | 23 +- docs/target-app-parity.md | 6 +- 12 files changed, 511 insertions(+), 226 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index dc047d9d65..2d9fea923f 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -182,20 +182,22 @@ pub fn has_multi(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; if st.selection.len() < 2 { Err("select at least two objects".into()) } else { Ok(()) } } -/// A document is open and it is not in isolation mode: Object › Lock's and Object › Hide's items, -/// Unlock All and Show All are off in isolation mode. Pattern editing mode and opacity mask -/// editing isolate their art too, and do not count as isolation mode here while their own layer -/// is the isolated one. An object isolated inside them counts. -pub fn outside_isolation(s: &Session) -> std::result::Result<(), String> { - let st = s.active().ok_or("no document open")?; - let editing_layer = |l| st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == l) || st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == l); - if st.isolation.is_some_and(|l| !editing_layer(l)) { Err("exit isolation mode first".into()) } else { Ok(()) } +/// The isolated group, layer or object in isolation mode. Pattern editing mode and opacity mask +/// editing isolate their own layer, which does not count here; an object isolated inside them +/// counts. +pub(crate) fn ordinary_isolation(st: &crate::DocState) -> Option<vectorcraft_doc::NodeId> { + st.isolation.filter(|l| !st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l) && !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l)) } -/// Objects are selected ([`has_selection`]) and the document is not in isolation mode -/// ([`outside_isolation`]). -pub fn has_selection_outside_isolation(s: &Session) -> std::result::Result<(), String> { - outside_isolation(s)?; - has_selection(s) +/// Objects are selected ([`has_selection`]), and in isolation mode ([`ordinary_isolation`]) at +/// least one of them is inside the isolated object: Object › Lock's and Object › Hide's items. +pub fn has_selected_member(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + let Some(root) = ordinary_isolation(st) else { return has_selection(s) }; + if st.selection.objects.iter().any(|id| inside_isolation(&st.doc, root, *id)) { Ok(()) } else { Err("nothing selected".into()) } +} +/// Whether `id` lies inside the isolated object `root` (the root itself does not). +pub(crate) fn inside_isolation(d: &vectorcraft_doc::Document, root: vectorcraft_doc::NodeId, id: vectorcraft_doc::NodeId) -> bool { + id != root && d.ancestry(id).is_some_and(|a| a.contains(&root)) } pub fn can_undo(s: &Session) -> std::result::Result<(), String> { s.active().filter(|d| !d.history.undo.is_empty()).map(|_| ()).ok_or_else(|| "nothing to undo".into()) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index a2cab84a89..3534d40ac5 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -566,17 +566,29 @@ pub(crate) fn selected_roots(s: &Session) -> Result<Vec<NodeId>> { /// rest still go to the compound path, which holds the paint. pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> { let st = s.doc()?; - Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), true)) + Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_| true)) +} + +/// [`selected_roots`] for the selected objects inside the isolated object `root` +/// ([`super::inside_isolation`]): `root` itself and objects outside it are left out before the +/// objects held by another selected object are dropped. A selected path of a compound path stands +/// for its compound unless the compound is `root` or `members` is set (as in +/// [`selected_roots_to_transform`]). +pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result<Vec<NodeId>> { + let st = s.doc()?; + let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect(); + Ok(roots_within(&st.doc, ids, |compound| members || compound == root)) } /// The top-level objects among `ids` (in paint order): compound-path members stand for their /// compound, and ids whose ancestor is also listed, and layers, are dropped. pub(crate) fn roots_of(doc: &Document, ids: Vec<NodeId>) -> Vec<NodeId> { - roots_within(doc, ids, false) + roots_within(doc, ids, |_| false) } -/// [`roots_of`]; with `members`, a compound path's member listed stays itself. -fn roots_within(doc: &Document, ids: Vec<NodeId>, members: bool) -> Vec<NodeId> { +/// [`roots_of`]; a compound path's member listed stays itself when `members` holds for the +/// compound's id. +fn roots_within(doc: &Document, ids: Vec<NodeId>, members: impl Fn(NodeId) -> bool) -> Vec<NodeId> { // Every id's place in the tree, found in one walk (a lookup per id is a walk per id). let paths = doc.index_paths(ids.iter().copied()); // A compound-path member acts as its compound (compounds are one object). @@ -586,7 +598,7 @@ fn roots_within(doc: &Document, ids: Vec<NodeId>, members: bool) -> Vec<NodeId> let path = paths.get(&id); let parent = path.and_then(|p| p.split_last()).map(|(_, up)| up).filter(|up| !up.is_empty()); match parent.and_then(|up| doc.node_at(up).map(|n| (up, n))) { - Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !members => (n.id, Some(up.to_vec())), + Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !members(n.id) => (n.id, Some(up.to_vec())), _ => (id, path.cloned()), } }) diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 7a93ac6176..73cf96c9ba 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -15,8 +15,8 @@ use vectorcraft_render::encode::{RasterExportOptions, RasterFormat}; use super::edit::{duplicate_in, selected_roots, selected_roots_to_transform}; use super::{ - CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selection, - has_selection_outside_isolation, switch_or, + CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selected_member, + has_selection, switch_or, }; /// Session-level (not saved) state owned by the menu commands. @@ -43,8 +43,8 @@ pub fn specs() -> Vec<CommandSpec> { "All Artwork Above", ["Object", "Lock"], None, - "{} lock objects in the same layer that are above and overlap the selection, deselecting every selected object left locked or hidden (the key object too) → {count}", - has_selection_outside_isolation, + "{} lock objects in the same layer that are above and overlap the selection, deselecting every selected object left locked or hidden (the key object too); in isolation mode, lock the selected objects and the objects above them inside the isolated object → {count}", + has_selected_member, |s, _| above(s, true) ), cmd!( @@ -52,8 +52,8 @@ pub fn specs() -> Vec<CommandSpec> { "Other Layers", ["Object", "Lock"], None, - "{} lock every layer that holds no selected object → {count}", - has_selection_outside_isolation, + "{} lock every layer that holds no selected object; in isolation mode, change nothing and return a count of 0 → {count}", + has_selected_member, |s, _| other_layers(s, true) ), cmd!( @@ -61,8 +61,8 @@ pub fn specs() -> Vec<CommandSpec> { "Unselected Artwork", ["Object", "Lock"], Some("Cmd+Alt+Shift+2"), - "{} lock unselected artwork in one undo step, including unselected members of partly selected groups, clipping groups and compound paths, and guides while Lock Guides is on; hidden art and art on locked layers stay unlocked; a selected layer's art counts as selected; in isolation, only art inside the isolated object is affected; object.unlockAll unlocks locked art document-wide → {count}", - has_selection, + "{} lock unselected artwork in one undo step, including unselected members of partly selected groups, clipping groups and compound paths, and guides while Lock Guides is on; hidden art and art on locked layers stay unlocked; a selected layer's art counts as selected; in isolation, only art inside the isolated object is affected; object.unlockAll unlocks locked art document-wide, or inside the isolated object in isolation mode → {count}", + has_selected_member, |s, _| unselected_art(s, true) ), cmd!( @@ -70,8 +70,8 @@ pub fn specs() -> Vec<CommandSpec> { "All Artwork Above", ["Object", "Hide"], None, - "{} hide objects in the same layer that are above and overlap the selection, deselecting every selected object left hidden or locked (the key object too) → {count}", - has_selection_outside_isolation, + "{} hide objects in the same layer that are above and overlap the selection, deselecting every selected object left hidden or locked (the key object too); in isolation mode, hide the selected objects and the objects above them inside the isolated object → {count}", + has_selected_member, |s, _| above(s, false) ), cmd!( @@ -79,8 +79,8 @@ pub fn specs() -> Vec<CommandSpec> { "Other Layers", ["Object", "Hide"], None, - "{} hide every layer that holds no selected object → {count}", - has_selection_outside_isolation, + "{} hide every layer that holds no selected object; in isolation mode, change nothing and return a count of 0 → {count}", + has_selected_member, |s, _| other_layers(s, false) ), cmd!( @@ -88,8 +88,8 @@ pub fn specs() -> Vec<CommandSpec> { "Unselected Artwork", ["Object", "Hide"], Some("Cmd+Alt+Shift+3"), - "{} hide, in one undo step, every object select.all takes that is not selected and holds no selected object; in a group that holds one it hides the other members one by one, and a clip group, compound path or other object that holds one stays as it is; the objects of a selected layer count as selected; while Lock Guides is on, guide paths count as selected and stay as they are; object.showAll shows them again; disabled in isolation mode → {count}", - has_selection_outside_isolation, + "{} hide, in one undo step, every object select.all takes that is not selected and holds no selected object; in a group that holds one it hides the other members one by one, and a clip group, compound path or other object that holds one stays as it is; the objects of a selected layer count as selected; while Lock Guides is on, guide paths count as selected and stay as they are; in isolation mode, only art inside the isolated object is affected; object.showAll shows them again → {count}", + has_selected_member, |s, _| unselected_art(s, false) ), cmd!( @@ -243,14 +243,21 @@ fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> { // ---------- Lock / Hide ---------- fn above(s: &mut Session, lock: bool) -> Result<Value> { - let roots = selected_roots(s)?; - let d = &s.doc()?.doc; + let st = s.doc()?; + let d = &st.doc; + let isolation = super::ordinary_isolation(st); + // In isolation mode a path of the isolated compound path is an object of its own. + let roots = match isolation { + Some(root) => super::edit::selected_roots_inside(s, root, false)?, + None => selected_roots(s)?, + }; let symbols = d.symbol_boxes(); - // `selected` holds each selected object's visual bounds, by layer, with the index there of its - // ancestor directly inside the layer. Symbol instances are measured by their art. + // `selected` holds each selected object's visual bounds, by layer (the isolated object in + // isolation mode), with the index there of its ancestor directly inside it. Symbol instances + // are measured by their art. let mut selected: BTreeMap<NodeId, Vec<(usize, Rect)>> = BTreeMap::new(); for id in &roots { - let Some(layer) = d.layer_of(*id) else { continue }; + let Some(layer) = isolation.or_else(|| d.layer_of(*id)) else { continue }; // The selected object's ancestor directly inside the layer. let anc = d.ancestry(*id).unwrap_or_default(); let Some(pos) = anc.iter().position(|a| *a == layer) else { continue }; @@ -259,10 +266,14 @@ fn above(s: &mut Session, lock: bool) -> Result<Value> { let Some((_, idx, _)) = d.position(top) else { continue }; selected.entry(layer).or_default().push((idx, b)); } - // The loop walks up each layer once. Each object that is not selected and overlaps a selected - // object below it is locked (Lock) or hidden (Hide). + // The loop walks up each layer once, or the isolated object in isolation mode. Each object that + // is not selected and overlaps a selected object below it is locked (Lock) or hidden (Hide). In + // isolation mode the selected objects are locked or hidden too. let roots: HashSet<NodeId> = roots.into_iter().collect(); let mut hits: BTreeSet<NodeId> = BTreeSet::new(); + if isolation.is_some() { + hits.extend(roots.iter().copied()); + } for (layer, mut below) in selected { below.sort_by_key(|(idx, _)| *idx); let mut below = below.into_iter().peekable(); @@ -307,6 +318,11 @@ fn above(s: &mut Session, lock: bool) -> Result<Value> { fn other_layers(s: &mut Session, lock: bool) -> Result<Value> { let st = s.doc()?; + // In isolation mode the other layers lie outside the isolated group, layer or sublayer, so the + // document and its undo history stay as they are. + if super::ordinary_isolation(st).is_some() { + return Ok(json!({ "count": 0 })); + } let keep: Vec<NodeId> = st.selection.objects.iter().filter_map(|id| st.doc.ancestry(*id)).flatten().collect(); let others: Vec<NodeId> = st.doc.layers.iter().map(|l| l.id).filter(|l| !keep.contains(l)).collect(); let n = others.len(); @@ -370,10 +386,19 @@ fn unselected( } fn unselected_art(s: &mut Session, lock: bool) -> Result<Value> { - let roots = selected_roots_to_transform(s)?; + // In isolation mode the isolated object itself does not count as a selected object. + let iso = super::ordinary_isolation(s.doc()?); + let roots = match iso { + Some(root) => super::edit::selected_roots_inside(s, root, true)?, + None => selected_roots_to_transform(s)?, + }; let guides_locked = s.menu.guides_locked; let st = s.doc()?; - let ids = unselected(&st.doc, st.isolation, &st.selection.objects, &roots, guides_locked, lock); + let selection: Vec<NodeId> = match iso { + Some(root) => st.selection.objects.iter().copied().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect(), + None => st.selection.objects.to_vec(), + }; + let ids = unselected(&st.doc, st.isolation, &selection, &roots, guides_locked, lock); // With nothing to lock (Lock) or hide (Hide), the document and its undo history stay as they are. if !ids.is_empty() { s.edit(if lock { "Lock" } else { "Hide" }, |d, _| { diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index 325024bcb1..741475d87f 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -143,7 +143,7 @@ pub(super) fn ungroup(s: &mut Session, _: &Value) -> Result<Value> { } pub(super) fn lock(s: &mut Session, _: &Value) -> Result<Value> { - let ids = selected_roots(s)?; + let ids = selected_lock_hide_roots(s)?; // With every selected object already locked, the document and its undo history stay as they // are, and the objects are deselected. let d = &s.doc()?.doc; @@ -163,6 +163,16 @@ pub(super) fn lock(s: &mut Session, _: &Value) -> Result<Value> { ok() } +/// The selected objects ([`selected_roots`]) that Lock › Selection and Hide › Selection change: in +/// isolation mode, only those inside the isolated object, where a path of the isolated compound +/// path is an object of its own. +fn selected_lock_hide_roots(s: &Session) -> Result<Vec<NodeId>> { + match crate::cmd::ordinary_isolation(s.doc()?) { + Some(root) => crate::cmd::edit::selected_roots_inside(s, root, false), + None => selected_roots(s), + } +} + fn collect_flag(d: &Document, f: impl Fn(&Node) -> bool) -> Vec<NodeId> { let mut v = vec![]; d.walk(|n| { @@ -174,14 +184,28 @@ fn collect_flag(d: &Document, f: impl Fn(&Node) -> bool) -> Vec<NodeId> { } /// The objects that `f` picks for `object.unlockAll` and `object.showAll` (`cmd`): in the whole -/// document, or with `scope: "group"` inside the groups that hold the selected objects. A selected -/// group is the group that holds its own members, and the objects of a group inside another such -/// group are taken once. With `scope: "group"` and no selected object in a group, it returns an -/// error. +/// document, inside the isolated object in isolation mode, or with `scope: "group"` inside the +/// groups that hold the selected objects (in isolation mode, only the objects of those groups +/// that are inside the isolated object). A selected group is the group that holds its own +/// members, and the objects of a group inside another such group are taken once. With +/// `scope: "group"` and no selected object in a group, it returns an error. fn collect_flag_in_scope(s: &Session, cmd: &str, p: &Value, f: impl Fn(&Node) -> bool) -> Result<Vec<NodeId>> { let st = s.doc()?; let d = &st.doc; if choice(p, cmd, "scope", &["document", "group"])? != Some("group") { + if let Some(root) = crate::cmd::ordinary_isolation(st) { + let mut ids = vec![]; + if let Some(node) = d.node(root) { + for child in node.children().into_iter().flatten() { + child.walk(&mut |n| { + if !n.is_layer() && f(n) { + ids.push(n.id); + } + }); + } + } + return Ok(ids); + } return Ok(collect_flag(d, f)); } let is_group = |id: &NodeId| d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. })); @@ -204,6 +228,10 @@ fn collect_flag_in_scope(s: &Session, cmd: &str, p: &Value, f: impl Fn(&Node) -> }); } } + // In isolation mode only the objects inside the isolated object are taken. + if let Some(root) = crate::cmd::ordinary_isolation(st) { + v.retain(|id| crate::cmd::inside_isolation(d, root, *id)); + } Ok(v) } @@ -226,7 +254,7 @@ pub(super) fn unlock_all(s: &mut Session, p: &Value) -> Result<Value> { } pub(super) fn hide(s: &mut Session, _: &Value) -> Result<Value> { - let ids = selected_roots(s)?; + let ids = selected_lock_hide_roots(s)?; // With every selected object already hidden, the document and its undo history stay as they // are, and the objects are deselected. let d = &s.doc()?.doc; diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index d5885ad3cf..69f464edb1 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -6,7 +6,7 @@ use super::props::set_props; use super::shape::{expand_shape, set_live_shape}; use super::transform::{move_cmd, nudge, reflect, rotate, scale, shear, transform, transform_again}; use super::{CommandSpec, cmd, has_doc, has_multi, has_selection, has_selection_or_guides}; -use crate::cmd::{has_selection_outside_isolation, outside_isolation}; +use crate::cmd::has_selected_member; pub fn specs() -> Vec<CommandSpec> { vec![ @@ -150,8 +150,8 @@ pub fn specs() -> Vec<CommandSpec> { "Selection", ["Object", "Lock"], Some("Cmd+2"), - "{ids?: [id…] (selected first; default: the selection)}", - has_selection_outside_isolation, + "{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}", + has_selected_member, lock ), cmd!( @@ -159,8 +159,8 @@ pub fn specs() -> Vec<CommandSpec> { "Unlock All", ["Object"], Some("Cmd+Alt+2"), - "{scope?: \"document\"|\"group\" (default document; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them → {count}", - outside_isolation, + "{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them → {count}", + has_doc, unlock_all ), cmd!( @@ -168,8 +168,8 @@ pub fn specs() -> Vec<CommandSpec> { "Selection", ["Object", "Hide"], Some("Cmd+3"), - "{ids?: [id…] (selected first; default: the selection)}", - has_selection_outside_isolation, + "{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}", + has_selected_member, hide ), cmd!( @@ -177,8 +177,8 @@ pub fn specs() -> Vec<CommandSpec> { "Show All", ["Object"], Some("Cmd+Alt+3"), - "{scope?: \"document\"|\"group\" (default document; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them → {count}", - outside_isolation, + "{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them → {count}", + has_doc, show_all ), cmd!( diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index ff11009b16..91194b2730 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -316,137 +316,347 @@ fn shown_and_locked(s: &Session, id: NodeId) -> (bool, bool) { (n.visible, n.locked) } -/// Each of `commands` is off in isolation mode: the command list reports it disabled, its error -/// names isolation mode, and so does the error of a call that gives the selection as `ids` (for a -/// command that takes them). -fn off_in_isolation(s: &mut Session, commands: &[&str]) { - let ids: Vec<u64> = selected(s).iter().map(|i| i.0).collect(); - for c in commands { - let spec = find_command(c).unwrap(); - assert_eq!(spec.info(s).disabled_reason.as_deref(), Some("exit isolation mode first"), "{c}"); - let given = cmd::params::takes_key(spec.params, "ids").then(|| json!({"ids": ids})); - for p in std::iter::once(json!({})).chain(given) { - let e = s.execute(c, &p).unwrap_err().to_string(); - assert!(e.contains("exit isolation mode first"), "{c} {p}: {e}"); - } - } -} - -/// In isolation mode, Lock › Selection and Hide › Selection are off and change nothing, in an -/// isolated group and in an isolated compound path with one of its paths selected. After Exit -/// Isolation Mode they lock and hide again. -#[test] -fn lock_and_hide_selection_are_off_in_isolation_mode() { - let mut s = session(); - let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); - let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0); - sel(&mut s, &[a, b]); - let g = id_of(&s.execute("object.group", &json!({})).unwrap()); - let outer = rect(&mut s, 100.0, 100.0, 100.0, 100.0); - let hole = rect(&mut s, 120.0, 120.0, 20.0, 20.0); - sel(&mut s, &[outer, hole]); - let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); - let ids = [a, b, g, outer, hole, compound]; - let commands = ["object.lock", "object.hide"]; - for (isolated, member) in [(g, a), (compound, hole)] { - s.execute("object.isolate", &json!({"id": isolated.0})).unwrap(); - sel(&mut s, &[member]); - off_in_isolation(&mut s, &commands); - for id in ids { - assert_eq!(shown_and_locked(&s, id), (true, false), "{id:?} in isolation of {isolated:?}"); - } - assert_eq!(selected(&s), [member]); - s.execute("object.exitIsolation", &json!({})).unwrap(); - } - sel(&mut s, &[a]); - s.execute("object.lock", &json!({})).unwrap(); - sel(&mut s, &[outer]); - s.execute("object.hide", &json!({})).unwrap(); - assert_eq!(shown_and_locked(&s, a), (true, true)); - assert_eq!(shown_and_locked(&s, compound), (false, false)); -} - -/// In isolation mode, Unlock All and Show All are off: the locked and the hidden objects outside -/// and inside the isolated group stay as they are. Pattern editing mode and opacity mask editing -/// are not isolation mode for them. -#[test] -fn unlock_all_and_show_all_are_off_in_isolation_mode() { - let mut s = session(); - let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); - let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0); - let c = rect(&mut s, 40.0, 0.0, 10.0, 10.0); - sel(&mut s, &[a, b, c]); - let g = id_of(&s.execute("object.group", &json!({})).unwrap()); - let locked = rect(&mut s, 100.0, 0.0, 10.0, 10.0); - let hidden = rect(&mut s, 120.0, 0.0, 10.0, 10.0); - s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap(); - s.execute("layer.setProps", &json!({"id": hidden.0, "visible": false})).unwrap(); - s.execute("layer.setProps", &json!({"id": b.0, "locked": true})).unwrap(); - s.execute("layer.setProps", &json!({"id": c.0, "visible": false})).unwrap(); - s.execute("object.isolate", &json!({"id": g.0})).unwrap(); - sel(&mut s, &[a]); - off_in_isolation(&mut s, &["object.unlockAll", "object.showAll"]); - for (id, want) in [(locked, (true, true)), (hidden, (false, false)), (b, (true, true)), (c, (false, false))] { - assert_eq!(shown_and_locked(&s, id), want, "{id:?}"); - } - s.execute("object.exitIsolation", &json!({})).unwrap(); - s.execute("object.unlockAll", &json!({})).unwrap(); - s.execute("object.showAll", &json!({})).unwrap(); - for id in [locked, hidden, b, c] { - assert_eq!(shown_and_locked(&s, id), (true, false), "{id:?}"); - } - - // Pattern editing mode: the tile's art hides and shows again. - let r = rect(&mut s, 300.0, 300.0, 10.0, 10.0); - sel(&mut s, &[r]); - s.execute("object.pattern.make", &json!({"name": "P"})).unwrap(); - let tile = selected(&s); - s.execute("object.hide", &json!({})).unwrap(); - assert!(!node(&s, tile[0]).visible, "hidden in pattern editing mode"); - s.execute("object.showAll", &json!({})).unwrap(); - assert!(node(&s, tile[0]).visible, "shown in pattern editing mode"); - // An object isolated inside pattern editing mode is isolation mode again. - s.execute("object.isolate", &json!({"id": tile[0].0})).unwrap(); - sel(&mut s, &[tile[0]]); - off_in_isolation(&mut s, &["object.unlockAll", "object.showAll"]); - s.execute("object.pattern.cancel", &json!({})).unwrap(); - - // Opacity mask editing: the mask's art locks and unlocks again. - let obj = rect(&mut s, 0.0, 300.0, 200.0, 200.0); - let m = rect(&mut s, 0.0, 300.0, 100.0, 200.0); - sel(&mut s, &[obj, m]); - s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); - s.execute("transparency.editOpacityMask", &json!({})).unwrap(); - let mask = selected(&s); - s.execute("object.lock", &json!({})).unwrap(); - assert!(node(&s, mask[0]).locked, "locked in opacity mask editing"); - s.execute("object.unlockAll", &json!({})).unwrap(); - assert!(!node(&s, mask[0]).locked, "unlocked in opacity mask editing"); -} - -/// In isolation mode, Lock › All Artwork Above, Lock › Other Layers, Hide › All Artwork Above and -/// Hide › Other Layers are off: the art above and the other layer stay as they are. -#[test] -fn lock_and_hide_above_and_other_layers_are_off_in_isolation_mode() { +/// Check command enablement, targets, selection and history inside an isolated group. +fn check_group_isolation_command(command: &str, lock: bool, a_changed: bool, b_changed: bool) { let mut s = session(); let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); - let b = rect(&mut s, 200.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 20.0, 20.0, 100.0, 100.0); sel(&mut s, &[a, b]); let g = id_of(&s.execute("object.group", &json!({})).unwrap()); - let over = rect(&mut s, 50.0, 50.0, 100.0, 100.0); + let out = rect(&mut s, 30.0, 30.0, 100.0, 100.0); let l2 = id_of(&s.execute("layer.new", &json!({})).unwrap()); + let p = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + sel(&mut s, &[out]); + assert!(!find_command(command).unwrap().info(&s).enabled, "{command}: outside selection"); + sel(&mut s, &[a]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + let before = history(&s).0; + s.execute(command, &json!({})).unwrap(); + let changed = |s: &Session, id| if lock { node(s, id).locked } else { !node(s, id).visible }; + assert_eq!(changed(&s, a), a_changed, "{command}: A"); + assert_eq!(changed(&s, b), b_changed, "{command}: B"); + assert!(!changed(&s, out) && !changed(&s, p) && !changed(&s, l2), "{command}: outside"); + assert_eq!(selected(&s), if a_changed { vec![] } else { vec![a] }, "{command}: selection"); + let steps = usize::from(a_changed || b_changed); + assert_eq!(history(&s).0, before + steps, "{command}: history"); + if steps != 0 { + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!changed(&s, a) && !changed(&s, b), "{command}: undo"); + assert_eq!(selected(&s), [a], "{command}: undo selection"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!((changed(&s, a), changed(&s, b)), (a_changed, b_changed), "{command}: redo"); + assert_eq!(selected(&s), if a_changed { vec![] } else { vec![a] }, "{command}: redo selection"); + } + if !a_changed && b_changed { + let restore = if lock { "object.unlockAll" } else { "object.showAll" }; + let params = if lock { json!({"id": out.0, "locked": true}) } else { json!({"id": out.0, "visible": false}) }; + s.execute("layer.setProps", ¶ms).unwrap(); + assert_eq!(s.execute(restore, &json!({})).unwrap(), json!({"count": 1})); + assert!(!changed(&s, b) && changed(&s, out), "{command}: scoped restore"); + } +} + +/// Generate the focused group isolation checks for each Lock and Hide command. +macro_rules! group_isolation_command_test { + ($name:ident, $command:literal, $lock:literal, $a:literal, $b:literal) => { + #[doc = concat!("Checks ", $command, " targets and history in group isolation.")] + #[test] + fn $name() { + check_group_isolation_command($command, $lock, $a, $b); + } + }; +} + +group_isolation_command_test!(lock_selection_in_group_isolation, "object.lock", true, true, false); +group_isolation_command_test!(lock_above_in_group_isolation, "object.lock.above", true, true, true); +group_isolation_command_test!(lock_other_layers_in_group_isolation, "object.lock.otherLayers", true, false, false); +group_isolation_command_test!(lock_unselected_in_group_isolation, "object.lock.unselected", true, false, true); +group_isolation_command_test!(hide_selection_in_group_isolation, "object.hide", false, true, false); +group_isolation_command_test!(hide_above_in_group_isolation, "object.hide.above", false, true, true); +group_isolation_command_test!(hide_other_layers_in_group_isolation, "object.hide.otherLayers", false, false, false); +group_isolation_command_test!(hide_unselected_in_group_isolation, "object.hide.unselected", false, false, true); + +/// Lock › Selection, Hide › Selection and All Artwork Above change only the selected path inside +/// an isolated compound path, with the other path below it. +#[test] +fn lock_and_hide_selection_in_isolated_compound_path() { + for command in ["object.lock", "object.hide", "object.lock.above", "object.hide.above"] { + let mut s = session(); + let outer = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let hole = rect(&mut s, 20.0, 20.0, 20.0, 20.0); + sel(&mut s, &[outer, hole]); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let outside = rect(&mut s, 150.0, 0.0, 20.0, 20.0); + s.execute("object.isolate", &json!({"id": compound.0})).unwrap(); + sel(&mut s, &[hole]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + let before = history(&s).0; + let want = if command.ends_with(".above") { json!({"count": 1}) } else { serde_json::Value::Null }; + assert_eq!(s.execute(command, &json!({})).unwrap(), want, "{command}"); + assert_eq!(history(&s).0, before + 1, "{command}"); + assert_eq!(selected(&s), [], "{command}"); + let expected = if command.starts_with("object.lock") { (true, true) } else { (false, false) }; + assert_eq!(shown_and_locked(&s, hole), expected, "{command}"); + for id in [outer, compound, outside] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}"); + } + } +} + +/// Lock › Selection, Hide › Selection and All Artwork Above change the whole compound path when +/// one of its paths is selected inside an isolated group that holds it. +#[test] +fn lock_and_hide_a_compound_path_member_in_an_isolated_group() { + for command in ["object.lock", "object.hide", "object.lock.above", "object.hide.above"] { + let mut s = session(); + let outer = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let hole = rect(&mut s, 20.0, 20.0, 20.0, 20.0); + sel(&mut s, &[outer, hole]); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let b = rect(&mut s, 150.0, 0.0, 20.0, 20.0); + sel(&mut s, &[compound, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + sel(&mut s, &[hole]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + let before = history(&s).0; + s.execute(command, &json!({})).unwrap(); + assert_eq!(history(&s).0, before + 1, "{command}"); + assert_eq!(selected(&s), [], "{command}"); + let expected = if command.starts_with("object.lock") { (true, true) } else { (false, false) }; + assert_eq!(shown_and_locked(&s, compound), expected, "{command}"); + for id in [outer, hole, b, g] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}"); + } + } +} + +/// Check that restore commands affect only isolated art and preserve undo and selection. +fn check_restore_in_group_isolation(change: &str, restore: &str, lock: bool) { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 20.0, 20.0, 100.0, 100.0); + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + let out = rect(&mut s, 30.0, 30.0, 100.0, 100.0); + let l2 = id_of(&s.execute("layer.new", &json!({})).unwrap()); + let p = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + for id in [out, p] { + let params = if lock { json!({"id": id.0, "locked": true}) } else { json!({"id": id.0, "visible": false}) }; + s.execute("layer.setProps", ¶ms).unwrap(); + } s.execute("object.isolate", &json!({"id": g.0})).unwrap(); sel(&mut s, &[a]); - off_in_isolation(&mut s, &["object.lock.above", "object.lock.otherLayers", "object.hide.above", "object.hide.otherLayers"]); - for id in [a, b, g, over, l2] { - assert_eq!(shown_and_locked(&s, id), (true, false), "{id:?}"); + s.execute(change, &json!({})).unwrap(); + assert!(selected(&s).is_empty()); + assert!(find_command(restore).unwrap().info(&s).enabled); + let before = history(&s).0; + assert_eq!(s.execute(restore, &json!({})).unwrap(), json!({"count": 1})); + assert_eq!(history(&s).0, before + 1); + assert_eq!(selected(&s), [a]); + let changed = |s: &Session, id| if lock { node(s, id).locked } else { !node(s, id).visible }; + assert!(!changed(&s, a) && !changed(&s, b)); + assert!(changed(&s, out) && changed(&s, p)); + let no_op = history(&s).0; + assert_eq!(s.execute(restore, &json!({})).unwrap(), json!({"count": 0})); + assert_eq!(history(&s).0, no_op); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(changed(&s, a)); + assert!(selected(&s).is_empty()); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(!changed(&s, a) && changed(&s, out) && changed(&s, p) && !changed(&s, l2)); + assert_eq!(selected(&s), [a]); +} + +/// Unlock All restores locked art inside the group after Lock Selection clears selection. +#[test] +fn unlock_all_in_group_isolation_without_selection() { + check_restore_in_group_isolation("object.lock", "object.unlockAll", true); +} + +/// Show All restores hidden art inside the group after Hide Selection clears selection. +#[test] +fn show_all_in_group_isolation_without_selection() { + check_restore_in_group_isolation("object.hide", "object.showAll", false); +} + +/// With `scope: "group"`, Unlock All and Show All in an isolated compound path inside a group +/// change only the compound path's paths, not the group's other objects or a group outside it +/// that holds a selected object. +#[test] +fn group_scope_restore_stays_inside_isolated_compound_path() { + for (restore, lock) in [("object.unlockAll", true), ("object.showAll", false)] { + let mut s = session(); + let outer = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let hole = rect(&mut s, 20.0, 20.0, 20.0, 20.0); + sel(&mut s, &[outer, hole]); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let sibling = rect(&mut s, 150.0, 0.0, 20.0, 20.0); + sel(&mut s, &[compound, sibling]); + s.execute("object.group", &json!({})).unwrap(); + let away = rect(&mut s, 300.0, 0.0, 20.0, 20.0); + let away_mate = rect(&mut s, 350.0, 0.0, 20.0, 20.0); + sel(&mut s, &[away, away_mate]); + s.execute("object.group", &json!({})).unwrap(); + for id in [hole, sibling, away_mate] { + let params = if lock { json!({"id": id.0, "locked": true}) } else { json!({"id": id.0, "visible": false}) }; + s.execute("layer.setProps", ¶ms).unwrap(); + } + s.execute("object.isolate", &json!({"id": compound.0})).unwrap(); + let changed = |s: &Session, id| if lock { node(s, id).locked } else { !node(s, id).visible }; + sel(&mut s, &[away]); + assert_eq!(s.execute(restore, &json!({"scope": "group"})).unwrap(), json!({"count": 0}), "{restore}: outside selection"); + assert!(changed(&s, away_mate) && changed(&s, hole) && changed(&s, sibling), "{restore}: outside selection"); + sel(&mut s, &[outer]); + assert_eq!(s.execute(restore, &json!({"scope": "group"})).unwrap(), json!({"count": 1}), "{restore}"); + assert!(!changed(&s, hole), "{restore}: hole"); + assert!(changed(&s, sibling) && changed(&s, away_mate), "{restore}: outside"); + assert_eq!(selected(&s), [hole], "{restore}: selection"); + } +} + +/// Lock › Selection, Hide › Selection and All Artwork Above, with the isolated group and one of +/// its members both selected, change the member. +#[test] +fn lock_and_hide_with_the_isolated_group_selected_change_its_member() { + for command in ["object.lock", "object.hide", "object.lock.above", "object.hide.above"] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 200.0, 0.0, 100.0, 100.0); + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + sel(&mut s, &[g, a]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + let before = history(&s).0; + let want = if command.ends_with(".above") { json!({"count": 1}) } else { serde_json::Value::Null }; + assert_eq!(s.execute(command, &json!({})).unwrap(), want, "{command}"); + assert_eq!(history(&s).0, before + 1, "{command}"); + let expected = if command.starts_with("object.lock") { (true, true) } else { (false, false) }; + assert_eq!(shown_and_locked(&s, a), expected, "{command}: A"); + for id in [b, g] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}"); + } + } +} + +/// Lock and Hide Unselected with the isolated group and one of its members selected change only its other members. +#[test] +fn lock_and_hide_unselected_with_the_isolated_group_selected_keep_its_member() { + for command in ["object.lock.unselected", "object.hide.unselected"] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 200.0, 0.0, 100.0, 100.0); + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + sel(&mut s, &[g, a]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + assert_eq!(s.execute(command, &json!({})).unwrap(), json!({"count": 1}), "{command}"); + let changed = if command == "object.lock.unselected" { (true, true) } else { (false, false) }; + assert_eq!(shown_and_locked(&s, b), changed, "{command}: B"); + for id in [a, g] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}"); + } + } +} + +/// Lock and Hide Unselected with the isolated layer and one of its objects selected change the layer's other objects, +/// and a selected sublayer inside the isolated layer keeps its art. +#[test] +fn lock_and_hide_unselected_with_the_isolated_layer_selected_keep_its_object() { + for command in ["object.lock.unselected", "object.hide.unselected"] { + let mut s = session(); + let layer = s.doc().unwrap().doc.layers[0].id; + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 200.0, 0.0, 100.0, 100.0); + let sub = id_of(&s.execute("layer.newSublayer", &json!({"parent": layer.0})).unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let c = rect(&mut s, 400.0, 0.0, 100.0, 100.0); + s.execute("object.isolate", &json!({"id": layer.0})).unwrap(); + let changed = if command == "object.lock.unselected" { (true, true) } else { (false, false) }; + sel(&mut s, &[layer, a]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + assert_eq!(s.execute(command, &json!({})).unwrap(), json!({"count": 2}), "{command}"); + for id in [b, c] { + assert_eq!(shown_and_locked(&s, id), changed, "{command}: {id:?}"); + } + for id in [a, sub, layer] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + sel(&mut s, &[layer, sub]); + assert_eq!(s.execute(command, &json!({})).unwrap(), json!({"count": 2}), "{command}: sublayer"); + for id in [a, b] { + assert_eq!(shown_and_locked(&s, id), changed, "{command}: sublayer, {id:?}"); + } + for id in [c, sub, layer] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: sublayer, {id:?}"); + } + } +} + +/// Pattern editing keeps Lock Selection and Unlock All available for its tile art. +#[test] +fn pattern_editing_keeps_lock_and_unlock_available() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + sel(&mut s, &[a]); + s.execute("object.pattern.make", &json!({"name": "P"})).unwrap(); + let tile = selected(&s)[0]; + assert!(find_command("object.lock").unwrap().info(&s).enabled); + s.execute("object.lock", &json!({})).unwrap(); + assert!(node(&s, tile).locked); + assert!(find_command("object.unlockAll").unwrap().info(&s).enabled); + s.execute("object.unlockAll", &json!({})).unwrap(); + assert!(!node(&s, tile).locked); + assert_eq!(selected(&s), [tile]); +} + +/// Opacity mask editing lets Lock and Hide Selection change mask art and restores it with Unlock All and Show All. +#[test] +fn opacity_mask_editing_keeps_lock_hide_and_restore_available() { + let mut s = session(); + let artwork = rect(&mut s, 0.0, 0.0, 200.0, 200.0); + let mask_source = rect(&mut s, 0.0, 0.0, 100.0, 200.0); + sel(&mut s, &[artwork, mask_source]); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + s.execute("transparency.editOpacityMask", &json!({})).unwrap(); + let mask = selected(&s)[0]; + for (change, restore) in [("object.lock", "object.unlockAll"), ("object.hide", "object.showAll")] { + assert!(find_command(change).unwrap().info(&s).enabled, "{change}"); + s.execute(change, &json!({})).unwrap(); + assert!(selected(&s).is_empty(), "{change}"); + assert_eq!(shown_and_locked(&s, mask), if change == "object.lock" { (true, true) } else { (false, false) }); + assert!(find_command(restore).unwrap().info(&s).enabled, "{restore}"); + assert_eq!(s.execute(restore, &json!({})).unwrap(), json!({"count": 1}), "{restore}"); + assert_eq!(shown_and_locked(&s, mask), (true, false), "{restore}"); + assert_eq!(selected(&s), [mask], "{restore}"); + } +} + +/// Other Layers changes nothing in an isolated layer or sublayer. +#[test] +fn other_layers_has_no_target_in_isolated_layers_or_sublayers() { + for sublayer in [false, true] { + let mut s = session(); + let layer = s.doc().unwrap().doc.layers[0].id; + let root = if sublayer { id_of(&s.execute("layer.newSublayer", &json!({"parent": layer.0})).unwrap()) } else { layer }; + s.execute("layer.setCurrent", &json!({"id": root.0})).unwrap(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let other = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap()); + s.execute("object.isolate", &json!({"id": root.0})).unwrap(); + sel(&mut s, &[a]); + for command in ["object.lock.otherLayers", "object.hide.otherLayers"] { + assert!(find_command(command).unwrap().info(&s).enabled); + let before = history(&s).0; + assert_eq!(s.execute(command, &json!({})).unwrap(), json!({"count": 0})); + assert_eq!(history(&s).0, before); + assert_eq!(selected(&s), [a]); + assert_eq!(shown_and_locked(&s, other), (true, false)); + } } - s.execute("object.exitIsolation", &json!({})).unwrap(); - sel(&mut s, &[g]); - assert_eq!(s.execute("object.lock.above", &json!({})).unwrap(), json!({"count": 1})); - s.execute("object.hide.otherLayers", &json!({})).unwrap(); - assert_eq!(shown_and_locked(&s, over), (true, true)); - assert_eq!(shown_and_locked(&s, l2), (false, false)); } /// How many steps there are to undo and to redo, and whether the document has unsaved changes. @@ -580,12 +790,10 @@ fn hide_unselected_artwork_leaves_the_art_on_a_locked_artboard() { assert_eq!([a, b, on_locked].map(|id| node(&s, id).visible), [true, false, true]); } -/// In isolation mode Hide › Unselected Artwork is disabled: the menu item is off, and the command returns an error that -/// names isolation mode and changes nothing. While Lock Guides is on it leaves the guides as they are. With nothing -/// left to hide it records no undo step and returns a count of 0. A compound path that holds a selected path stays as -/// it is. +/// Hide Unselected affects only isolated art, keeps locked guides, records no step for a no-op, and +/// preserves a compound path that holds the selected path. #[test] -fn hide_unselected_artwork_keeps_locked_guides_and_is_disabled_in_isolation_mode() { +fn hide_unselected_artwork_keeps_locked_guides_and_scopes_isolation() { let mut s = session(); let guide = rect(&mut s, 0.0, 0.0, 10.0, 10.0); sel(&mut s, &[guide]); @@ -600,17 +808,15 @@ fn hide_unselected_artwork_keeps_locked_guides_and_is_disabled_in_isolation_mode let shown = |s: &Session, ids: &[NodeId]| ids.iter().map(|id| node(s, *id).visible).collect::<Vec<_>>(); s.execute("object.isolate", &json!({"id": g.0})).unwrap(); select_with_a_step_to_redo(&mut s, &[m]); - let before = history(&s); - let info = find_command("object.hide.unselected").unwrap().info(&s); - assert!(!info.enabled && info.disabled_reason.as_deref() == Some("exit isolation mode first"), "{info:?}"); - let e = s.execute("object.hide.unselected", &json!({})).unwrap_err(); - assert!(matches!(e, EngineError::Disabled(..)) && e.to_string().contains("isolation mode"), "{e}"); - assert_eq!(shown(&s, &[m, n, out, guide]), [true; 4]); - assert_eq!((history(&s), selected(&s)), (before, vec![m])); + let before = history(&s).0; + assert!(find_command("object.hide.unselected").unwrap().info(&s).enabled); + assert_eq!(hide(&mut s), json!({"count": 1})); + assert_eq!(history(&s).0, before + 1); + assert_eq!(shown(&s, &[m, n, out, guide]), [true, false, true, true]); + assert_eq!(selected(&s), [m]); s.execute("object.exitIsolation", &json!({})).unwrap(); sel(&mut s, &[m]); - assert!(find_command("object.hide.unselected").unwrap().info(&s).enabled); - assert_eq!(hide(&mut s), json!({"count": 2})); + assert_eq!(hide(&mut s), json!({"count": 1})); assert_eq!(shown(&s, &[n, out, guide]), [false, false, true]); select_with_a_step_to_redo(&mut s, &[m]); let before = history(&s); @@ -621,7 +827,7 @@ fn hide_unselected_artwork_keeps_locked_guides_and_is_disabled_in_isolation_mode sel(&mut s, &[m]); assert_eq!(hide(&mut s), json!({"count": 1})); assert_eq!(shown(&s, &[guide]), [false]); - // A compound path that holds the selected path stays as it is with its paths. + // The compound path and its paths stay visible when one path is selected. let outer = rect(&mut s, 0.0, 200.0, 100.0, 100.0); let hole = rect(&mut s, 40.0, 240.0, 20.0, 20.0); sel(&mut s, &[outer, hole]); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 17b05d72ee..b323306af7 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6971,10 +6971,10 @@ fn the_task_bar_recolors_coloured_art() { assert!(app.ui.dialog.is_none(), "no Recolor button without colours"); } -/// The Contextual Task Bar's Lock button is off in isolation mode, as Object › Lock › Selection -/// is: a click locks nothing and shows no error. Outside isolation mode it locks the selection. +/// The Contextual Task Bar's Lock button locks the selected member in isolation mode and the +/// selected group outside isolation mode. #[test] -fn the_task_bar_lock_button_is_off_in_isolation_mode() { +fn the_task_bar_lock_button_locks_selected_art_in_isolation_mode() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); // Plain paths: a basic shape shows its properties in Lock's place. @@ -6983,6 +6983,9 @@ fn the_task_bar_lock_button_is_off_in_isolation_mode() { let a = app.session.execute("path.create", &square(150.0)).unwrap()["id"].clone(); let b = app.session.execute("path.create", &square(210.0)).unwrap()["id"].clone(); app.session.execute("select.set", &json!({"ids": [a.clone(), b]})).unwrap(); + let a = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 130, "width": 40, "height": 40})).unwrap()["id"].clone(); + let b = app.session.execute("shape.rectangle", &json!({"x": 210, "y": 130, "width": 40, "height": 40})).unwrap()["id"].clone(); + app.session.execute("select.set", &json!({"ids": [a.clone(), b.clone()]})).unwrap(); let g = app.session.execute("object.group", &json!({})).unwrap()["id"].clone(); app.select_tool("selection"); let ctx = egui::Context::default(); @@ -7003,7 +7006,8 @@ fn the_task_bar_lock_button_is_off_in_isolation_mode() { app.session.execute("object.isolate", &json!({"id": g.clone()})).unwrap(); app.session.execute("select.set", &json!({"ids": [a.clone()]})).unwrap(); click_lock(&mut app); - assert!(!locked(&app, &a), "nothing is locked in isolation mode"); + assert!(locked(&app, &a), "the selected member is locked in isolation mode"); + assert!(!locked(&app, &b), "the other member stays unlocked"); assert_eq!(app.ui.status, "", "no error"); app.session.execute("object.exitIsolation", &json!({})).unwrap(); app.session.execute("select.set", &json!({"ids": [g.clone()]})).unwrap(); diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index b0ee269ad3..17a8864c10 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -669,10 +669,9 @@ fn expand_appearance_is_an_object_menu_item_only() { assert_eq!(paths, [vec!["Object".to_string()]]); } -/// In isolation mode, every item of Object › Lock and Object › Hide, Unlock All and Show All are -/// greyed out, while Group stays on. After Exit Isolation Mode they are on again. +/// Isolation keeps the Lock and Hide actions available for selected members. #[test] -fn lock_and_hide_menus_are_greyed_out_in_isolation_mode() { +fn lock_and_hide_menus_are_enabled_in_isolation_mode() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({})).unwrap(); let a = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].clone(); @@ -715,8 +714,11 @@ fn lock_and_hide_menus_are_greyed_out_in_isolation_mode() { }; app.run("object.isolate", json!({"id": g.clone()})).unwrap(); app.run("select.set", json!({"ids": [b]})).unwrap(); - assert_eq!(shown(&app), [false, false, false, false, false, false, false, false, false, true], "in isolation mode"); + assert_eq!(shown(&app), [true; 10], "in isolation mode"); assert!(lock_unselected(&app), "shortcut command remains enabled in isolation"); + assert!(crate::menus::enabled(&app, "object.hide.unselected"), "Hide Unselected remains enabled in isolation"); + let chord = crate::shortcut_editor::default_of("object.hide.unselected").expect("default Hide Unselected shortcut"); + assert_eq!(crate::shortcut_editor::normalize(chord), crate::shortcut_editor::normalize("Cmd+Alt+Shift+3")); app.run("object.exitIsolation", json!({})).unwrap(); app.run("select.set", json!({"ids": [g]})).unwrap(); assert_eq!(shown(&app), [true; 10], "after Exit Isolation Mode"); diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 0bd879a318..49acb3e8af 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1286,25 +1286,28 @@ fn blend_options_is_a_quick_action_for_one_blend() { assert!(!shows(&tall(&mut app, &ctx, vec![]), "Blend Options"), "a rectangle"); } -/// Quick Actions have no Lock in isolation mode, where Object › Lock › Selection is off. Outside -/// isolation mode Lock is there and locks the selection. +/// Quick Actions offer Lock for a selected member in isolation and for a selected group outside it. #[test] -fn lock_is_a_quick_action_outside_isolation_mode_only() { +fn lock_is_a_quick_action_in_and_outside_isolation_mode() { let mut app = new_app(); let (a, b) = (rect(&mut app, 20.0, 20.0, 40.0, 40.0), rect(&mut app, 200.0, 20.0, 40.0, 40.0)); app.run("select.set", json!({"ids": [a.clone(), b]})).unwrap(); let g = app.run("object.group", json!({})).unwrap()["id"].clone(); app.run("object.isolate", json!({"id": g.clone()})).unwrap(); - app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("select.set", json!({"ids": [a.clone()]})).unwrap(); let ctx = egui::Context::default(); let texts = tall(&mut app, &ctx, vec![]); - assert!(shows(&texts, "Offset Path") && !shows(&texts, "Lock"), "no Lock in isolation mode: {texts:?}"); + assert!(shows(&texts, "Offset Path") && shows(&texts, "Lock"), "Lock in isolation mode: {texts:?}"); + press(&mut app, &ctx, text_at(&texts, "Lock").center()); + let locked = |app: &VectorcraftApp, id: &serde_json::Value| { + app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().locked + }; + assert!(locked(&app, &a)); app.run("object.exitIsolation", json!({})).unwrap(); app.run("select.set", json!({"ids": [g.clone()]})).unwrap(); let texts = tall(&mut app, &ctx, vec![]); press(&mut app, &ctx, text_at(&texts, "Lock").center()); - let locked = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(g.as_u64().unwrap())).unwrap().locked; - assert!(locked, "Lock locks the group"); + assert!(locked(&app, &g), "Lock locks the group"); } /// A Live Paint group selected with a path has Merge Live Paint in Quick Actions, which adds diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 38365f5ed1..ad71fb3977 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -264,7 +264,7 @@ fn cmd_shift_o_creates_outlines() { /// Cmd+Alt+Shift+3 is Object › Hide › Unselected Artwork: it hides the object that is not /// selected. Cmd+Alt+3 still shows all, and Cmd+3 still hides the selection. In isolation mode -/// the item is disabled. +/// the shortcut hides unselected members of the isolated group. #[test] fn cmd_alt_shift_3_hides_unselected_artwork() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); @@ -285,15 +285,15 @@ fn cmd_alt_shift_3_hides_unselected_artwork() { app.session.execute("select.set", &json!({"ids": [a.0]})).unwrap(); frame(&mut app, vec![three(Modifiers::COMMAND)]); assert_eq!(shown(&app), [false, true], "Cmd+3 hides the selection"); - // In isolation mode the menu item is off, and the shortcut hides nothing. + // In isolation mode the shortcut hides only the group's unselected member. app.session.execute("object.showAll", &json!({})).unwrap(); app.session.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); let g = app.session.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); app.session.execute("object.isolate", &json!({"id": g})).unwrap(); app.session.execute("select.set", &json!({"ids": [a.0]})).unwrap(); - assert!(!crate::menus::enabled(&app, "object.hide.unselected")); + assert!(crate::menus::enabled(&app, "object.hide.unselected")); frame(&mut app, vec![three(Modifiers::COMMAND | Modifiers::ALT | Modifiers::SHIFT)]); - assert_eq!(shown(&app), [true, true], "nothing is hidden in isolation mode"); + assert_eq!(shown(&app), [true, false], "the unselected member is hidden in isolation mode"); } /// Cmd+Alt+Shift+J opens Average & Join's dialog, Points: Corner the first time. Cancel changes diff --git a/docs/mcp.md b/docs/mcp.md index d4898b5170..6f342c98cd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1380,7 +1380,8 @@ them again with the key object. When the call changes nothing, it records no und Other `object.setProps` calls leave the selection unchanged. `object.unlockAll` and `object.showAll` unlock or show every locked or hidden object in the document and select -them → `{count}`. With `scope: "group"` they take only the objects inside the groups that hold the selected objects: +them → `{count}`. In isolation mode they take only the objects inside the isolated object. With `scope: "group"` they +take only the objects inside the groups that hold the selected objects: for each selected object, the group nearest above it, or the object itself when it is a group. The objects of a group inside another such group are counted once. With no selected object in a group, the call returns the error "nothing selected is in a group" and changes nothing. `scope: "document"` is the default, and any other value is @@ -1397,16 +1398,15 @@ object that `select.all` takes and that is neither selected nor holds a selected group that holds a selected object it hides the group's other members one by one; a clip group, a compound path or another object that holds a selected object stays as it is with its members. The objects of a selected layer count as selected. While Lock Guides is on, the guide paths count as selected and stay as they are. The selection stays as it is, and `object.showAll` shows the objects again. With nothing to -hide it records no undo step. In isolation mode the menu item is disabled, and the command returns the error "exit -isolation mode first" and changes nothing. +hide it records no undo step. In isolation mode it hides only unselected objects inside the isolated object. `object.lock.unselected` (Cmd+Alt+Shift+2; shortcut and command, with no Object › Lock menu item) locks unselected artwork in one undo step and returns `{count}`. In a partly selected group, clipping group, or compound path, it locks the unselected members and leaves the container and selected members unlocked. It includes unselected guides even while Lock Guides is on. Hidden art and art on locked layers stay individually unlocked; a selected layer's artwork counts as selected. In ordinary isolation mode it locks only unselected art inside the isolated object. The selection -stays as it is. `object.unlockAll` unlocks and selects all locked artwork in the document, including art locked before -this command. With nothing to lock it records no undo step. +stays as it is. `object.unlockAll` unlocks and selects all locked artwork in the document, or inside the isolated +object in isolation mode, including art locked before this command. With nothing to lock it records no undo step. These Select menu commands select only the objects that `select.all` selects and the objects inside them: every `select.same.*` and `select.object.*` command except `select.object.slices`, `select.nextAbove`, `select.nextBelow` @@ -2334,11 +2334,14 @@ and `layerRows`, the rows highlighted in the panel. opens no rows for it and scrolls as with the option off. A change made with the panel's own rows, buttons or menu is not located, and a change made during a drag is located when the drag ends. A document opens with only its top-level layers open; the open rows are saved in the native file and reopen that way. -- **Lock and Hide in isolation mode**: in isolation mode, Object › Lock's and Object › Hide's items (`object.lock`, - `object.lock.above`, `object.lock.otherLayers`, `object.hide`, `object.hide.above`, `object.hide.otherLayers`), - `object.unlockAll` and `object.showAll` are off, and a call returns the error "command `object.hide` is not - available right now: exit isolation mode first", with the command's own id. Pattern editing mode and opacity mask - editing do not count as isolation mode for these commands. +- **Lock and Hide in isolation mode**: Object › Lock's and Object › Hide's items (`object.lock`, `object.lock.above`, + `object.lock.otherLayers`, `object.lock.unselected`, `object.hide`, `object.hide.above`, `object.hide.otherLayers`, + `object.hide.unselected`) are on while an object inside the isolated object is selected, and they change only objects + inside it. All Artwork Above locks or hides the selected objects as well as the objects above them that overlap them. + Other Layers changes nothing in an isolated group, layer or sublayer, returns a count of 0 and records no undo step. + `object.unlockAll` and `object.showAll` are on with nothing selected, and they unlock or show and select only the + objects inside the isolated object. Pattern editing mode and opacity mask editing do not count as isolation mode for + these commands. - **Search and filter** (control channel and the app's MCP): the Search All field keeps the rows whose names hold the text typed, and `ui.layersFilter {objects?, layers?}` sets the choices of the Filter button beside it. `objects` (By Object) takes `paths` (paths and compound paths), `shapes` (live rectangles, ellipses, polygons and lines), `text`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e950d73e70..05985f9f18 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -986,9 +986,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Colour, type and file workflows:** Recolor Artwork (dialog with harmonies), Edit Colors, Find & Replace, Change Case, Smart Punctuation, Guides, Lock/Hide Above, Transform Each, Rasterize. The Libraries panel holds gradients and patterns: its + button adds the selection's fill or stroke gradient or pattern, a gradient or pattern swatch dragged from the Swatches panel is added, and a click paints the selection through the active Fill/Stroke proxy, a pattern bringing its definition and swatch into the document. Object › Lock › All Artwork Above and Object › Hide › All Artwork Above deselect the selected objects they lock or hide, the key object included. - Object › Hide › Unselected Artwork (Cmd/Ctrl+Alt+Shift+3, `object.hide.unselected`) hides, in one undo step, every object Select All takes that is not selected and holds no selected object; the members of a group that holds a selected object are hidden one by one, and Object › Show All shows them again. It is disabled in isolation mode. Public references: [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Hide unselected artwork"; [How to lock, hide, and delete objects in Illustrator](https://web.archive.org/web/20220303070637/https://helpx.adobe.com/illustrator/using/locking-hiding-deleting-objects.html), which says the Show All and Hide menus are unavailable in isolation mode. - Cmd/Ctrl+Alt+Shift+2 (`object.lock.unselected`) locks unselected artwork in one undo step and has no Object › Lock menu item. It locks unselected members of partly selected groups, clipping groups and compound paths, and unselected guides while Lock Guides is on. In ordinary isolation mode it locks only unselected art inside the isolated object. Object › Unlock All unlocks all locked art in the document. The [public shortcut page](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) calls the action "Lock all deselected artwork". - In isolation mode, the visible items of Object › Lock and Object › Hide, Unlock All and Show All are greyed out ([lock, hide, and delete objects](https://web.archive.org/web/20220303070637/https://helpx.adobe.com/illustrator/using/locking-hiding-deleting-objects.html)); the shortcut-only `object.lock.unselected` command remains enabled with a selection. The Contextual Task Bar's Lock button is greyed out too, the Properties panel's Quick Actions have no Lock, and the other Lock and Hide commands return an error. Pattern editing mode and opacity mask editing do not count as isolation mode for them. + Object › Hide › Unselected Artwork (Cmd/Ctrl+Alt+Shift+3, `object.hide.unselected`) hides, in one undo step, every object Select All takes that is not selected and holds no selected object; the members of a group that holds a selected object are hidden one by one, and Object › Show All shows them again. In isolation mode it hides only unselected objects inside the isolated object. Public reference: [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Hide unselected artwork". + Cmd/Ctrl+Alt+Shift+2 (`object.lock.unselected`) locks unselected artwork in one undo step and has no Object › Lock menu item. It locks unselected members of partly selected groups, clipping groups and compound paths, and unselected guides while Lock Guides is on. In ordinary isolation mode it locks only unselected art inside the isolated object. Object › Unlock All unlocks all locked art in the document, or inside the isolated object in isolation mode. The [public shortcut page](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) calls the action "Lock all deselected artwork". + In isolation mode, the items of Object › Lock and Object › Hide are on while an object inside the isolated object is selected, and they change only objects inside it: All Artwork Above locks or hides the selected objects and the objects above them that overlap them, and Other Layers changes nothing in an isolated group, layer or sublayer. Unlock All and Show All are on with nothing selected and unlock or show and select only the objects inside the isolated object. The Contextual Task Bar's Lock button and the Properties panel's Quick Actions Lock lock the selected object. Pattern editing mode and opacity mask editing do not count as isolation mode for them. Liquify (its brush Width, Height and Angle, Intensity, Detail, Simplify, Twirl Rate, Complexity, Horizontal and Vertical), Puppet Warp (its Expand and each pin's angle), Transform in Perspective (its depth), Nudge in Perspective (its direction) and Move Plane (its location or distance) refuse a value other than a number or null, such as "40", Draw in Perspective refuses a click point that is not two numbers, and Width Profile refuses a point that is not three numbers; each leaves the document and its undo history as they were. Object › Lock › All Artwork Above and Object › Hide › All Artwork Above go through each top-level layer once, checking each object that is not selected against the selected objects below it: with 100 tiles selected under 25,000 rectangles, Lock took 6.4 s and now takes under 0.1 s, and with all of 5,001 objects selected it took 8.8 s and now takes under 0.1 s. Object › Unlock All and Object › Show All clicked in the in-window menu bar with Shift+Alt (Shift+Option) held unlock or show only the objects inside the groups that hold the selected objects ([lock, hide, and delete objects](https://web.archive.org/web/20230623025912/https://helpx.adobe.com/illustrator/using/locking-hiding-deleting-objects.html)); `object.unlockAll` and `object.showAll` take `scope: "group"` for it. From 9badc6bae7bc1dd483c7971b48d4305108eb09af Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 01:21:53 +0700 Subject: [PATCH 123/260] i18n: one row per catalog entry after #4860 --- crates/ui-egui/src/i18n/nl.tsv | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 01d80c460f..7fb221d3ed 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2858,7 +2858,6 @@ theme Appearance Vormgeving Yes Ja No Nee Duplicate Brush Kwast dupliceren - Duplicate Brush Penseel dupliceren Duplicate Symbol Symbool dupliceren Edit Symbol Symbool bewerken Expand Brush Strokes Penseelstreken omzetten From f1a6a9ff67f7b34bab378b351a6d504380efa4d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 03:34:44 -0700 Subject: [PATCH 124/260] Contextual Task Bar: the Shape Properties popup stays open for its Corner dropdown Opening a polygon's Corner dropdown closed the Shape Properties popup, so no corner type could be picked from it. The popup now uses widgets::popover, which keeps it open while its dropdowns are open. --- crates/ui-egui/src/canvas/task_bar.rs | 5 +++-- crates/ui-egui/src/tests/taskbar.rs | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index cf40955ee6..73a6334866 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -267,9 +267,10 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { if let Some(shape) = &shape && let NodeKind::Path { live: Some(live), .. } = &shape.kind { - // The shape's properties in a popup that stays open while its fields are edited. + // The shape's properties in a popover that stays open while its fields and + // its Corner dropdown are used. let props = widgets::icon_button(ui, "shapes", tl!("Shape Properties"), false, 30.0); - egui::Popup::menu(&props).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + widgets::popover(&props, props.clicked(), |ui| { ui.set_min_width(250.0); crate::panels::transform::live_shape_rows(app, ui, shape, live, "task-bar-shape", true); }); diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 2cc79e6daa..7a6bd26168 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -323,6 +323,27 @@ fn the_shape_properties_popup_edits_the_shape() { assert_eq!(sides(&app), 6); } +/// The popup stays open while a polygon's Corner dropdown is open, so a corner type can be picked +/// from it. +#[test] +fn the_shape_properties_popup_keeps_its_corner_dropdown() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let polygon = id(app.run("shape.polygon", json!({"cx": 100, "cy": 100, "radius": 40, "sides": 6})).unwrap()); + select(&mut app, &[polygon]); + let (ctx, texts) = click_lock_slot(&mut app); + let click = |app: &mut VectorcraftApp, p: Pos2| { + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, &ctx, vec![Event::PointerMoved(p), press(true), press(false)]); + frame(app, &ctx, vec![]) + }; + let texts = click(&mut app, at(&texts, "Round")); + assert!(has(&texts, "Polygon Properties:") && has(&texts, "Chamfer"), "the popup and its dropdown: {texts:?}"); + click(&mut app, at(&texts, "Chamfer")); + let vectorcraft_doc::LiveShape::Polygon { kinds, .. } = live(&app, polygon) else { panic!("not a polygon") }; + assert!(!kinds.is_empty() && kinds.iter().all(|k| *k == vectorcraft_geom::shapes::CornerKind::Chamfer), "{kinds:?}"); +} + /// Every other selection keeps Lock: a plain closed path, a star (a plain path), a path with live /// corners, a group and several objects. The Direct Selection tool keeps it for a basic shape. #[test] From 19b4fc8d437fa273f6e203be46f0841bd764527a Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 00:53:01 +0700 Subject: [PATCH 125/260] Canvas tests: the isolation-mode Lock test uses plain paths, as the task bar shows Lock for them --- crates/ui-egui/src/canvas/tests.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index b323306af7..f7361da0ca 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6982,9 +6982,6 @@ fn the_task_bar_lock_button_locks_selected_art_in_isolation_mode() { |x: f64| json!({"anchors": [{"x": x, "y": 130}, {"x": x + 40.0, "y": 130}, {"x": x + 40.0, "y": 170}, {"x": x, "y": 170}], "closed": true}); let a = app.session.execute("path.create", &square(150.0)).unwrap()["id"].clone(); let b = app.session.execute("path.create", &square(210.0)).unwrap()["id"].clone(); - app.session.execute("select.set", &json!({"ids": [a.clone(), b]})).unwrap(); - let a = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 130, "width": 40, "height": 40})).unwrap()["id"].clone(); - let b = app.session.execute("shape.rectangle", &json!({"x": 210, "y": 130, "width": 40, "height": 40})).unwrap()["id"].clone(); app.session.execute("select.set", &json!({"ids": [a.clone(), b.clone()]})).unwrap(); let g = app.session.execute("object.group", &json!({})).unwrap()["id"].clone(); app.select_tool("selection"); From 49290fa8e6bd32b1f841718a28e73a7f2b6ebdd1 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 06:32:34 -0700 Subject: [PATCH 126/260] Brushes: Delete Brush asks first, and Alt-click deletes without asking The Brushes panel's Delete Brush button and its panel menu item now ask before deleting the selected brushes, as Swatches and Graphic Styles do. OK deletes them in one undo step and strokes that used them become plain strokes; Cancel leaves the document unchanged. Alt-click (Option-click on macOS) on the button deletes without asking. The brush.delete command still deletes at once. --- crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/panels/brushes.rs | 21 +++++- crates/ui-egui/src/panels/brushes/tests.rs | 83 ++++++++++++++++++++-- docs/target-app-parity.md | 1 + 28 files changed, 171 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index dabb1c8e9a..702fb78d2b 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -742,6 +742,9 @@ font-technology Variable Променливи Yes Да No Не Delete Tab Изтриване на табулация + Delete the brush “{name}”? Да се изтрие четката „{name}“? + Delete these {count} brushes? Да се изтрият тези {count} четки? + Strokes using deleted brushes become plain strokes. Щрихите, които използват изтритите четки, стават обикновени щрихи. Delete the graphic style “{name}”? Изтриване на графичния стил „{name}“? Delete Theme Изтриване на тема Delete theme Изтриване на тема diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 59984a5192..4269d2b7e7 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1059,6 +1059,9 @@ Yes Sí No No Delete Tab Suprimeix la tabulació + Delete the brush “{name}”? Voleu suprimir el pinzell “{name}”? + Delete these {count} brushes? Voleu suprimir aquests {count} pinzells? + Strokes using deleted brushes become plain strokes. Els traços que utilitzen pinzells suprimits esdevenen traços normals. Delete the graphic style “{name}”? Voleu suprimir l’estil gràfic “{name}”? Delete the library “{name}”? Voleu suprimir la biblioteca “{name}”? Delete Theme Suprimeix el tema diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 11d38443b6..39c5e2be1a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1558,6 +1558,9 @@ lighting Light Světlo Reverse Gradient Obrátit přechod Save to Swatches Uložit do vzorníku Delete Graphic Style (Alt-click: without asking) Odstranit grafický styl (Alt+kliknutí: bez dotazu) + Delete the brush “{name}”? Odstranit štětec „{name}“? + Delete these {count} brushes? Odstranit těchto {count} štětců? + Strokes using deleted brushes become plain strokes. Tahy používající odstraněné štětce se změní na běžné tahy. Delete the graphic style “{name}”? Odstranit grafický styl „{name}“? Delete these {n} graphic styles? Odstranit tyto grafické styly ({n})? Delete this {n} graphic style? Odstranit tento grafický styl ({n})? diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 1203b3d366..f7021936c3 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1472,6 +1472,9 @@ lighting Light Lys Reverse Gradient Omvend gradient Save to Swatches Gem i farveprøver Delete Graphic Style (Alt-click: without asking) Slet grafisk typografi (Alt-klik: uden at spørge) + Delete the brush “{name}”? Slet penslen »{name}«? + Delete these {count} brushes? Slet disse {count} pensler? + Strokes using deleted brushes become plain strokes. Streger, der bruger slettede pensler, bliver almindelige streger. Delete the graphic style “{name}”? Slet den grafiske typografi »{name}«? Delete these {n} graphic styles? Slet disse {n} grafiske typografier? Delete this {n} graphic style? Slet denne {n} grafiske typografi? diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index e832311b06..dc9c67f8bb 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -736,6 +736,9 @@ font-technology Variable Variabel Yes Ja No Nein Delete Tab Tabulator löschen + Delete the brush “{name}”? Pinsel „{name}“ löschen? + Delete these {count} brushes? Diese {count} Pinsel löschen? + Strokes using deleted brushes become plain strokes. Konturen mit gelöschten Pinseln werden zu einfachen Konturen. Delete the graphic style “{name}”? Grafikstil „{name}“ löschen? Delete Theme Thema löschen Delete theme Thema löschen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 90709397af..150002aa42 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -716,6 +716,9 @@ font-technology Variable Μεταβλητές Yes Ναι No Όχι Delete Tab Διαγραφή στηλοθέτη + Delete the brush “{name}”? Να διαγραφεί το πινέλο «{name}»; + Delete these {count} brushes? Να διαγραφούν αυτά τα {count} πινέλα; + Strokes using deleted brushes become plain strokes. Οι πινελιές που χρησιμοποιούν διαγραμμένα πινέλα γίνονται απλές πινελιές. Delete the graphic style “{name}”? Να διαγραφεί το στυλ γραφικών «{name}»; Delete Theme Διαγραφή θέματος Delete theme Διαγραφή θέματος diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f90a4b0471..2bbb317024 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -757,6 +757,9 @@ font-technology Variable Variables Yes Sí No No Delete Tab Eliminar tabulación + Delete the brush “{name}”? ¿Eliminar el pincel “{name}”? + Delete these {count} brushes? ¿Eliminar estos {count} pinceles? + Strokes using deleted brushes become plain strokes. Los trazos que usan pinceles eliminados se convierten en trazos simples. Delete the graphic style “{name}”? ¿Eliminar el estilo gráfico “{name}”? Delete Theme Eliminar tema Delete theme Eliminar tema diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 8c4bc1fc10..1a276e0e71 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1532,6 +1532,9 @@ lighting Light Valo Reverse Gradient Käännä liukuväri Save to Swatches Tallenna värimalleihin Delete Graphic Style (Alt-click: without asking) Poista grafiikkatyyli (Alt-napsautus: kysymättä) + Delete the brush “{name}”? Poistetaanko sivellin ”{name}”? + Delete these {count} brushes? Poistetaanko nämä {count} sivellintä? + Strokes using deleted brushes become plain strokes. Poistettuja siveltimiä käyttävät viivat muuttuvat tavallisiksi viivoiksi. Delete the graphic style “{name}”? Poistetaanko grafiikkatyyli ”{name}”? Delete these {n} graphic styles? Poistetaanko nämä {n} grafiikkatyyliä? Delete this {n} graphic style? Poistetaanko tämä {n} grafiikkatyyli? diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 7db8ee535a..68a78da7dd 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -759,6 +759,9 @@ font-technology Variable Variables Yes Oui No Non Delete Tab Supprimer la tabulation + Delete the brush “{name}”? Supprimer la forme « {name} » ? + Delete these {count} brushes? Supprimer ces {count} formes ? + Strokes using deleted brushes become plain strokes. Les contours utilisant des formes supprimées deviennent des contours simples. Delete the graphic style “{name}”? Supprimer le style graphique « {name} » ? Delete Theme Supprimer le thème Delete theme Supprimer le thème diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0aceab5ab4..322770fb87 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -981,6 +981,9 @@ font-technology Variable Változó Yes Igen No Nem Delete Tab Tabulátor törlése + Delete the brush “{name}”? Törlöd ezt az ecsetet: „{name}”? + Delete these {count} brushes? Törlöd ezt a {count} ecsetet? + Strokes using deleted brushes become plain strokes. A törölt ecseteket használó körvonalak egyszerű körvonalakká válnak. Delete the graphic style “{name}”? Törlöd ezt a grafikai stílust: „{name}”? Delete the library “{name}”? Törlöd ezt a könyvtárat: „{name}”? Delete Theme Téma törlése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 95a3036337..25ee0213a1 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1472,6 +1472,9 @@ lighting Light Cahaya Reverse Gradient Balikkan gradien Save to Swatches Simpan ke swatch Delete Graphic Style (Alt-click: without asking) Hapus gaya grafis (Alt+klik: tanpa konfirmasi) + Delete the brush “{name}”? Hapus kuas “{name}”? + Delete these {count} brushes? Hapus {count} kuas ini? + Strokes using deleted brushes become plain strokes. Goresan yang menggunakan kuas terhapus menjadi goresan biasa. Delete the graphic style “{name}”? Hapus gaya grafis “{name}”? Delete these {n} graphic styles? Hapus {n} gaya grafis ini? Delete this {n} graphic style? Hapus {n} gaya grafis ini? diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index a9c16d3ba9..7685ad98a5 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -757,6 +757,9 @@ font-technology Variable Variabili Yes Sì No No Delete Tab Elimina tabulazione + Delete the brush “{name}”? Eliminare il pennello “{name}”? + Delete these {count} brushes? Eliminare questi {count} pennelli? + Strokes using deleted brushes become plain strokes. I tracciati che usano pennelli eliminati diventano tracciati semplici. Delete the graphic style “{name}”? Eliminare lo stile grafico “{name}”? Delete Theme Elimina tema Delete theme Elimina tema diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 01c25917b9..99376a0f11 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1308,6 +1308,9 @@ font-technology Variable バリアブル Delete Transparency Flattener Preset 透明の分割・統合プリセットを削除 Delete Width Point 幅ポイントを削除 Delete Workspace ワークスペースを削除 + Delete the brush “{name}”? ブラシ「{name}」を削除しますか? + Delete these {count} brushes? これら {count} 個のブラシを削除しますか? + Strokes using deleted brushes become plain strokes. 削除したブラシを使用する線は通常の線になります。 Delete the graphic style “{name}”? グラフィックスタイル「{name}」を削除しますか? Delete theme テーマを削除 Delete this saved preset この保存済みプリセットを削除 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index e0e1a10953..b55b3f2c95 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1389,6 +1389,9 @@ lighting Light სინათლე Reverse Gradient გრადიენტის შებრუნება Save to Swatches ფერის ნიმუშებში შენახვა Delete Graphic Style (Alt-click: without asking) გრაფიკული სტილის წაშლა (Alt-დაწკაპუნებით: დაუკითხავად) + Delete the brush “{name}”? წაიშალოს ფუნჯი „{name}“? + Delete these {count} brushes? წაიშალოს ეს {count} ფუნჯი? + Strokes using deleted brushes become plain strokes. წაშლილი ფუნჯებით დახატული შტრიხები ჩვეულებრივ შტრიხებად იქცევა. Delete the graphic style “{name}”? წაიშალოს გრაფიკული სტილი „{name}“? Delete these {n} graphic styles? წაიშალოს ეს გრაფიკული სტილები ({n})? Delete this {n} graphic style? წაიშალოს ეს გრაფიკული სტილი ({n})? diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 45ce73252c..e5dee07ee1 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1299,6 +1299,9 @@ font-technology Variable 가변 Delete Transparency Flattener Preset 투명도 병합 프리셋 삭제 Delete Width Point 너비 포인트 삭제 Delete Workspace 작업 영역 삭제 + Delete the brush “{name}”? 브러시 “{name}”을(를) 삭제하시겠습니까? + Delete these {count} brushes? 이 브러시 {count}개를 삭제하시겠습니까? + Strokes using deleted brushes become plain strokes. 삭제된 브러시를 사용한 선은 일반 선이 됩니다. Delete the graphic style “{name}”? 그래픽 스타일 “{name}”을(를) 삭제하시겠습니까? Delete theme 테마 삭제 Delete this saved preset 저장된 이 프리셋 삭제 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index e4cca253f8..bbee0d063b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1486,6 +1486,9 @@ lighting Light Licht Reverse Gradient Verloop omkeren Save to Swatches Opslaan in stalen Delete Graphic Style (Alt-click: without asking) Grafische stijl verwijderen (Alt-klik: zonder vragen) + Delete the brush “{name}”? Kwast „{name}” verwijderen? + Delete these {count} brushes? Deze {count} kwasten verwijderen? + Strokes using deleted brushes become plain strokes. Lijnen die verwijderde kwasten gebruiken, worden gewone lijnen. Delete the graphic style “{name}”? De grafische stijl „{name}” verwijderen? Delete these {n} graphic styles? Deze {n} grafische stijlen verwijderen? Delete this {n} graphic style? Deze {n} grafische stijl verwijderen? diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 027f7198e2..95d62b9a05 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1472,6 +1472,9 @@ lighting Light Światło Reverse Gradient Odwróć gradient Save to Swatches Zapisz w próbkach Delete Graphic Style (Alt-click: without asking) Usuń styl graficzny (kliknięcie z Alt: bez pytania) + Delete the brush “{name}”? Usunąć pędzel „{name}”? + Delete these {count} brushes? Usunąć te {count} pędzle? + Strokes using deleted brushes become plain strokes. Obrysy używające usuniętych pędzli stają się zwykłymi obrysami. Delete the graphic style “{name}”? Usunąć styl graficzny „{name}”? Delete these {n} graphic styles? Usunąć te style graficzne ({n})? Delete this {n} graphic style? Usunąć ten styl graficzny ({n})? diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e9ee07994f..7f4d8287a3 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -674,6 +674,9 @@ Delete Transparency Flattener Preset Excluir Predefinido de Achatamento de Transparência Delete Width Point Excluir Ponto de Largura Delete Workspace Excluir Espaço de Trabalho + Delete the brush “{name}”? Excluir o pincel “{name}”? + Delete these {count} brushes? Excluir estes {count} pincéis? + Strokes using deleted brushes become plain strokes. Traços que usam pincéis excluídos tornam-se traços simples. Delete the graphic style “{name}”? Excluir o estilo gráfico “{name}”? Delete theme Excluir tema Delete this saved preset Excluir este predefinido salvo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index dea1bee849..583a3f09a7 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -755,6 +755,9 @@ font-technology Variable Вариативные Yes Да No Нет Delete Tab Удалить табуляцию + Delete the brush “{name}”? Удалить кисть «{name}»? + Delete these {count} brushes? Удалить эти кисти ({count})? + Strokes using deleted brushes become plain strokes. Обводки, использующие удалённые кисти, становятся обычными обводками. Delete the graphic style “{name}”? Удалить графический стиль «{name}»? Delete Theme Удалить тему Delete theme Удалить тему diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index fcd0427a77..1b68826627 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -744,6 +744,9 @@ font-technology Variable Variabla Yes Ja No Nej Delete Tab Radera tabb + Delete the brush “{name}”? Radera penseln ”{name}”? + Delete these {count} brushes? Radera dessa {count} penslar? + Strokes using deleted brushes become plain strokes. Linjer som använder borttagna penslar blir vanliga linjer. Delete the graphic style “{name}”? Radera grafikstilen ”{name}”? Delete Theme Radera tema Delete theme Radera tema diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7a1ea36471..d318f8a75d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -736,6 +736,9 @@ font-technology Variable Değişken Yes Evet No Hayır Delete Tab Sekmeyi Sil + Delete the brush “{name}”? “{name}” fırçası silinsin mi? + Delete these {count} brushes? Bu {count} fırça silinsin mi? + Strokes using deleted brushes become plain strokes. Silinen fırçaları kullanan konturlar düz konturlara dönüşür. Delete the graphic style “{name}”? “{name}” grafik stili silinsin mi? Delete Theme Temayı Sil Delete theme Temayı sil diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 58693ddfd1..5dd9b8979c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -751,6 +751,9 @@ font-technology Variable Варіативні Yes Так No Ні Delete Tab Видалити табуляцію + Delete the brush “{name}”? Видалити пензель «{name}»? + Delete these {count} brushes? Видалити ці пензлі ({count})? + Strokes using deleted brushes become plain strokes. Обведення, що використовують видалені пензлі, стають звичайними обведеннями. Delete the graphic style “{name}”? Видалити графічний стиль «{name}»? Delete Theme Видалити тему Delete theme Видалити тему diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index aaa74d0e7c..6136b2ddd6 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -877,6 +877,9 @@ font-technology Variable Biến thiên Yes Có No Không Delete Tab Xóa tab + Delete the brush “{name}”? Xóa cọ “{name}”? + Delete these {count} brushes? Xóa {count} cọ này? + Strokes using deleted brushes become plain strokes. Các nét dùng cọ đã xóa trở thành nét thông thường. Delete the graphic style “{name}”? Xóa kiểu đồ họa “{name}”? Delete the library “{name}”? Xóa thư viện “{name}”? Delete Theme Xóa bộ màu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 71b1fead14..7fbdf119b0 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -700,6 +700,9 @@ Yes 是 No 否 Delete Tab 删除制表位 + Delete the brush “{name}”? 要删除画笔“{name}”吗? + Delete these {count} brushes? 要删除这 {count} 个画笔吗? + Strokes using deleted brushes become plain strokes. 使用已删除画笔的描边会变成普通描边。 Delete the graphic style “{name}”? 要删除图形样式“{name}”吗? Delete Theme 删除主题 Delete theme 删除主题 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a89fd28cce..3cb07c146a 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -719,6 +719,9 @@ font-technology Variable 可變 Yes 是 No 否 Delete Tab 刪除定位點 + Delete the brush “{name}”? 要刪除筆刷「{name}」嗎? + Delete these {count} brushes? 要刪除這 {count} 個筆刷嗎? + Strokes using deleted brushes become plain strokes. 使用已刪除筆刷的筆畫會變成一般筆畫。 Delete the graphic style “{name}”? 要刪除繪圖樣式「{name}」嗎? Delete Theme 刪除主題 Delete theme 刪除主題 diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index cf95c5a9f1..29acddf378 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -204,6 +204,23 @@ fn run_on(app: &mut VectorcraftApp, id: &str, names: &[String]) { app.run(id, p).ok(); } +/// Delete `names` after asking, or immediately when the bottom button was Alt-clicked. +fn delete(app: &mut VectorcraftApp, names: &[String], now: bool) { + let params = match names { + [name] => json!({ "name": name }), + _ => json!({ "names": names }), + }; + if now { + app.run("brush.delete", params).ok(); + return; + } + let message = match names { + [name] => crate::i18n::fmt(tl!("Delete the brush “{name}”?"), &[("name", name)]), + _ => crate::i18n::fmt(tl!("Delete these {count} brushes?"), &[("count", &names.len().to_string())]), + }; + crate::dialogs::confirm::ask(app, &message, tl!("Strokes using deleted brushes become plain strokes."), "brush.delete", params); +} + /// The names in `list` in the order the panel shows them: by type in [`KINDS`] order, without the /// hidden types. fn shown<'a>(list: &'a [(String, String)], hidden: &[String]) -> Vec<&'a str> { @@ -417,7 +434,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { app.status(e); } if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Brush"), false, !targets.is_empty(), 24.0).clicked() { - run_on(app, "brush.delete", &targets); + delete(app, &targets, ui.input(|i| i.modifiers.alt)); } }); } @@ -452,7 +469,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { run_on(app, "brush.duplicate", &targets); } if menu_item(ui, tl!("Delete Brush"), !targets.is_empty(), false) { - run_on(app, "brush.delete", &targets); + delete(app, &targets, false); } if menu_item(ui, tl!("Remove Brush Stroke"), sel.is_some(), false) { app.run("brush.remove", json!({})).ok(); diff --git a/crates/ui-egui/src/panels/brushes/tests.rs b/crates/ui-egui/src/panels/brushes/tests.rs index 47fc962c64..711a601999 100644 --- a/crates/ui-egui/src/panels/brushes/tests.rs +++ b/crates/ui-egui/src/panels/brushes/tests.rs @@ -146,6 +146,23 @@ fn names(app: &mut VectorcraftApp) -> Vec<String> { brushes(app).0.into_iter().map(|b| b.0).collect() } +fn undo_count(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +fn delete_button(ctx: &egui::Context, app: &mut VectorcraftApp, modifiers: egui::Modifiers, time: f64) { + let out = frame_with(ctx, app, vec![], egui::Modifiers::NONE, time, show); + let at = clickable(&out).into_iter().find(|(label, _)| label.as_deref() == Some("Delete Brush")).expect("Delete Brush button").1.center(); + click(ctx, app, at, modifiers, time + 0.5, show); +} + +fn assert_delete_dialog(app: &VectorcraftApp, message: &str) { + let d = app.ui.dialog.as_ref().expect("Delete Brush asks first"); + assert_eq!(d.kind, crate::dialogs::confirm::KIND); + assert_eq!(d.str("message"), message); + assert_eq!(d.str("detail"), "Strokes using deleted brushes become plain strokes."); +} + /// Click the panel menu's item `label` (frames at `time`, `time + 0.5`). fn menu_click(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, time: f64) { let out = frame_with(ctx, app, vec![], egui::Modifiers::NONE, time, menu); @@ -186,21 +203,23 @@ fn shift_and_command_clicks_select_brushes_for_delete_and_duplicate() { click(&ctx, &mut app, tiles[1].center(), egui::Modifiers::COMMAND, 3.0, show); let out = frame_with(&ctx, &mut app, vec![], egui::Modifiers::NONE, 3.5, show); assert_eq!(lit_tiles(&out), [0, 2]); - let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); - let before = (names(&mut app), undo(&app)); + let before = (names(&mut app), undo_count(&app)); menu_click(&ctx, &mut app, "Duplicate Brush", 4.0); let copies = [format!("{} copy", three[0]), format!("{} copy", three[2])]; assert_eq!(names(&mut app)[before.0.len()..], copies); - assert_eq!(undo(&app), before.1 + 1); + assert_eq!(undo_count(&app), before.1 + 1); // The bottom bar's last button, Delete Brush. - let out = frame_with(&ctx, &mut app, vec![], egui::Modifiers::NONE, 5.0, show); - let trash = clickable(&out).last().unwrap().1.center(); - click(&ctx, &mut app, trash, egui::Modifiers::NONE, 6.0, show); + delete_button(&ctx, &mut app, egui::Modifiers::NONE, 5.0); + assert_delete_dialog(&app, "Delete these 2 brushes?"); + assert_eq!(names(&mut app), [before.0.clone(), copies.to_vec()].concat()); + assert_eq!(brush_of(&app, rect).as_deref(), Some(three[0].as_str())); + assert_eq!(undo_count(&app), before.1 + 1); + crate::dialogs::confirm(&mut app).unwrap(); let left = names(&mut app); assert!(!left.contains(&three[0]) && !left.contains(&three[2]) && left.contains(&three[1]), "{left:?}"); assert!(copies.iter().all(|c| left.contains(c)), "{left:?}"); assert_eq!(brush_of(&app, rect), None); - assert_eq!(undo(&app), before.1 + 2); + assert_eq!(undo_count(&app), before.1 + 2); } /// Selecting other art ends the multi-selection: selecting the first art again does not bring @@ -231,6 +250,9 @@ fn selecting_other_art_ends_the_brush_multi_selection() { let out = frame_with(&ctx, &mut app, vec![], egui::Modifiers::NONE, 4.0, show); assert_eq!(lit_tiles(&out), [1]); menu_click(&ctx, &mut app, "Delete Brush", 5.0); + assert_delete_dialog(&app, &format!("Delete the brush “{}”?", three[1])); + assert!(names(&mut app).contains(&three[1])); + crate::dialogs::confirm(&mut app).unwrap(); let left = names(&mut app); assert!(left.contains(&three[0]) && !left.contains(&three[1]) && left.contains(&three[2]), "{left:?}"); assert_eq!((brush_of(&app, a).as_deref(), brush_of(&app, c)), (Some(three[0].as_str()), None)); @@ -297,10 +319,57 @@ fn select_all_unused_selects_the_brushes_no_stroke_paints_with() { let on: Vec<usize> = (0..tiles.len()).filter(|i| lit(&ctx, &out).contains(&tiles[*i])).collect(); assert_eq!(on, (0..tiles.len()).filter(|i| *i != 1).collect::<Vec<_>>()); menu_click(&ctx, &mut app, "Delete Brush", 3.0); + assert_delete_dialog(&app, &format!("Delete these {} brushes?", list.len() - 1)); + assert_eq!(names(&mut app).len(), list.len()); + crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(names(&mut app), [list[1].0.clone()]); assert_eq!(brush_of(&app, a), Some(list[1].0.clone())); } +#[test] +fn delete_button_cancel_keeps_selected_brushes_strokes_and_history() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let rect = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap()); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let (three, _) = select_three(&ctx, &mut app, rect); + let before = (names(&mut app), brush_of(&app, rect), undo_count(&app)); + delete_button(&ctx, &mut app, egui::Modifiers::NONE, 3.0); + assert_delete_dialog(&app, "Delete these 3 brushes?"); + assert_eq!((names(&mut app), brush_of(&app, rect), undo_count(&app)), before); + crate::dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!((names(&mut app), brush_of(&app, rect), undo_count(&app)), before); + assert_eq!(before.1.as_deref(), Some(three[0].as_str())); + app.run("brush.delete", json!({"name": three[0]})).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(undo_count(&app), before.2 + 1); + app.run("brush.delete", json!({"names": [three[1], three[2]]})).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(undo_count(&app), before.2 + 2); +} + +#[test] +fn alt_delete_button_removes_selected_brushes_without_dialog() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let rect = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap()); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let (three, _) = select_three(&ctx, &mut app, rect); + let before = undo_count(&app); + delete_button(&ctx, &mut app, egui::Modifiers::NONE, 3.0); + assert_delete_dialog(&app, "Delete these 3 brushes?"); + crate::dialogs::cancel(&mut app); + delete_button(&ctx, &mut app, egui::Modifiers::ALT, 4.0); + assert!(app.ui.dialog.is_none()); + let left = names(&mut app); + assert!(three.iter().all(|name| !left.contains(name))); + assert_eq!(brush_of(&app, rect), None); + assert_eq!(undo_count(&app), before + 1); +} + #[test] fn art_dropped_on_the_panel_becomes_an_art_brush_and_a_brush_drags_out() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 05985f9f18..ab9b96f4b3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -962,6 +962,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (<https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html>). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). In the Brushes panel, Shift-click selects a range of brushes and Ctrl/Cmd-click adds or removes one. Delete Brush and Duplicate Brush then act on all of them (`brush.delete {names}`, `brush.duplicate {names}`). + The bottom Delete Brush button and the panel menu ask before deleting; Alt-click (Option-click on macOS) on the button deletes without asking. Document Info has a Brushes category after Graphic Styles. It lists the Brushes panel's brushes, or with Selection Only it lists the brushes that the selected objects' strokes use. The Document Info report and Package's report list them too (`document.info {category: "brushes"}`, `brushNames`). Document Info has a Repeat Objects category after Embedded Images. It lists each radial, grid and mirror Repeat object by name with its kind and the number of instances it makes. For a grid it gives the rows and columns instead, followed by the number of instances it draws when that is fewer. With Selection Only it lists the Repeat objects in the selection. The Document Info report and Package's report list them too (`document.info {category: "repeats"}`, `repeatObjects`). The Brushes panel menu's Select All Unused selects the brushes that are not used in the document, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. A brush counts as used when a stroke paints with it in the art (opacity masks included), in symbols, graph designs, pattern tiles or graphic styles, or in the art of a used brush (`brush.unused`). From 90f9907de970c3dc8d6c66ddce35941e2e992751 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 06:49:52 -0700 Subject: [PATCH 127/260] Brushes: Alt-click Delete Brush runs through the shared command helper --- crates/ui-egui/src/panels/brushes.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index 29acddf378..22b7d9401e 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -206,14 +206,14 @@ fn run_on(app: &mut VectorcraftApp, id: &str, names: &[String]) { /// Delete `names` after asking, or immediately when the bottom button was Alt-clicked. fn delete(app: &mut VectorcraftApp, names: &[String], now: bool) { + if now { + run_on(app, "brush.delete", names); + return; + } let params = match names { [name] => json!({ "name": name }), _ => json!({ "names": names }), }; - if now { - app.run("brush.delete", params).ok(); - return; - } let message = match names { [name] => crate::i18n::fmt(tl!("Delete the brush “{name}”?"), &[("name", name)]), _ => crate::i18n::fmt(tl!("Delete these {count} brushes?"), &[("count", &names.len().to_string())]), From 79188b359387ff99743a0ec1ac37a1cc5bebdc90 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 07:21:27 -0700 Subject: [PATCH 128/260] Brushes: the Delete Brush prompt for several brushes uses each language's plural forms The confirmation for several brushes now goes through i18n::tn, as the Graphic Styles prompt does, and each catalog gives the count-dependent forms in an @plural row. --- crates/ui-egui/src/i18n/bg.tsv | 2 +- crates/ui-egui/src/i18n/ca.tsv | 2 +- crates/ui-egui/src/i18n/cs.tsv | 2 +- crates/ui-egui/src/i18n/da.tsv | 2 +- crates/ui-egui/src/i18n/de.tsv | 2 +- crates/ui-egui/src/i18n/el.tsv | 2 +- crates/ui-egui/src/i18n/es.tsv | 2 +- crates/ui-egui/src/i18n/fi.tsv | 2 +- crates/ui-egui/src/i18n/fr.tsv | 2 +- crates/ui-egui/src/i18n/hu.tsv | 2 +- crates/ui-egui/src/i18n/id.tsv | 2 +- crates/ui-egui/src/i18n/it.tsv | 2 +- crates/ui-egui/src/i18n/ja.tsv | 2 +- crates/ui-egui/src/i18n/ka.tsv | 2 +- crates/ui-egui/src/i18n/ko.tsv | 2 +- crates/ui-egui/src/i18n/nl.tsv | 2 +- crates/ui-egui/src/i18n/pl.tsv | 2 +- crates/ui-egui/src/i18n/pt-br.tsv | 2 +- crates/ui-egui/src/i18n/ru.tsv | 2 +- crates/ui-egui/src/i18n/sv.tsv | 2 +- crates/ui-egui/src/i18n/tr.tsv | 2 +- crates/ui-egui/src/i18n/uk.tsv | 2 +- crates/ui-egui/src/i18n/vi.tsv | 2 +- crates/ui-egui/src/i18n/zh-hans.tsv | 2 +- crates/ui-egui/src/i18n/zh-hant.tsv | 2 +- crates/ui-egui/src/panels/brushes.rs | 2 +- crates/ui-egui/src/panels/brushes/tests.rs | 13 +++++++++++++ 27 files changed, 39 insertions(+), 26 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 702fb78d2b..5a5efddad2 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -743,7 +743,6 @@ font-technology Variable Променливи No Не Delete Tab Изтриване на табулация Delete the brush “{name}”? Да се изтрие четката „{name}“? - Delete these {count} brushes? Да се изтрият тези {count} четки? Strokes using deleted brushes become plain strokes. Щрихите, които използват изтритите четки, стават обикновени щрихи. Delete the graphic style “{name}”? Изтриване на графичния стил „{name}“? Delete Theme Изтриване на тема @@ -3634,6 +3633,7 @@ imageTrace Outline Контур @plural {n} item|{n} items {n} обект|{n} обекта @plural Color Table ({n} color)|Color Table ({n} colors) Цветна таблица ({n} цвят)|Цветна таблица ({n} цвята) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Изтриване на този графичен стил ({n})?|Изтриване на тези графични стилове ({n})? +@plural Delete this {n} brush?|Delete these {n} brushes? Изтриване на тази четка ({n})?|Изтриване на тези четки ({n})? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Изтриване на този {n} образец или група?|Изтриване на тези {n} образца и групи? @plural {n} Layer|{n} Layers {n} слой|{n} слоя @plural {n} Object|{n} Objects {n} обект|{n} обекта diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 4269d2b7e7..cd1046755c 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1060,7 +1060,6 @@ No No Delete Tab Suprimeix la tabulació Delete the brush “{name}”? Voleu suprimir el pinzell “{name}”? - Delete these {count} brushes? Voleu suprimir aquests {count} pinzells? Strokes using deleted brushes become plain strokes. Els traços que utilitzen pinzells suprimits esdevenen traços normals. Delete the graphic style “{name}”? Voleu suprimir l’estil gràfic “{name}”? Delete the library “{name}”? Voleu suprimir la biblioteca “{name}”? @@ -4694,6 +4693,7 @@ @plural agrees with {n} default shortcut|agrees with {n} default shortcuts coincideix amb {n} drecera per defecte|coincideix amb {n} dreceres per defecte @plural Color Table ({n} color)|Color Table ({n} colors) Taula de colors ({n} color)|Taula de colors ({n} colors) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Voleu suprimir aquest {n} estil gràfic?|Voleu suprimir aquests {n} estils gràfics? +@plural Delete this {n} brush?|Delete these {n} brushes? Voleu suprimir aquest {n} pinzell?|Voleu suprimir aquests {n} pinzells? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Voleu suprimir aquesta {n} mostra o grup?|Voleu suprimir aquestes {n} mostres i grups? @plural {n} area highlighted|{n} areas highlighted {n} àrea ressaltada|{n} àrees ressaltades @plural {n} color|{n} colors {n} color|{n} colors diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 39c5e2be1a..4ffe67aea9 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1559,7 +1559,6 @@ lighting Light Světlo Save to Swatches Uložit do vzorníku Delete Graphic Style (Alt-click: without asking) Odstranit grafický styl (Alt+kliknutí: bez dotazu) Delete the brush “{name}”? Odstranit štětec „{name}“? - Delete these {count} brushes? Odstranit těchto {count} štětců? Strokes using deleted brushes become plain strokes. Tahy používající odstraněné štětce se změní na běžné tahy. Delete the graphic style “{name}”? Odstranit grafický styl „{name}“? Delete these {n} graphic styles? Odstranit tyto grafické styly ({n})? @@ -4138,6 +4137,7 @@ imageTrace Outline Obrys @plural {n} item|{n} items {n} položka|{n} položky|{n} položek @plural Color Table ({n} color)|Color Table ({n} colors) Tabulka barev ({n} barva)|Tabulka barev ({n} barvy)|Tabulka barev ({n} barev) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Odstranit {n} grafický styl?|Odstranit {n} grafické styly?|Odstranit {n} grafických stylů? +@plural Delete this {n} brush?|Delete these {n} brushes? Odstranit {n} štětec?|Odstranit {n} štětce?|Odstranit {n} štětců? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Odstranit {n} položku vzorníku nebo skupinu?|Odstranit {n} položky vzorníku a skupiny?|Odstranit {n} položek vzorníku a skupin? @plural {n} Layer|{n} Layers {n} vrstva|{n} vrstvy|{n} vrstev @plural {n} Object|{n} Objects {n} objekt|{n} objekty|{n} objektů diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index f7021936c3..bce83c7bd6 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1473,7 +1473,6 @@ lighting Light Lys Save to Swatches Gem i farveprøver Delete Graphic Style (Alt-click: without asking) Slet grafisk typografi (Alt-klik: uden at spørge) Delete the brush “{name}”? Slet penslen »{name}«? - Delete these {count} brushes? Slet disse {count} pensler? Strokes using deleted brushes become plain strokes. Streger, der bruger slettede pensler, bliver almindelige streger. Delete the graphic style “{name}”? Slet den grafiske typografi »{name}«? Delete these {n} graphic styles? Slet disse {n} grafiske typografier? @@ -3870,6 +3869,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} element|{n} elementer @plural Color Table ({n} color)|Color Table ({n} colors) Farvetabel ({n} farve)|Farvetabel ({n} farver) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Vil du slette denne {n} grafikstil?|Vil du slette disse {n} grafikstile? +@plural Delete this {n} brush?|Delete these {n} brushes? Vil du slette denne {n} pensel?|Vil du slette disse {n} pensler? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Slet denne {n} farveprøve eller gruppe?|Slet disse {n} farveprøver og grupper? @plural {n} Layer|{n} Layers {n} lag|{n} lag @plural {n} Object|{n} Objects {n} objekt|{n} objekter diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index dc9c67f8bb..9e837d8eb6 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -737,7 +737,6 @@ font-technology Variable Variabel No Nein Delete Tab Tabulator löschen Delete the brush “{name}”? Pinsel „{name}“ löschen? - Delete these {count} brushes? Diese {count} Pinsel löschen? Strokes using deleted brushes become plain strokes. Konturen mit gelöschten Pinseln werden zu einfachen Konturen. Delete the graphic style “{name}”? Grafikstil „{name}“ löschen? Delete Theme Thema löschen @@ -3621,6 +3620,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} Element|{n} Elemente @plural Color Table ({n} color)|Color Table ({n} colors) Farbtabelle ({n} Farbe)|Farbtabelle ({n} Farben) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Diesen {n} Grafikstil löschen?|Diese {n} Grafikstile löschen? +@plural Delete this {n} brush?|Delete these {n} brushes? Diesen {n} Pinsel löschen?|Diese {n} Pinsel löschen? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? {n} Farbfeld oder Gruppe löschen?|Diese {n} Farbfelder und Gruppen löschen? @plural {n} Layer|{n} Layers {n} Ebene|{n} Ebenen @plural {n} Object|{n} Objects {n} Objekt|{n} Objekte diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 150002aa42..e5ac837751 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -717,7 +717,6 @@ font-technology Variable Μεταβλητές No Όχι Delete Tab Διαγραφή στηλοθέτη Delete the brush “{name}”? Να διαγραφεί το πινέλο «{name}»; - Delete these {count} brushes? Να διαγραφούν αυτά τα {count} πινέλα; Strokes using deleted brushes become plain strokes. Οι πινελιές που χρησιμοποιούν διαγραμμένα πινέλα γίνονται απλές πινελιές. Delete the graphic style “{name}”? Να διαγραφεί το στυλ γραφικών «{name}»; Delete Theme Διαγραφή θέματος @@ -2032,6 +2031,7 @@ imageTrace Outline Περίγραμμα @plural {n} item|{n} items {n} στοιχείο|{n} στοιχεία @plural Color Table ({n} color)|Color Table ({n} colors) Πίνακας χρωμάτων ({n} χρώμα)|Πίνακας χρωμάτων ({n} χρώματα) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Να διαγραφεί αυτό το {n} στυλ γραφικών;|Να διαγραφούν αυτά τα {n} στυλ γραφικών; +@plural Delete this {n} brush?|Delete these {n} brushes? Να διαγραφεί αυτό το {n} πινέλο;|Να διαγραφούν αυτά τα {n} πινέλα; @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Να διαγραφεί αυτό το {n} δείγμα χρώματος ή ομάδα;|Να διαγραφούν αυτά τα {n} δείγματα χρωμάτων και οι ομάδες; @plural {n} Layer|{n} Layers {n} επίπεδο|{n} επίπεδα @plural {n} Object|{n} Objects {n} αντικείμενο|{n} αντικείμενα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 2bbb317024..367692be2f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -758,7 +758,6 @@ font-technology Variable Variables No No Delete Tab Eliminar tabulación Delete the brush “{name}”? ¿Eliminar el pincel “{name}”? - Delete these {count} brushes? ¿Eliminar estos {count} pinceles? Strokes using deleted brushes become plain strokes. Los trazos que usan pinceles eliminados se convierten en trazos simples. Delete the graphic style “{name}”? ¿Eliminar el estilo gráfico “{name}”? Delete Theme Eliminar tema @@ -3706,6 +3705,7 @@ imageTrace Outline Contorno @plural {n} item|{n} items {n} elemento|{n} elementos @plural Color Table ({n} color)|Color Table ({n} colors) Tabla de colores ({n} color)|Tabla de colores ({n} colores) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? ¿Eliminar {n} estilo gráfico?|¿Eliminar estos {n} estilos gráficos? +@plural Delete this {n} brush?|Delete these {n} brushes? ¿Eliminar {n} pincel?|¿Eliminar estos {n} pinceles? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? ¿Eliminar {n} muestra o grupo?|¿Eliminar estas {n} muestras y grupos? @plural {n} Layer|{n} Layers {n} capa|{n} capas @plural {n} Object|{n} Objects {n} objeto|{n} objetos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1a276e0e71..d0b30760ac 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1533,7 +1533,6 @@ lighting Light Valo Save to Swatches Tallenna värimalleihin Delete Graphic Style (Alt-click: without asking) Poista grafiikkatyyli (Alt-napsautus: kysymättä) Delete the brush “{name}”? Poistetaanko sivellin ”{name}”? - Delete these {count} brushes? Poistetaanko nämä {count} sivellintä? Strokes using deleted brushes become plain strokes. Poistettuja siveltimiä käyttävät viivat muuttuvat tavallisiksi viivoiksi. Delete the graphic style “{name}”? Poistetaanko grafiikkatyyli ”{name}”? Delete these {n} graphic styles? Poistetaanko nämä {n} grafiikkatyyliä? @@ -4056,6 +4055,7 @@ imageTrace Outline Ääriviiva @plural {n} item|{n} items {n} kohde|{n} kohdetta @plural Color Table ({n} color)|Color Table ({n} colors) Väritaulukko ({n} väri)|Väritaulukko ({n} väriä) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Poistetaanko tämä {n} grafiikkatyyli?|Poistetaanko nämä {n} grafiikkatyyliä? +@plural Delete this {n} brush?|Delete these {n} brushes? Poistetaanko tämä {n} sivellin?|Poistetaanko nämä {n} sivellintä? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Poistetaanko tämä {n} värimalli tai ryhmä?|Poistetaanko nämä {n} värimallia ja ryhmää? @plural {n} Layer|{n} Layers {n} taso|{n} tasoa @plural {n} Object|{n} Objects {n} objekti|{n} objektia diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 68a78da7dd..ab5fc9acd1 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -760,7 +760,6 @@ font-technology Variable Variables No Non Delete Tab Supprimer la tabulation Delete the brush “{name}”? Supprimer la forme « {name} » ? - Delete these {count} brushes? Supprimer ces {count} formes ? Strokes using deleted brushes become plain strokes. Les contours utilisant des formes supprimées deviennent des contours simples. Delete the graphic style “{name}”? Supprimer le style graphique « {name} » ? Delete Theme Supprimer le thème @@ -3704,6 +3703,7 @@ imageTrace Outline Contour @plural {n} item|{n} items {n} élément|{n} éléments @plural Color Table ({n} color)|Color Table ({n} colors) Table des couleurs ({n} couleur)|Table des couleurs ({n} couleurs) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Supprimer {n} style graphique ?|Supprimer ces {n} styles graphiques ? +@plural Delete this {n} brush?|Delete these {n} brushes? Supprimer {n} forme ?|Supprimer ces {n} formes ? @plural {n} Layer|{n} Layers {n} calque|{n} calques @plural {n} Object|{n} Objects {n} objet|{n} objets @plural {n} area highlighted|{n} areas highlighted {n} zone mise en évidence|{n} zones mises en évidence diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 322770fb87..e91e7dfe56 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -982,7 +982,6 @@ font-technology Variable Változó No Nem Delete Tab Tabulátor törlése Delete the brush “{name}”? Törlöd ezt az ecsetet: „{name}”? - Delete these {count} brushes? Törlöd ezt a {count} ecsetet? Strokes using deleted brushes become plain strokes. A törölt ecseteket használó körvonalak egyszerű körvonalakká válnak. Delete the graphic style “{name}”? Törlöd ezt a grafikai stílust: „{name}”? Delete the library “{name}”? Törlöd ezt a könyvtárat: „{name}”? @@ -4459,6 +4458,7 @@ theme Appearance Kinézet imageTrace Outline Körvonal @plural Color Table ({n} color)|Color Table ({n} colors) Színtábla ({n} szín) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? {n} grafikai stílus törlése? +@plural Delete this {n} brush?|Delete these {n} brushes? {n} ecset törlése? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? {n} színminta és csoport törlése? @plural {n} area highlighted|{n} areas highlighted Kiemelt terület: {n} @plural {n} color|{n} colors {n} szín diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 25ee0213a1..265da6fbee 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1473,7 +1473,6 @@ lighting Light Cahaya Save to Swatches Simpan ke swatch Delete Graphic Style (Alt-click: without asking) Hapus gaya grafis (Alt+klik: tanpa konfirmasi) Delete the brush “{name}”? Hapus kuas “{name}”? - Delete these {count} brushes? Hapus {count} kuas ini? Strokes using deleted brushes become plain strokes. Goresan yang menggunakan kuas terhapus menjadi goresan biasa. Delete the graphic style “{name}”? Hapus gaya grafis “{name}”? Delete these {n} graphic styles? Hapus {n} gaya grafis ini? @@ -3870,6 +3869,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} item @plural Color Table ({n} color)|Color Table ({n} colors) Tabel warna ({n} warna) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Hapus {n} gaya grafis ini? +@plural Delete this {n} brush?|Delete these {n} brushes? Hapus {n} kuas ini? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Hapus {n} swatch dan grup ini? @plural {n} Layer|{n} Layers {n} lapisan @plural {n} Object|{n} Objects {n} objek diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 7685ad98a5..af6874bbe8 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -758,7 +758,6 @@ font-technology Variable Variabili No No Delete Tab Elimina tabulazione Delete the brush “{name}”? Eliminare il pennello “{name}”? - Delete these {count} brushes? Eliminare questi {count} pennelli? Strokes using deleted brushes become plain strokes. I tracciati che usano pennelli eliminati diventano tracciati semplici. Delete the graphic style “{name}”? Eliminare lo stile grafico “{name}”? Delete Theme Elimina tema @@ -3742,6 +3741,7 @@ imageTrace Outline Contorno @plural {n} item|{n} items {n} elemento|{n} elementi @plural Color Table ({n} color)|Color Table ({n} colors) Tabella colori ({n} colore)|Tabella colori ({n} colori) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Eliminare {n} stile grafico?|Eliminare questi {n} stili grafici? +@plural Delete this {n} brush?|Delete these {n} brushes? Eliminare {n} pennello?|Eliminare questi {n} pennelli? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Eliminare {n} campione o gruppo?|Eliminare questi {n} campioni e gruppi? @plural {n} Layer|{n} Layers {n} livello|{n} livelli @plural {n} Object|{n} Objects {n} oggetto|{n} oggetti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 99376a0f11..f9ad60b875 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1309,7 +1309,6 @@ font-technology Variable バリアブル Delete Width Point 幅ポイントを削除 Delete Workspace ワークスペースを削除 Delete the brush “{name}”? ブラシ「{name}」を削除しますか? - Delete these {count} brushes? これら {count} 個のブラシを削除しますか? Strokes using deleted brushes become plain strokes. 削除したブラシを使用する線は通常の線になります。 Delete the graphic style “{name}”? グラフィックスタイル「{name}」を削除しますか? Delete theme テーマを削除 @@ -3725,6 +3724,7 @@ file-filter Templates テンプレート imageTrace Outline アウトライン @plural Color Table ({n} color)|Color Table ({n} colors) カラーテーブル ({n} 色) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? {n} 個のグラフィックスタイルを削除しますか? +@plural Delete this {n} brush?|Delete these {n} brushes? {n} 個のブラシを削除しますか? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? これら {n} 個のスウォッチとグループを削除しますか? @plural {n} Layer|{n} Layers {n} レイヤー @plural {n} Object|{n} Objects {n} オブジェクト diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b55b3f2c95..7f6eb84ba3 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1390,7 +1390,6 @@ lighting Light სინათლე Save to Swatches ფერის ნიმუშებში შენახვა Delete Graphic Style (Alt-click: without asking) გრაფიკული სტილის წაშლა (Alt-დაწკაპუნებით: დაუკითხავად) Delete the brush “{name}”? წაიშალოს ფუნჯი „{name}“? - Delete these {count} brushes? წაიშალოს ეს {count} ფუნჯი? Strokes using deleted brushes become plain strokes. წაშლილი ფუნჯებით დახატული შტრიხები ჩვეულებრივ შტრიხებად იქცევა. Delete the graphic style “{name}”? წაიშალოს გრაფიკული სტილი „{name}“? Delete these {n} graphic styles? წაიშალოს ეს გრაფიკული სტილები ({n})? @@ -3636,6 +3635,7 @@ font-technology Variable ცვლადი @plural {n} item|{n} items ელემენტი: {n} @plural Color Table ({n} color)|Color Table ({n} colors) ფერების ცხრილი (ფერი: {n}) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? წაიშალოს გრაფიკული სტილები ({n})? +@plural Delete this {n} brush?|Delete these {n} brushes? წაიშალოს ეს ფუნჯი ({n})? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? წაიშალოს ეს ფერის ნიმუშები და ჯგუფები ({n})? @plural {n} Layer|{n} Layers შრე: {n} @plural {n} Object|{n} Objects ობიექტი: {n} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e5dee07ee1..a64392ef3b 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1300,7 +1300,6 @@ font-technology Variable 가변 Delete Width Point 너비 포인트 삭제 Delete Workspace 작업 영역 삭제 Delete the brush “{name}”? 브러시 “{name}”을(를) 삭제하시겠습니까? - Delete these {count} brushes? 이 브러시 {count}개를 삭제하시겠습니까? Strokes using deleted brushes become plain strokes. 삭제된 브러시를 사용한 선은 일반 선이 됩니다. Delete the graphic style “{name}”? 그래픽 스타일 “{name}”을(를) 삭제하시겠습니까? Delete theme 테마 삭제 @@ -3714,6 +3713,7 @@ file-filter Templates 템플릿 imageTrace Outline 윤곽선 @plural Color Table ({n} color)|Color Table ({n} colors) 색상 표 ({n}색)|색상 표 ({n}색) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? 그래픽 스타일 {n}개를 삭제하시겠습니까?|그래픽 스타일 {n}개를 삭제하시겠습니까? +@plural Delete this {n} brush?|Delete these {n} brushes? 브러시 {n}개를 삭제하시겠습니까?|브러시 {n}개를 삭제하시겠습니까? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? 견본과 그룹 {n}개를 삭제하시겠습니까? @plural {n} Layer|{n} Layers 레이어 {n}개|레이어 {n}개 @plural {n} Object|{n} Objects 개체 {n}개|개체 {n}개 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index bbee0d063b..ed254e2a19 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1487,7 +1487,6 @@ lighting Light Licht Save to Swatches Opslaan in stalen Delete Graphic Style (Alt-click: without asking) Grafische stijl verwijderen (Alt-klik: zonder vragen) Delete the brush “{name}”? Kwast „{name}” verwijderen? - Delete these {count} brushes? Deze {count} kwasten verwijderen? Strokes using deleted brushes become plain strokes. Lijnen die verwijderde kwasten gebruiken, worden gewone lijnen. Delete the graphic style “{name}”? De grafische stijl „{name}” verwijderen? Delete these {n} graphic styles? Deze {n} grafische stijlen verwijderen? @@ -3884,6 +3883,7 @@ imageTrace Outline Contour @plural {n} item|{n} items {n} item|{n} items @plural Color Table ({n} color)|Color Table ({n} colors) Kleurentabel ({n} kleur)|Kleurentabel ({n} kleuren) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Deze {n} grafische stijl verwijderen?|Deze {n} grafische stijlen verwijderen? +@plural Delete this {n} brush?|Delete these {n} brushes? Deze {n} kwast verwijderen?|Deze {n} kwasten verwijderen? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Deze {n} staal of groep verwijderen?|Deze {n} stalen en groepen verwijderen? @plural {n} Layer|{n} Layers {n} laag|{n} lagen @plural {n} Object|{n} Objects {n} object|{n} objecten diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 95d62b9a05..f2e5c5964b 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1473,7 +1473,6 @@ lighting Light Światło Save to Swatches Zapisz w próbkach Delete Graphic Style (Alt-click: without asking) Usuń styl graficzny (kliknięcie z Alt: bez pytania) Delete the brush “{name}”? Usunąć pędzel „{name}”? - Delete these {count} brushes? Usunąć te {count} pędzle? Strokes using deleted brushes become plain strokes. Obrysy używające usuniętych pędzli stają się zwykłymi obrysami. Delete the graphic style “{name}”? Usunąć styl graficzny „{name}”? Delete these {n} graphic styles? Usunąć te style graficzne ({n})? @@ -3964,6 +3963,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} element|{n} elementy|{n} elementów @plural Color Table ({n} color)|Color Table ({n} colors) Tablica kolorów ({n} kolor)|Tablica kolorów ({n} kolory)|Tablica kolorów ({n} kolorów) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Usunąć {n} styl graficzny?|Usunąć {n} style graficzne?|Usunąć {n} stylów graficznych? +@plural Delete this {n} brush?|Delete these {n} brushes? Usunąć {n} pędzel?|Usunąć {n} pędzle?|Usunąć {n} pędzli? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Usunąć {n} próbkę lub grupę?|Usunąć {n} próbki i grupy?|Usunąć {n} próbek i grup? @plural {n} Layer|{n} Layers {n} warstwa|{n} warstwy|{n} warstw @plural {n} Object|{n} Objects {n} obiekt|{n} obiekty|{n} obiektów diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 7f4d8287a3..4d39287c57 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -675,7 +675,6 @@ Delete Width Point Excluir Ponto de Largura Delete Workspace Excluir Espaço de Trabalho Delete the brush “{name}”? Excluir o pincel “{name}”? - Delete these {count} brushes? Excluir estes {count} pincéis? Strokes using deleted brushes become plain strokes. Traços que usam pincéis excluídos tornam-se traços simples. Delete the graphic style “{name}”? Excluir o estilo gráfico “{name}”? Delete theme Excluir tema @@ -3044,6 +3043,7 @@ imageTrace Outline Contorno @plural {n} item|{n} items {n} item|{n} itens @plural Color Table ({n} color)|Color Table ({n} colors) Tabela de Cores ({n} cor)|Tabela de Cores ({n} cores) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Excluir este {n} estilo gráfico?|Excluir estes {n} estilos gráficos? +@plural Delete this {n} brush?|Delete these {n} brushes? Excluir este {n} pincel?|Excluir estes {n} pincéis? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Excluir esta {n} amostra ou grupo?|Excluir estas {n} amostras e grupos? @plural {n} Layer|{n} Layers {n} Camada|{n} Camadas @plural {n} Object|{n} Objects {n} Objeto|{n} Objetos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 583a3f09a7..952171bbf1 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -756,7 +756,6 @@ font-technology Variable Вариативные No Нет Delete Tab Удалить табуляцию Delete the brush “{name}”? Удалить кисть «{name}»? - Delete these {count} brushes? Удалить эти кисти ({count})? Strokes using deleted brushes become plain strokes. Обводки, использующие удалённые кисти, становятся обычными обводками. Delete the graphic style “{name}”? Удалить графический стиль «{name}»? Delete Theme Удалить тему @@ -3738,6 +3737,7 @@ imageTrace Outline Контур @plural {n} item|{n} items {n} элемент|{n} элемента|{n} элементов @plural Color Table ({n} color)|Color Table ({n} colors) Цветовая таблица ({n} цвет)|Цветовая таблица ({n} цвета)|Цветовая таблица ({n} цветов) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Удалить этот графический стиль ({n})?|Удалить эти графические стили ({n})?|Удалить эти графические стили ({n})? +@plural Delete this {n} brush?|Delete these {n} brushes? Удалить эту кисть ({n})?|Удалить эти кисти ({n})?|Удалить {n} кистей? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Удалить образцы и группы ({n})?|Удалить {n} образца и группы?|Удалить {n} образцов и групп? @plural {n} Layer|{n} Layers {n} слой|{n} слоя|{n} слоёв @plural {n} Object|{n} Objects {n} объект|{n} объекта|{n} объектов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1b68826627..9f24f8e02c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -745,7 +745,6 @@ font-technology Variable Variabla No Nej Delete Tab Radera tabb Delete the brush “{name}”? Radera penseln ”{name}”? - Delete these {count} brushes? Radera dessa {count} penslar? Strokes using deleted brushes become plain strokes. Linjer som använder borttagna penslar blir vanliga linjer. Delete the graphic style “{name}”? Radera grafikstilen ”{name}”? Delete Theme Radera tema @@ -3634,6 +3633,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} objekt|{n} objekt @plural Color Table ({n} color)|Color Table ({n} colors) Färgtabell ({n} färg)|Färgtabell ({n} färger) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Radera {n} grafisk stil?|Radera de här {n} grafiska stilarna? +@plural Delete this {n} brush?|Delete these {n} brushes? Radera {n} pensel?|Radera dessa {n} penslar? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Radera {n} färgruta eller grupp?|Radera dessa {n} färgrutor och grupper? @plural {n} Layer|{n} Layers {n} lager|{n} lager @plural {n} Object|{n} Objects {n} objekt|{n} objekt diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d318f8a75d..91fd8143d1 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -737,7 +737,6 @@ font-technology Variable Değişken No Hayır Delete Tab Sekmeyi Sil Delete the brush “{name}”? “{name}” fırçası silinsin mi? - Delete these {count} brushes? Bu {count} fırça silinsin mi? Strokes using deleted brushes become plain strokes. Silinen fırçaları kullanan konturlar düz konturlara dönüşür. Delete the graphic style “{name}”? “{name}” grafik stili silinsin mi? Delete Theme Temayı Sil @@ -3528,6 +3527,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} öğe @plural Color Table ({n} color)|Color Table ({n} colors) Renk Tablosu ({n} renk) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Bu {n} grafik stili silinsin mi? +@plural Delete this {n} brush?|Delete these {n} brushes? Bu {n} fırça silinsin mi? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Bu {n} renk örneği ve grup silinsin mi? @plural {n} Layer|{n} Layers {n} Katman @plural {n} Object|{n} Objects {n} Nesne diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 5dd9b8979c..750796afe1 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -752,7 +752,6 @@ font-technology Variable Варіативні No Ні Delete Tab Видалити табуляцію Delete the brush “{name}”? Видалити пензель «{name}»? - Delete these {count} brushes? Видалити ці пензлі ({count})? Strokes using deleted brushes become plain strokes. Обведення, що використовують видалені пензлі, стають звичайними обведеннями. Delete the graphic style “{name}”? Видалити графічний стиль «{name}»? Delete Theme Видалити тему @@ -3735,6 +3734,7 @@ imageTrace Outline Контур @plural {n} item|{n} items {n} елемент|{n} елементи|{n} елементів @plural Color Table ({n} color)|Color Table ({n} colors) Таблиця кольорів ({n} колір)|Таблиця кольорів ({n} кольори)|Таблиця кольорів ({n} кольорів) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Видалити цей графічний стиль ({n})?|Видалити ці графічні стилі ({n})?|Видалити ці графічні стилі ({n})? +@plural Delete this {n} brush?|Delete these {n} brushes? Видалити цей пензель ({n})?|Видалити ці пензлі ({n})?|Видалити {n} пензлів? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Видалити зразки та групи ({n})?|Видалити {n} зразки та групи?|Видалити {n} зразків і груп? @plural {n} Layer|{n} Layers {n} шар|{n} шари|{n} шарів @plural {n} Object|{n} Objects {n} об’єкт|{n} об’єкти|{n} об’єктів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 6136b2ddd6..494b40265c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -878,7 +878,6 @@ font-technology Variable Biến thiên No Không Delete Tab Xóa tab Delete the brush “{name}”? Xóa cọ “{name}”? - Delete these {count} brushes? Xóa {count} cọ này? Strokes using deleted brushes become plain strokes. Các nét dùng cọ đã xóa trở thành nét thông thường. Delete the graphic style “{name}”? Xóa kiểu đồ họa “{name}”? Delete the library “{name}”? Xóa thư viện “{name}”? @@ -4100,6 +4099,7 @@ gradient-kind Radial Hướng tâm imageTrace Outline Đường viền @plural Color Table ({n} color)|Color Table ({n} colors) Bảng màu ({n} màu) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Xóa {n} kiểu đồ họa này? +@plural Delete this {n} brush?|Delete these {n} brushes? Xóa {n} cọ này? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Xóa {n} mẫu màu và nhóm này? @plural {n} area highlighted|{n} areas highlighted {n} vùng được tô sáng @plural {n} color|{n} colors {n} màu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 7fbdf119b0..105fefd26d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -701,7 +701,6 @@ No 否 Delete Tab 删除制表位 Delete the brush “{name}”? 要删除画笔“{name}”吗? - Delete these {count} brushes? 要删除这 {count} 个画笔吗? Strokes using deleted brushes become plain strokes. 使用已删除画笔的描边会变成普通描边。 Delete the graphic style “{name}”? 要删除图形样式“{name}”吗? Delete Theme 删除主题 @@ -3581,6 +3580,7 @@ imageTrace Outline 轮廓 @plural {n} item|{n} items {n} 个项目 @plural Color Table ({n} color)|Color Table ({n} colors) 颜色表 ({n} 色) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? 要删除这 {n} 个图形样式吗? +@plural Delete this {n} brush?|Delete these {n} brushes? 要删除这 {n} 个画笔吗? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? 要删除这 {n} 个色板和编组吗? @plural {n} Layer|{n} Layers {n} 个图层 @plural {n} Object|{n} Objects {n} 个对象 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 3cb07c146a..7ffb1831a4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -720,7 +720,6 @@ font-technology Variable 可變 No 否 Delete Tab 刪除定位點 Delete the brush “{name}”? 要刪除筆刷「{name}」嗎? - Delete these {count} brushes? 要刪除這 {count} 個筆刷嗎? Strokes using deleted brushes become plain strokes. 使用已刪除筆刷的筆畫會變成一般筆畫。 Delete the graphic style “{name}”? 要刪除繪圖樣式「{name}」嗎? Delete Theme 刪除主題 @@ -4560,6 +4559,7 @@ imageTrace Outline 輪廓 @plural {n} item|{n} items {n} 個項目 @plural Color Table ({n} color)|Color Table ({n} colors) 色彩表 ({n} 色) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? 要刪除這 {n} 個繪圖樣式嗎? +@plural Delete this {n} brush?|Delete these {n} brushes? 要刪除這 {n} 個筆刷嗎? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? 要刪除這 {n} 個色票和群組嗎? @plural {n} Layer|{n} Layers {n} 個圖層 @plural {n} Object|{n} Objects {n} 個物件 diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index 22b7d9401e..b734047305 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -216,7 +216,7 @@ fn delete(app: &mut VectorcraftApp, names: &[String], now: bool) { }; let message = match names { [name] => crate::i18n::fmt(tl!("Delete the brush “{name}”?"), &[("name", name)]), - _ => crate::i18n::fmt(tl!("Delete these {count} brushes?"), &[("count", &names.len().to_string())]), + _ => crate::i18n::tn(names.len() as u64, "Delete this {n} brush?", "Delete these {n} brushes?"), }; crate::dialogs::confirm::ask(app, &message, tl!("Strokes using deleted brushes become plain strokes."), "brush.delete", params); } diff --git a/crates/ui-egui/src/panels/brushes/tests.rs b/crates/ui-egui/src/panels/brushes/tests.rs index 711a601999..421c0162a4 100644 --- a/crates/ui-egui/src/panels/brushes/tests.rs +++ b/crates/ui-egui/src/panels/brushes/tests.rs @@ -163,6 +163,19 @@ fn assert_delete_dialog(app: &VectorcraftApp, message: &str) { assert_eq!(d.str("detail"), "Strokes using deleted brushes become plain strokes."); } +#[test] +fn deleting_five_brushes_uses_polish_many_form() { + let previous = crate::i18n::current(); + let polish = crate::i18n::Lang::from_code("pl").unwrap(); + crate::i18n::set_current(polish); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let names: Vec<String> = (1..=5).map(|n| format!("Brush {n}")).collect(); + delete(&mut app, &names, false); + let message = app.ui.dialog.as_ref().map(|d| d.str("message")); + crate::i18n::set_current(previous); + assert_eq!(message, Some("Usunąć 5 pędzli?".to_string())); +} + /// Click the panel menu's item `label` (frames at `time`, `time + 0.5`). fn menu_click(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, time: f64) { let out = frame_with(ctx, app, vec![], egui::Modifiers::NONE, time, menu); From b1aa5767648715225b5ebc294bdf7698e3e39a1b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 21:56:48 -0700 Subject: [PATCH 129/260] Brushes: Delete Brush asks Yes or No for unused brushes, and Remove Strokes or Cancel for brushes in use The question for brushes no stroke uses reads "Delete the brush selection?" with Yes and No, from the bottom button and the panel menu, and Alt-click (Option-click on macOS) on the button still deletes them without asking. When a stroke uses one of the brushes, the button, Alt-click and the menu item ask with Remove Strokes and Cancel; Remove Strokes deletes the brushes and the strokes that used them become plain strokes. brush.unused also counts the tile that pattern editing's Cancel puts back, which brush.delete already clears, so the panel asks the in-use question for a brush only that tile uses. --- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/brushes.rs | 7 +- crates/engine/src/tests/brushsym.rs | 25 +++++++ crates/ui-egui/src/dialogs.rs | 2 + crates/ui-egui/src/dialogs/brush_delete.rs | 61 +++++++++++++++ .../ui-egui/src/dialogs/brush_delete/tests.rs | 71 ++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 7 +- crates/ui-egui/src/i18n/bs.tsv | 5 ++ crates/ui-egui/src/i18n/ca.tsv | 7 +- crates/ui-egui/src/i18n/cs.tsv | 7 +- crates/ui-egui/src/i18n/da.tsv | 7 +- crates/ui-egui/src/i18n/de.tsv | 7 +- crates/ui-egui/src/i18n/el.tsv | 7 +- crates/ui-egui/src/i18n/es.tsv | 7 +- crates/ui-egui/src/i18n/fi.tsv | 7 +- crates/ui-egui/src/i18n/fr.tsv | 8 +- crates/ui-egui/src/i18n/hu.tsv | 7 +- crates/ui-egui/src/i18n/id.tsv | 7 +- crates/ui-egui/src/i18n/it.tsv | 7 +- crates/ui-egui/src/i18n/ja.tsv | 7 +- crates/ui-egui/src/i18n/ka.tsv | 7 +- crates/ui-egui/src/i18n/ko.tsv | 7 +- crates/ui-egui/src/i18n/nl.tsv | 7 +- crates/ui-egui/src/i18n/pl.tsv | 7 +- crates/ui-egui/src/i18n/pt-br.tsv | 7 +- crates/ui-egui/src/i18n/ru.tsv | 7 +- crates/ui-egui/src/i18n/sv.tsv | 7 +- crates/ui-egui/src/i18n/tr.tsv | 7 +- crates/ui-egui/src/i18n/uk.tsv | 7 +- crates/ui-egui/src/i18n/vi.tsv | 7 +- crates/ui-egui/src/i18n/zh-hans.tsv | 7 +- crates/ui-egui/src/i18n/zh-hant.tsv | 7 +- crates/ui-egui/src/panels/brushes.rs | 16 ++-- crates/ui-egui/src/panels/brushes/tests.rs | 75 +++++++++++++++---- docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 36 files changed, 367 insertions(+), 81 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/brush_delete.rs create mode 100644 crates/ui-egui/src/dialogs/brush_delete/tests.rs diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 8ef171d326..7b37fea769 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -125,7 +125,7 @@ pub fn specs() -> Vec<CommandSpec> { "Select All Unused", [], None, - "{} → {names: [the brushes no stroke paints with, in library order]} (the Brushes panel selects them): strokes in the art (opacity masks included), symbols, graph designs, pattern tiles and graphic styles count, and so do strokes in the art of a brush that is used", + "{} → {names: [the brushes no stroke paints with, in library order]} (the Brushes panel selects them): strokes in the art (opacity masks included), symbols, graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and graphic styles count, and so do strokes in the art of a brush that is used", has_doc, brush_unused ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index 66dd546e90..f5e5c73fce 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -362,14 +362,15 @@ fn art_brushes(n: &Node, out: &mut Vec<String>) { } /// The brushes no stroke paints with. Strokes in the art (opacity masks included), symbols, graph -/// designs, pattern tiles and graphic styles count, and so do the strokes in the art of every brush -/// that a counted stroke paints with. +/// designs, pattern tiles and the tiles that pattern editing's Cancel puts back, and graphic styles +/// count, and so do the strokes in the art of every brush that a counted stroke paints with. pub(super) fn brush_unused(s: &mut Session, _: &Value) -> Result<Value> { let d = &s.doc()?.doc; let lib = brush::library(d); let mut todo = vec![]; let trees = d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)).chain(d.graph_designs.iter().map(|g| &g.art)); - trees.chain(d.patterns.iter().flat_map(|p| &p.art)).for_each(|n| art_brushes(n, &mut todo)); + let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref())); + trees.chain(patterns.flat_map(|p| &p.art)).for_each(|n| art_brushes(n, &mut todo)); d.graphic_styles.iter().for_each(|g| stroke_brushes(&g.appearance.items, &mut todo)); let mut used = BTreeSet::new(); while let Some(name) = todo.pop() { diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index c6a33ffc66..bba39230bc 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -457,6 +457,31 @@ fn brush_unused_lists_the_brushes_no_stroke_paints_with() { assert_eq!(unused(&mut s), ["3 pt. Round", "6 pt. Flat", "Charcoal"]); } +/// A stroke in the tile that pattern editing's Cancel puts back counts as a use, as `brush.delete` +/// clears it there. +#[test] +fn brush_unused_counts_pattern_edit_originals() { + let mut s = session(); + let id = rect(&mut s, 10.0, 10.0, 40.0, 20.0); + s.execute("brush.apply", &json!({"name": "6 pt. Flat", "ids": [id.0]})).unwrap(); + let name = s.execute("object.pattern.make", &json!({"ids": [id.0], "edit": false})).unwrap()["name"].clone(); + s.execute("brush.remove", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.pattern.edit", &json!({ "name": name })).unwrap(); + // The tile's copies in the editing layer are selected; only the tile kept for Cancel paints with the brush. + s.execute("brush.remove", &json!({})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let original = d.pattern_edit.as_ref().and_then(|pe| pe.original.as_ref()).expect("pattern edit original"); + assert_eq!(original.art.first().and_then(|n| n.appearance.stroke()).and_then(|k| k.brush.as_deref()), Some("6 pt. Flat")); + for pattern in &mut d.patterns { + for art in &mut pattern.art { + if let Some(stroke) = std::sync::Arc::make_mut(art).appearance.stroke_mut() { + stroke.brush = None; + } + } + } + assert!(!unused(&mut s).contains(&"6 pt. Flat".to_string())); +} + /// A brush counts as used when a stroke paints with it in an opacity mask, a symbol, a graph /// design, a pattern tile, a graphic style, or the art of a brush that is used. The art of a brush /// that is not used, its own strokes included, does not count. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 488cd1d956..b2a42af49b 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -12,6 +12,7 @@ pub mod action_set_options; pub mod artboard_options; pub mod blend_options; mod brush_art_options; +pub mod brush_delete; pub mod brush_options; pub mod color_balance; pub mod color_guide_options; @@ -293,6 +294,7 @@ registry! { FindFont: ["findFont"] => DialogSpec::window(crate::find_font::show, |app, _| crate::find_font::confirm(app)), SwatchOptions: [swatch_options::KIND] => swatch_options::SPEC, Confirm: [confirm::KIND] => confirm::SPEC, + BrushDelete: [brush_delete::KIND] => brush_delete::SPEC, Message: [confirm::MESSAGE] => confirm::MESSAGE_SPEC, Replace: [confirm::REPLACE] => confirm::REPLACE_SPEC, NewSwatch: [new_swatch::KIND] => new_swatch::SPEC, diff --git a/crates/ui-egui/src/dialogs/brush_delete.rs b/crates/ui-egui/src/dialogs/brush_delete.rs new file mode 100644 index 0000000000..9488d14bec --- /dev/null +++ b/crates/ui-egui/src/dialogs/brush_delete.rs @@ -0,0 +1,61 @@ +//! The Brushes panel's Delete Brush question ([`ask`]): Yes or No when none of the brushes is in +//! use, else Remove Strokes or Cancel. Yes and Remove Strokes run `brush.delete`, which leaves the +//! strokes that used the brushes as plain strokes. +//! +//! Fields: `message` (the question, shown as the heading), `used` (whether a brush is in use) and +//! `params` (the `brush.delete` params). + +use serde_json::{Value, json}; + +use super::{DialogAction, DialogSpec}; +use crate::VectorcraftApp; +use crate::state::Dialog; +use crate::widgets; + +/// The dialog kind of the Delete Brush question. +pub const KIND: &str = "brushDelete"; + +pub(super) const SPEC: DialogSpec = + DialogSpec { heading: |d| d.str("message"), body_with_actions: Some(body), confirm, ok: None, max_width: Some(540.0), ..DialogSpec::FORM }; + +/// Ask whether to delete the brushes `params` names (`used`: one of them is in use). +pub fn ask(app: &mut VectorcraftApp, params: Value, used: bool) { + let message = if used { + tl!("One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed.") + } else { + tl!("Delete the brush selection?") + }; + app.ui.dialog = Some(Dialog::new(KIND, json!({"params": params, "used": used, "message": message}))); +} + +fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let mut action = DialogAction::None; + ui.horizontal(|ui| { + if d.bool("used") { + if widgets::primary_button_enabled(ui, tl!("Remove Strokes"), true).clicked() { + action = DialogAction::Confirm; + } + if widgets::secondary_button(ui, tl!("Cancel")).clicked() { + action = DialogAction::Cancel; + } + } else { + if widgets::primary_button_enabled(ui, tl!("Yes"), true).clicked() { + action = DialogAction::Confirm; + } + if widgets::secondary_button(ui, tl!("No")).clicked() { + action = DialogAction::Cancel; + } + } + }); + action +} + +/// Closes before running, so a dialog the command opens stays open. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { + let params = d.fields.get("params").cloned().unwrap_or_else(|| json!({})); + app.ui.dialog = None; + app.run("brush.delete", params) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/brush_delete/tests.rs b/crates/ui-egui/src/dialogs/brush_delete/tests.rs new file mode 100644 index 0000000000..407351c794 --- /dev/null +++ b/crates/ui-egui/src/dialogs/brush_delete/tests.rs @@ -0,0 +1,71 @@ +use egui::{Pos2, Rect, pos2, vec2}; +use serde_json::json; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::Session; + +use super::*; + +fn frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>, time: f64) -> egui::FullOutput { + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); + let input = egui::RawInput { screen_rect, time: Some(time), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + out +} + +fn press(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, time: f64) { + frame(ctx, app, vec![], time); + let out = frame(ctx, app, vec![], time + 0.1); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("dialog accessibility tree").nodes; + let button = nodes.iter().find(|(_, node)| node.label().map(str::trim) == Some(label)); + let bounds = button.and_then(|(_, node)| node.bounds()).expect("visible button"); + let at = pos2(((bounds.x0 + bounds.x1) / 2.0) as f32, ((bounds.y0 + bounds.y1) / 2.0) as f32); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(ctx, app, vec![egui::Event::PointerMoved(at), button(true), button(false)], time + 0.2); +} + +fn context() -> egui::Context { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + ctx +} + +#[test] +fn visible_yes_and_no_buttons_control_unused_deletion() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let name = app.run("brush.list", json!({})).unwrap()["brushes"][0]["name"].as_str().unwrap().to_string(); + let ctx = context(); + let before = app.session.active().unwrap().history.undo.len(); + ask(&mut app, json!({"name": name}), false); + press(&ctx, &mut app, "No", 0.0); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().history.undo.len(), before); + assert!(app.run("brush.get", json!({"name": name})).is_ok()); + ask(&mut app, json!({"name": name}), false); + press(&ctx, &mut app, "Yes", 1.0); + assert!(app.run("brush.get", json!({"name": name})).is_err()); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); +} + +#[test] +fn visible_remove_strokes_and_cancel_buttons_control_used_deletion() { + for choice in ["Cancel", "Remove Strokes"] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let path = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap()); + let name = "10 pt. Oval"; + app.run("brush.apply", json!({"name": name})).unwrap(); + let before = app.session.active().unwrap().history.undo.len(); + let ctx = context(); + ask(&mut app, json!({"name": name}), true); + press(&ctx, &mut app, choice, 0.0); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + usize::from(choice != "Cancel")); + let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap(); + assert_eq!(stroke.brush.as_deref(), (choice == "Cancel").then_some(name)); + assert!(stroke.width > 0.0); + } +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 5a5efddad2..e423aab1a6 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -742,8 +742,6 @@ font-technology Variable Променливи Yes Да No Не Delete Tab Изтриване на табулация - Delete the brush “{name}”? Да се изтрие четката „{name}“? - Strokes using deleted brushes become plain strokes. Щрихите, които използват изтритите четки, стават обикновени щрихи. Delete the graphic style “{name}”? Изтриване на графичния стил „{name}“? Delete Theme Изтриване на тема Delete theme Изтриване на тема @@ -5901,6 +5899,11 @@ breakText Glyphs Глифи Gap 4 Разстояние 4 Dash 5 Тире 5 Gap 5 Разстояние 5 + Delete the brush selection? Да се изтрият избраните четки? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Една или повече от четките се използват и не могат да бъдат изтрити, докато щрихите им не бъдат разширени или премахнати. + Remove Strokes Премахване на щрихи + Yes Да + No Не # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Инструменти за подреждане Arrange in Grid… Подреждане в мрежа… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index da8c5d134e..6b48514683 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5931,6 +5931,11 @@ shape Open Otvoren @msg `follow` must be "average", "a" or "b" `follow` mora biti "average", "a" ili "b" @msg the paths have nothing to merge there putanje tu nemaju šta spojiti @msg the path is locked or hidden putanja je zaključana ili skrivena + Delete the brush selection? Izbrisati odabrane četkice? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Jedna ili više četkica se koristi i ne mogu se izbrisati dok se njihovi potezi ne prošire ili uklone. + Remove Strokes Ukloni poteze + Yes Da + No Ne # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Alati za raspoređivanje Arrange in Grid… Rasporedi u mrežu… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index cd1046755c..970625ac0e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1059,8 +1059,6 @@ Yes Sí No No Delete Tab Suprimeix la tabulació - Delete the brush “{name}”? Voleu suprimir el pinzell “{name}”? - Strokes using deleted brushes become plain strokes. Els traços que utilitzen pinzells suprimits esdevenen traços normals. Delete the graphic style “{name}”? Voleu suprimir l’estil gràfic “{name}”? Delete the library “{name}”? Voleu suprimir la biblioteca “{name}”? Delete Theme Suprimeix el tema @@ -6001,6 +5999,11 @@ breakText Glyphs Glifs Gap 4 Separació 4 Dash 5 Guió 5 Gap 5 Separació 5 + Delete the brush selection? Voleu suprimir la selecció de pinzells? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Un o més pinzells estan en ús i no es poden suprimir fins que els traços s’expandeixin o s’eliminin. + Remove Strokes Elimina els traços + Yes Sí + No No # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Eines d’organització Arrange in Grid… Organitza en quadrícula… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4ffe67aea9..bc8c6b09bd 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1558,8 +1558,6 @@ lighting Light Světlo Reverse Gradient Obrátit přechod Save to Swatches Uložit do vzorníku Delete Graphic Style (Alt-click: without asking) Odstranit grafický styl (Alt+kliknutí: bez dotazu) - Delete the brush “{name}”? Odstranit štětec „{name}“? - Strokes using deleted brushes become plain strokes. Tahy používající odstraněné štětce se změní na běžné tahy. Delete the graphic style “{name}”? Odstranit grafický styl „{name}“? Delete these {n} graphic styles? Odstranit tyto grafické styly ({n})? Delete this {n} graphic style? Odstranit tento grafický styl ({n})? @@ -6010,6 +6008,11 @@ breakText Glyphs Glyfy Gap 4 Mezera 4 Dash 5 Čárka 5 Gap 5 Mezera 5 + Delete the brush selection? Odstranit vybrané štětce? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Jeden nebo více štětců se používá a nelze je odstranit, dokud jejich tahy nebudou rozloženy nebo odebrány. + Remove Strokes Odebrat tahy + Yes Ano + No Ne # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Nástroje uspořádání Arrange in Grid… Uspořádat do mřížky… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index bce83c7bd6..fc45ef6e51 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1472,8 +1472,6 @@ lighting Light Lys Reverse Gradient Omvend gradient Save to Swatches Gem i farveprøver Delete Graphic Style (Alt-click: without asking) Slet grafisk typografi (Alt-klik: uden at spørge) - Delete the brush “{name}”? Slet penslen »{name}«? - Strokes using deleted brushes become plain strokes. Streger, der bruger slettede pensler, bliver almindelige streger. Delete the graphic style “{name}”? Slet den grafiske typografi »{name}«? Delete these {n} graphic styles? Slet disse {n} grafiske typografier? Delete this {n} graphic style? Slet denne {n} grafiske typografi? @@ -5915,6 +5913,11 @@ breakText Glyphs Glyffer Gap 4 Mellemrum 4 Dash 5 Streg 5 Gap 5 Mellemrum 5 + Delete the brush selection? Slet de valgte pensler? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. En eller flere pensler er i brug og kan ikke slettes, før deres streger er udvidet eller fjernet. + Remove Strokes Fjern streger + Yes Ja + No Nej # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Arrangeringsværktøjer Arrange in Grid… Arrangér i gitter… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9e837d8eb6..a36a57825e 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -736,8 +736,6 @@ font-technology Variable Variabel Yes Ja No Nein Delete Tab Tabulator löschen - Delete the brush “{name}”? Pinsel „{name}“ löschen? - Strokes using deleted brushes become plain strokes. Konturen mit gelöschten Pinseln werden zu einfachen Konturen. Delete the graphic style “{name}”? Grafikstil „{name}“ löschen? Delete Theme Thema löschen Delete theme Thema löschen @@ -5596,6 +5594,11 @@ breakText Glyphs Glyphen Gap 4 Lücke 4 Dash 5 Strich 5 Gap 5 Lücke 5 + Delete the brush selection? Ausgewählte Pinsel löschen? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Ein oder mehrere Pinsel werden verwendet und können erst gelöscht werden, wenn ihre Konturen umgewandelt oder entfernt wurden. + Remove Strokes Konturen entfernen + Yes Ja + No Nein # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Anordnungswerkzeuge Arrange in Grid… In Raster anordnen… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e5ac837751..7c9b2fa5c8 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -716,8 +716,6 @@ font-technology Variable Μεταβλητές Yes Ναι No Όχι Delete Tab Διαγραφή στηλοθέτη - Delete the brush “{name}”? Να διαγραφεί το πινέλο «{name}»; - Strokes using deleted brushes become plain strokes. Οι πινελιές που χρησιμοποιούν διαγραμμένα πινέλα γίνονται απλές πινελιές. Delete the graphic style “{name}”? Να διαγραφεί το στυλ γραφικών «{name}»; Delete Theme Διαγραφή θέματος Delete theme Διαγραφή θέματος @@ -5963,6 +5961,11 @@ breakText Glyphs Γλύφοι Gap 4 Διάκενο 4 Dash 5 Παύλα 5 Gap 5 Διάκενο 5 + Delete the brush selection? Να διαγραφούν τα επιλεγμένα πινέλα; + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Ένα ή περισσότερα πινέλα χρησιμοποιούνται και δεν μπορούν να διαγραφούν μέχρι να επεκταθούν ή να αφαιρεθούν τα περιγράμματά τους. + Remove Strokes Αφαίρεση περιγραμμάτων + Yes Ναι + No Όχι # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Εργαλεία διάταξης Arrange in Grid… Διάταξη σε πλέγμα… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 367692be2f..70e009d067 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -757,8 +757,6 @@ font-technology Variable Variables Yes Sí No No Delete Tab Eliminar tabulación - Delete the brush “{name}”? ¿Eliminar el pincel “{name}”? - Strokes using deleted brushes become plain strokes. Los trazos que usan pinceles eliminados se convierten en trazos simples. Delete the graphic style “{name}”? ¿Eliminar el estilo gráfico “{name}”? Delete Theme Eliminar tema Delete theme Eliminar tema @@ -5953,6 +5951,11 @@ breakText Glyphs Glifos Gap 4 Hueco 4 Dash 5 Guion 5 Gap 5 Hueco 5 + Delete the brush selection? ¿Eliminar los pinceles seleccionados? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Uno o más pinceles están en uso y no se pueden eliminar hasta expandir o quitar sus trazos. + Remove Strokes Quitar trazos + Yes Sí + No No # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Herramientas de organización Arrange in Grid… Organizar en cuadrícula… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d0b30760ac..51e68665ba 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1532,8 +1532,6 @@ lighting Light Valo Reverse Gradient Käännä liukuväri Save to Swatches Tallenna värimalleihin Delete Graphic Style (Alt-click: without asking) Poista grafiikkatyyli (Alt-napsautus: kysymättä) - Delete the brush “{name}”? Poistetaanko sivellin ”{name}”? - Strokes using deleted brushes become plain strokes. Poistettuja siveltimiä käyttävät viivat muuttuvat tavallisiksi viivoiksi. Delete the graphic style “{name}”? Poistetaanko grafiikkatyyli ”{name}”? Delete these {n} graphic styles? Poistetaanko nämä {n} grafiikkatyyliä? Delete this {n} graphic style? Poistetaanko tämä {n} grafiikkatyyli? @@ -6041,6 +6039,11 @@ breakText Glyphs Merkit Gap 4 Väli 4 Dash 5 Viiva 5 Gap 5 Väli 5 + Delete the brush selection? Poistetaanko valitut siveltimet? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Yksi tai useampi sivellin on käytössä eikä niitä voi poistaa ennen kuin niiden viivat on laajennettu tai poistettu. + Remove Strokes Poista viivat + Yes Kyllä + No Ei # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Järjestelytyökalut Arrange in Grid… Järjestä ruudukkoon… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index ab5fc9acd1..0c355f4785 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -759,8 +759,6 @@ font-technology Variable Variables Yes Oui No Non Delete Tab Supprimer la tabulation - Delete the brush “{name}”? Supprimer la forme « {name} » ? - Strokes using deleted brushes become plain strokes. Les contours utilisant des formes supprimées deviennent des contours simples. Delete the graphic style “{name}”? Supprimer le style graphique « {name} » ? Delete Theme Supprimer le thème Delete theme Supprimer le thème @@ -3703,7 +3701,6 @@ imageTrace Outline Contour @plural {n} item|{n} items {n} élément|{n} éléments @plural Color Table ({n} color)|Color Table ({n} colors) Table des couleurs ({n} couleur)|Table des couleurs ({n} couleurs) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Supprimer {n} style graphique ?|Supprimer ces {n} styles graphiques ? -@plural Delete this {n} brush?|Delete these {n} brushes? Supprimer {n} forme ?|Supprimer ces {n} formes ? @plural {n} Layer|{n} Layers {n} calque|{n} calques @plural {n} Object|{n} Objects {n} objet|{n} objets @plural {n} area highlighted|{n} areas highlighted {n} zone mise en évidence|{n} zones mises en évidence @@ -6009,6 +6006,11 @@ breakText Glyphs Glyphes Gap 4 Écart 4 Dash 5 Tiret 5 Gap 5 Écart 5 + Delete the brush selection? Supprimer les formes sélectionnées ? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Une ou plusieurs formes sont utilisées et ne peuvent pas être supprimées tant que leurs contours ne sont pas décomposés ou supprimés. + Remove Strokes Supprimer les contours + Yes Oui + No Non # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Outils de disposition Arrange in Grid… Disposer en grille… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e91e7dfe56..965e4ddb27 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -981,8 +981,6 @@ font-technology Variable Változó Yes Igen No Nem Delete Tab Tabulátor törlése - Delete the brush “{name}”? Törlöd ezt az ecsetet: „{name}”? - Strokes using deleted brushes become plain strokes. A törölt ecseteket használó körvonalak egyszerű körvonalakká válnak. Delete the graphic style “{name}”? Törlöd ezt a grafikai stílust: „{name}”? Delete the library “{name}”? Törlöd ezt a könyvtárat: „{name}”? Delete Theme Téma törlése @@ -5997,6 +5995,11 @@ breakText Glyphs Glifák Gap 4 Hézag 4 Dash 5 Vonal 5 Gap 5 Hézag 5 + Delete the brush selection? Törlöd a kijelölt ecseteket? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Egy vagy több ecset használatban van, és nem törölhető, amíg a körvonalait ki nem bontod vagy el nem távolítod. + Remove Strokes Körvonalak eltávolítása + Yes Igen + No Nem # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Elrendezőeszközök Arrange in Grid… Elrendezés rácsba… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 265da6fbee..ebfdabf544 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1472,8 +1472,6 @@ lighting Light Cahaya Reverse Gradient Balikkan gradien Save to Swatches Simpan ke swatch Delete Graphic Style (Alt-click: without asking) Hapus gaya grafis (Alt+klik: tanpa konfirmasi) - Delete the brush “{name}”? Hapus kuas “{name}”? - Strokes using deleted brushes become plain strokes. Goresan yang menggunakan kuas terhapus menjadi goresan biasa. Delete the graphic style “{name}”? Hapus gaya grafis “{name}”? Delete these {n} graphic styles? Hapus {n} gaya grafis ini? Delete this {n} graphic style? Hapus {n} gaya grafis ini? @@ -5915,6 +5913,11 @@ breakText Glyphs Glif Gap 4 Jarak 4 Dash 5 Garis 5 Gap 5 Jarak 5 + Delete the brush selection? Hapus kuas yang dipilih? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Satu atau beberapa kuas sedang digunakan dan tidak dapat dihapus sampai stroke-nya diperluas atau dihapus. + Remove Strokes Hapus Stroke + Yes Ya + No Tidak # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Alat penyusunan Arrange in Grid… Susun dalam grid… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index af6874bbe8..ffc95c4da3 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -757,8 +757,6 @@ font-technology Variable Variabili Yes Sì No No Delete Tab Elimina tabulazione - Delete the brush “{name}”? Eliminare il pennello “{name}”? - Strokes using deleted brushes become plain strokes. I tracciati che usano pennelli eliminati diventano tracciati semplici. Delete the graphic style “{name}”? Eliminare lo stile grafico “{name}”? Delete Theme Elimina tema Delete theme Elimina tema @@ -5630,6 +5628,11 @@ breakText Glyphs Glifi Gap 4 Spazio 4 Dash 5 Tratto 5 Gap 5 Spazio 5 + Delete the brush selection? Eliminare i pennelli selezionati? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Uno o più pennelli sono in uso e non possono essere eliminati finché le tracce non vengono espanse o rimosse. + Remove Strokes Rimuovi tracce + Yes Sì + No No # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Strumenti di disposizione Arrange in Grid… Disponi in griglia… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index f9ad60b875..754362ef57 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1308,8 +1308,6 @@ font-technology Variable バリアブル Delete Transparency Flattener Preset 透明の分割・統合プリセットを削除 Delete Width Point 幅ポイントを削除 Delete Workspace ワークスペースを削除 - Delete the brush “{name}”? ブラシ「{name}」を削除しますか? - Strokes using deleted brushes become plain strokes. 削除したブラシを使用する線は通常の線になります。 Delete the graphic style “{name}”? グラフィックスタイル「{name}」を削除しますか? Delete theme テーマを削除 Delete this saved preset この保存済みプリセットを削除 @@ -5696,6 +5694,11 @@ breakText Glyphs 字形 Gap 4 間隔 4 Dash 5 線分 5 Gap 5 間隔 5 + Delete the brush selection? 選択したブラシを削除しますか? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. 使用中のブラシが含まれています。線を拡張または削除するまでブラシを削除できません。 + Remove Strokes 線を削除 + Yes はい + No いいえ # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 配置ツール Arrange in Grid… グリッドに配置… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 7f6eb84ba3..b07dfd7fca 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1389,8 +1389,6 @@ lighting Light სინათლე Reverse Gradient გრადიენტის შებრუნება Save to Swatches ფერის ნიმუშებში შენახვა Delete Graphic Style (Alt-click: without asking) გრაფიკული სტილის წაშლა (Alt-დაწკაპუნებით: დაუკითხავად) - Delete the brush “{name}”? წაიშალოს ფუნჯი „{name}“? - Strokes using deleted brushes become plain strokes. წაშლილი ფუნჯებით დახატული შტრიხები ჩვეულებრივ შტრიხებად იქცევა. Delete the graphic style “{name}”? წაიშალოს გრაფიკული სტილი „{name}“? Delete these {n} graphic styles? წაიშალოს ეს გრაფიკული სტილები ({n})? Delete this {n} graphic style? წაიშალოს ეს გრაფიკული სტილი ({n})? @@ -6000,6 +5998,11 @@ breakText Glyphs გლიფები Gap 4 შუალედი 4 Dash 5 ტირე 5 Gap 5 შუალედი 5 + Delete the brush selection? წაიშალოს არჩეული ფუნჯები? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. ერთი ან მეტი ფუნჯი გამოიყენება და მათი წაშლა შეუძლებელია, სანამ კონტურები არ გაიშლება ან არ მოიხსნება. + Remove Strokes კონტურების მოხსნა + Yes დიახ + No არა # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools განლაგების ხელსაწყოები Arrange in Grid… ბადეში განლაგება… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index a64392ef3b..e487667b56 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1299,8 +1299,6 @@ font-technology Variable 가변 Delete Transparency Flattener Preset 투명도 병합 프리셋 삭제 Delete Width Point 너비 포인트 삭제 Delete Workspace 작업 영역 삭제 - Delete the brush “{name}”? 브러시 “{name}”을(를) 삭제하시겠습니까? - Strokes using deleted brushes become plain strokes. 삭제된 브러시를 사용한 선은 일반 선이 됩니다. Delete the graphic style “{name}”? 그래픽 스타일 “{name}”을(를) 삭제하시겠습니까? Delete theme 테마 삭제 Delete this saved preset 저장된 이 프리셋 삭제 @@ -5593,6 +5591,11 @@ breakText Glyphs 글리프 Gap 4 간격 4 Dash 5 대시 5 Gap 5 간격 5 + Delete the brush selection? 선택한 브러시를 삭제하시겠습니까? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. 하나 이상의 브러시가 사용 중이며 선을 확장하거나 제거할 때까지 삭제할 수 없습니다. + Remove Strokes 선 제거 + Yes 예 + No 아니요 # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 배치 도구 Arrange in Grid… 격자로 배치… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ed254e2a19..71d7a6d732 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1486,8 +1486,6 @@ lighting Light Licht Reverse Gradient Verloop omkeren Save to Swatches Opslaan in stalen Delete Graphic Style (Alt-click: without asking) Grafische stijl verwijderen (Alt-klik: zonder vragen) - Delete the brush “{name}”? Kwast „{name}” verwijderen? - Strokes using deleted brushes become plain strokes. Lijnen die verwijderde kwasten gebruiken, worden gewone lijnen. Delete the graphic style “{name}”? De grafische stijl „{name}” verwijderen? Delete these {n} graphic styles? Deze {n} grafische stijlen verwijderen? Delete this {n} graphic style? Deze {n} grafische stijl verwijderen? @@ -5959,6 +5957,11 @@ breakText Glyphs Glyphs Gap 4 Tussenruimte 4 Dash 5 Streepje 5 Gap 5 Tussenruimte 5 + Delete the brush selection? Geselecteerde kwasten verwijderen? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Een of meer kwasten zijn in gebruik en kunnen pas worden verwijderd als hun contouren zijn uitgebreid of verwijderd. + Remove Strokes Contouren verwijderen + Yes Ja + No Nee # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Schikgereedschappen Arrange in Grid… In raster schikken… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f2e5c5964b..7a606131ff 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1472,8 +1472,6 @@ lighting Light Światło Reverse Gradient Odwróć gradient Save to Swatches Zapisz w próbkach Delete Graphic Style (Alt-click: without asking) Usuń styl graficzny (kliknięcie z Alt: bez pytania) - Delete the brush “{name}”? Usunąć pędzel „{name}”? - Strokes using deleted brushes become plain strokes. Obrysy używające usuniętych pędzli stają się zwykłymi obrysami. Delete the graphic style “{name}”? Usunąć styl graficzny „{name}”? Delete these {n} graphic styles? Usunąć te style graficzne ({n})? Delete this {n} graphic style? Usunąć ten styl graficzny ({n})? @@ -5866,6 +5864,11 @@ breakText Glyphs Glify Gap 4 Odstęp 4 Dash 5 Kreska 5 Gap 5 Odstęp 5 + Delete the brush selection? Usunąć zaznaczone pędzle? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Co najmniej jeden pędzel jest używany i nie można go usunąć, dopóki jego obrysy nie zostaną rozszerzone lub usunięte. + Remove Strokes Usuń obrysy + Yes Tak + No Nie # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Narzędzia układania Arrange in Grid… Ułóż w siatce… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4d39287c57..e1044cbbd7 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -674,8 +674,6 @@ Delete Transparency Flattener Preset Excluir Predefinido de Achatamento de Transparência Delete Width Point Excluir Ponto de Largura Delete Workspace Excluir Espaço de Trabalho - Delete the brush “{name}”? Excluir o pincel “{name}”? - Strokes using deleted brushes become plain strokes. Traços que usam pincéis excluídos tornam-se traços simples. Delete the graphic style “{name}”? Excluir o estilo gráfico “{name}”? Delete theme Excluir tema Delete this saved preset Excluir este predefinido salvo @@ -5930,6 +5928,11 @@ breakText Glyphs Glifos Gap 4 Lacuna 4 Dash 5 Traço 5 Gap 5 Lacuna 5 + Delete the brush selection? Excluir os pincéis selecionados? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Um ou mais pincéis estão em uso e não podem ser excluídos até que seus traçados sejam expandidos ou removidos. + Remove Strokes Remover Traçados + Yes Sim + No Não # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Ferramentas de Organização Arrange in Grid… Organizar em Grade… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 952171bbf1..d9cede6983 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -755,8 +755,6 @@ font-technology Variable Вариативные Yes Да No Нет Delete Tab Удалить табуляцию - Delete the brush “{name}”? Удалить кисть «{name}»? - Strokes using deleted brushes become plain strokes. Обводки, использующие удалённые кисти, становятся обычными обводками. Delete the graphic style “{name}”? Удалить графический стиль «{name}»? Delete Theme Удалить тему Delete theme Удалить тему @@ -5988,6 +5986,11 @@ breakText Glyphs Глифы Gap 4 Зазор 4 Dash 5 Штрих 5 Gap 5 Зазор 5 + Delete the brush selection? Удалить выбранные кисти? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Одна или несколько кистей используются и не могут быть удалены, пока их обводки не будут разобраны или убраны. + Remove Strokes Убрать обводки + Yes Да + No Нет # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Инструменты размещения Arrange in Grid… Разместить по сетке… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 9f24f8e02c..68239d409b 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -744,8 +744,6 @@ font-technology Variable Variabla Yes Ja No Nej Delete Tab Radera tabb - Delete the brush “{name}”? Radera penseln ”{name}”? - Strokes using deleted brushes become plain strokes. Linjer som använder borttagna penslar blir vanliga linjer. Delete the graphic style “{name}”? Radera grafikstilen ”{name}”? Delete Theme Radera tema Delete theme Radera tema @@ -6063,6 +6061,11 @@ breakText Glyphs Glyfer Gap 4 Mellanrum 4 Dash 5 Streck 5 Gap 5 Mellanrum 5 + Delete the brush selection? Radera de valda penslarna? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. En eller flera penslar används och kan inte raderas förrän deras konturer har expanderats eller tagits bort. + Remove Strokes Ta bort konturer + Yes Ja + No Nej # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Ordningsverktyg Arrange in Grid… Ordna i rutnät… diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 91fd8143d1..44cc14ba51 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -736,8 +736,6 @@ font-technology Variable Değişken Yes Evet No Hayır Delete Tab Sekmeyi Sil - Delete the brush “{name}”? “{name}” fırçası silinsin mi? - Strokes using deleted brushes become plain strokes. Silinen fırçaları kullanan konturlar düz konturlara dönüşür. Delete the graphic style “{name}”? “{name}” grafik stili silinsin mi? Delete Theme Temayı Sil Delete theme Temayı sil @@ -5968,6 +5966,11 @@ breakText Glyphs Glifler Gap 4 Boşluk 4 Dash 5 Çizgi 5 Gap 5 Boşluk 5 + Delete the brush selection? Seçili fırçalar silinsin mi? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Bir veya daha fazla fırça kullanılıyor ve konturları genişletilmeden veya kaldırılmadan silinemez. + Remove Strokes Konturları Kaldır + Yes Evet + No Hayır # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Düzenleme Araçları Arrange in Grid… Izgarada Düzenle… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 750796afe1..271b96793e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -751,8 +751,6 @@ font-technology Variable Варіативні Yes Так No Ні Delete Tab Видалити табуляцію - Delete the brush “{name}”? Видалити пензель «{name}»? - Strokes using deleted brushes become plain strokes. Обведення, що використовують видалені пензлі, стають звичайними обведеннями. Delete the graphic style “{name}”? Видалити графічний стиль «{name}»? Delete Theme Видалити тему Delete theme Видалити тему @@ -5610,6 +5608,11 @@ breakText Glyphs Гліфи Gap 4 Проміжок 4 Dash 5 Штрих 5 Gap 5 Проміжок 5 + Delete the brush selection? Видалити вибрані пензлі? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Один або кілька пензлів використовуються і не можуть бути видалені, доки їхні обведення не буде розібрано або забрано. + Remove Strokes Забрати обведення + Yes Так + No Ні # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Інструменти розміщення Arrange in Grid… Розмістити сіткою… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 494b40265c..66978c3703 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -877,8 +877,6 @@ font-technology Variable Biến thiên Yes Có No Không Delete Tab Xóa tab - Delete the brush “{name}”? Xóa cọ “{name}”? - Strokes using deleted brushes become plain strokes. Các nét dùng cọ đã xóa trở thành nét thông thường. Delete the graphic style “{name}”? Xóa kiểu đồ họa “{name}”? Delete the library “{name}”? Xóa thư viện “{name}”? Delete Theme Xóa bộ màu @@ -5612,6 +5610,11 @@ breakText Glyphs Glyph Gap 4 Khoảng hở 4 Dash 5 Nét 5 Gap 5 Khoảng hở 5 + Delete the brush selection? Xóa các cọ đã chọn? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Một hoặc nhiều cọ đang được sử dụng và không thể xóa cho đến khi nét được mở rộng hoặc gỡ bỏ. + Remove Strokes Gỡ nét + Yes Có + No Không # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Công cụ sắp xếp Arrange in Grid… Sắp xếp theo lưới… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 105fefd26d..85e1ffd3d9 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -700,8 +700,6 @@ Yes 是 No 否 Delete Tab 删除制表位 - Delete the brush “{name}”? 要删除画笔“{name}”吗? - Strokes using deleted brushes become plain strokes. 使用已删除画笔的描边会变成普通描边。 Delete the graphic style “{name}”? 要删除图形样式“{name}”吗? Delete Theme 删除主题 Delete theme 删除主题 @@ -5852,6 +5850,11 @@ breakText Glyphs 字形 Gap 4 间隔 4 Dash 5 虚线 5 Gap 5 间隔 5 + Delete the brush selection? 删除选中的画笔吗? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. 一个或多个画笔正在使用中,必须先扩展或移除其描边才能删除。 + Remove Strokes 移除描边 + Yes 是 + No 否 # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 排列工具 Arrange in Grid… 按网格排列… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 7ffb1831a4..44e077e904 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -719,8 +719,6 @@ font-technology Variable 可變 Yes 是 No 否 Delete Tab 刪除定位點 - Delete the brush “{name}”? 要刪除筆刷「{name}」嗎? - Strokes using deleted brushes become plain strokes. 使用已刪除筆刷的筆畫會變成一般筆畫。 Delete the graphic style “{name}”? 要刪除繪圖樣式「{name}」嗎? Delete Theme 刪除主題 Delete theme 刪除主題 @@ -5649,6 +5647,11 @@ breakText Glyphs 字符 Gap 4 間隙 4 Dash 5 虛線 5 Gap 5 間隙 5 + Delete the brush selection? 要刪除選取的筆刷嗎? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. 一個或多個筆刷正在使用中,必須先擴展或移除其筆畫才能刪除。 + Remove Strokes 移除筆畫 + Yes 是 + No 否 # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 排列工具 Arrange in Grid… 依格狀排列… diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index b734047305..279677527f 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -204,9 +204,15 @@ fn run_on(app: &mut VectorcraftApp, id: &str, names: &[String]) { app.run(id, p).ok(); } -/// Delete `names` after asking, or immediately when the bottom button was Alt-clicked. +/// Delete `names` after asking: Yes or No when none of them is in use, else Remove Strokes or +/// Cancel. With `now` (Alt-click on the bottom button), brushes that are not in use go at once. fn delete(app: &mut VectorcraftApp, names: &[String], now: bool) { - if now { + let Ok(unused) = app.run("brush.unused", json!({})) else { + return; + }; + let unused = unused.get("names").and_then(Value::as_array).cloned().unwrap_or_default(); + let used = names.iter().any(|name| !unused.iter().any(|n| n.as_str() == Some(name))); + if now && !used { run_on(app, "brush.delete", names); return; } @@ -214,11 +220,7 @@ fn delete(app: &mut VectorcraftApp, names: &[String], now: bool) { [name] => json!({ "name": name }), _ => json!({ "names": names }), }; - let message = match names { - [name] => crate::i18n::fmt(tl!("Delete the brush “{name}”?"), &[("name", name)]), - _ => crate::i18n::tn(names.len() as u64, "Delete this {n} brush?", "Delete these {n} brushes?"), - }; - crate::dialogs::confirm::ask(app, &message, tl!("Strokes using deleted brushes become plain strokes."), "brush.delete", params); + crate::dialogs::brush_delete::ask(app, params, used); } /// The names in `list` in the order the panel shows them: by type in [`KINDS`] order, without the diff --git a/crates/ui-egui/src/panels/brushes/tests.rs b/crates/ui-egui/src/panels/brushes/tests.rs index 421c0162a4..c4b794677a 100644 --- a/crates/ui-egui/src/panels/brushes/tests.rs +++ b/crates/ui-egui/src/panels/brushes/tests.rs @@ -158,22 +158,25 @@ fn delete_button(ctx: &egui::Context, app: &mut VectorcraftApp, modifiers: egui: fn assert_delete_dialog(app: &VectorcraftApp, message: &str) { let d = app.ui.dialog.as_ref().expect("Delete Brush asks first"); - assert_eq!(d.kind, crate::dialogs::confirm::KIND); + assert_eq!(d.kind, crate::dialogs::brush_delete::KIND); assert_eq!(d.str("message"), message); - assert_eq!(d.str("detail"), "Strokes using deleted brushes become plain strokes."); + assert_eq!(d.bool("used"), message.starts_with("One or more")); } +/// Deleting several unused brushes asks one question about the selection, with no count in it. #[test] -fn deleting_five_brushes_uses_polish_many_form() { +fn deleting_five_brushes_uses_one_selection_question() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let five: Vec<String> = names(&mut app).into_iter().take(5).collect(); + assert_eq!(five.len(), 5); let previous = crate::i18n::current(); let polish = crate::i18n::Lang::from_code("pl").unwrap(); crate::i18n::set_current(polish); - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - let names: Vec<String> = (1..=5).map(|n| format!("Brush {n}")).collect(); - delete(&mut app, &names, false); + delete(&mut app, &five, false); let message = app.ui.dialog.as_ref().map(|d| d.str("message")); crate::i18n::set_current(previous); - assert_eq!(message, Some("Usunąć 5 pędzli?".to_string())); + assert_eq!(message, Some("Usunąć zaznaczone pędzle?".to_string())); } /// Click the panel menu's item `label` (frames at `time`, `time + 0.5`). @@ -223,7 +226,7 @@ fn shift_and_command_clicks_select_brushes_for_delete_and_duplicate() { assert_eq!(undo_count(&app), before.1 + 1); // The bottom bar's last button, Delete Brush. delete_button(&ctx, &mut app, egui::Modifiers::NONE, 5.0); - assert_delete_dialog(&app, "Delete these 2 brushes?"); + assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); assert_eq!(names(&mut app), [before.0.clone(), copies.to_vec()].concat()); assert_eq!(brush_of(&app, rect).as_deref(), Some(three[0].as_str())); assert_eq!(undo_count(&app), before.1 + 1); @@ -263,7 +266,7 @@ fn selecting_other_art_ends_the_brush_multi_selection() { let out = frame_with(&ctx, &mut app, vec![], egui::Modifiers::NONE, 4.0, show); assert_eq!(lit_tiles(&out), [1]); menu_click(&ctx, &mut app, "Delete Brush", 5.0); - assert_delete_dialog(&app, &format!("Delete the brush “{}”?", three[1])); + assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); assert!(names(&mut app).contains(&three[1])); crate::dialogs::confirm(&mut app).unwrap(); let left = names(&mut app); @@ -332,7 +335,7 @@ fn select_all_unused_selects_the_brushes_no_stroke_paints_with() { let on: Vec<usize> = (0..tiles.len()).filter(|i| lit(&ctx, &out).contains(&tiles[*i])).collect(); assert_eq!(on, (0..tiles.len()).filter(|i| *i != 1).collect::<Vec<_>>()); menu_click(&ctx, &mut app, "Delete Brush", 3.0); - assert_delete_dialog(&app, &format!("Delete these {} brushes?", list.len() - 1)); + assert_delete_dialog(&app, "Delete the brush selection?"); assert_eq!(names(&mut app).len(), list.len()); crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(names(&mut app), [list[1].0.clone()]); @@ -349,7 +352,7 @@ fn delete_button_cancel_keeps_selected_brushes_strokes_and_history() { let (three, _) = select_three(&ctx, &mut app, rect); let before = (names(&mut app), brush_of(&app, rect), undo_count(&app)); delete_button(&ctx, &mut app, egui::Modifiers::NONE, 3.0); - assert_delete_dialog(&app, "Delete these 3 brushes?"); + assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); assert_eq!((names(&mut app), brush_of(&app, rect), undo_count(&app)), before); crate::dialogs::cancel(&mut app); assert!(app.ui.dialog.is_none()); @@ -364,7 +367,7 @@ fn delete_button_cancel_keeps_selected_brushes_strokes_and_history() { } #[test] -fn alt_delete_button_removes_selected_brushes_without_dialog() { +fn alt_delete_button_asks_when_a_selected_brush_is_used() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); let rect = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap()); @@ -373,16 +376,56 @@ fn alt_delete_button_removes_selected_brushes_without_dialog() { let (three, _) = select_three(&ctx, &mut app, rect); let before = undo_count(&app); delete_button(&ctx, &mut app, egui::Modifiers::NONE, 3.0); - assert_delete_dialog(&app, "Delete these 3 brushes?"); + assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); crate::dialogs::cancel(&mut app); delete_button(&ctx, &mut app, egui::Modifiers::ALT, 4.0); - assert!(app.ui.dialog.is_none()); + assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); + crate::dialogs::cancel(&mut app); let left = names(&mut app); - assert!(three.iter().all(|name| !left.contains(name))); - assert_eq!(brush_of(&app, rect), None); + assert!(three.iter().all(|name| left.contains(name))); + assert_eq!(brush_of(&app, rect).as_deref(), Some(three[0].as_str())); + assert_eq!(undo_count(&app), before); +} + +#[test] +fn alt_delete_button_deletes_unused_brush_without_a_question() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let first = names(&mut app)[0].clone(); + let out = frame_with(&ctx, &mut app, vec![], egui::Modifiers::NONE, 0.0, show); + let tile = clickable(&out).into_iter().find(|(label, _)| label.as_deref() == Some(first.as_str())).expect("brush tile").1.center(); + click(&ctx, &mut app, tile, egui::Modifiers::NONE, 1.0, show); + let before = undo_count(&app); + delete_button(&ctx, &mut app, egui::Modifiers::ALT, 2.0); + assert!(app.ui.dialog.is_none()); + assert!(!names(&mut app).contains(&first)); assert_eq!(undo_count(&app), before + 1); } +#[test] +fn menu_delete_used_brush_requires_remove_strokes_or_cancel() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let rect = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap()); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let (three, _) = select_three(&ctx, &mut app, rect); + let before = undo_count(&app); + menu_click(&ctx, &mut app, "Delete Brush", 3.0); + assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); + crate::dialogs::cancel(&mut app); + assert_eq!(undo_count(&app), before); + assert_eq!(brush_of(&app, rect).as_deref(), Some(three[0].as_str())); + menu_click(&ctx, &mut app, "Delete Brush", 4.0); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(undo_count(&app), before + 1); + assert_eq!(brush_of(&app, rect), None); + assert!(app.session.active().unwrap().doc.node(rect).unwrap().appearance.stroke().is_some()); + assert!(three.iter().all(|name| !names(&mut app).contains(name))); +} + #[test] fn art_dropped_on_the_panel_becomes_an_art_brush_and_a_brush_drags_out() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/docs/mcp.md b/docs/mcp.md index 6f342c98cd..1f843271e9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1557,8 +1557,10 @@ already walks Image Trace. Short agent entry points: name they are given, as `symbol.options` trims `newName`; a blank one gives "New Symbol" or "<name> copy". - The Brushes panel menu's Select All Unused: `brush.unused` (a query) lists the brushes no stroke paints with, in library order, and the panel selects them. Strokes in the art (opacity masks included), symbols, graph designs, - pattern tiles and graphic styles count, and so do the strokes in the art of a brush that is used. The art of a brush - that is not used does not count, so a brush whose own art is the only art that paints with it is listed. + pattern tiles (with the tiles that pattern editing's Cancel puts back) and graphic styles count, and so do the + strokes in the art of a brush that is used. The art of a brush that is not used does not count, so a brush whose own + art is the only art that paints with it is listed. The panel's Delete Brush asks Yes/No when every brush it deletes + is unused, and offers Remove Strokes or Cancel when one of them is in use. - Brushes: `brush.list`, `brush.get {name}`, `brush.apply {name, ids?}`, `brush.new {type, name?, params?, ids?}`, `brush.setCurrent {name}`, `brush.options {name, params?, newName?}`, `brush.delete {name} | {names}`, `brush.duplicate {name, newName?} | {names}`, `brush.freehand`, `object.expandBrush {ids?}`. `brush.new`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ab9b96f4b3..a035815286 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -962,7 +962,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (<https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html>). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). In the Brushes panel, Shift-click selects a range of brushes and Ctrl/Cmd-click adds or removes one. Delete Brush and Duplicate Brush then act on all of them (`brush.delete {names}`, `brush.duplicate {names}`). - The bottom Delete Brush button and the panel menu ask before deleting; Alt-click (Option-click on macOS) on the button deletes without asking. + The Brushes panel's Delete Brush button and panel menu item ask "Delete the brush selection?" with Yes and No when none of the brushes is in use. Alt-click (Option-click on macOS) on the button deletes them without asking, as the [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists ("Delete without confirmation (except for Layers panel)"). When a stroke uses one of the brushes, the button, Alt-click and the menu item all ask with Remove Strokes and Cancel; Remove Strokes deletes the brushes and the strokes that used them become plain strokes. Tests: `panels::brushes::tests`, `dialogs::brush_delete::tests`. Document Info has a Brushes category after Graphic Styles. It lists the Brushes panel's brushes, or with Selection Only it lists the brushes that the selected objects' strokes use. The Document Info report and Package's report list them too (`document.info {category: "brushes"}`, `brushNames`). Document Info has a Repeat Objects category after Embedded Images. It lists each radial, grid and mirror Repeat object by name with its kind and the number of instances it makes. For a grid it gives the rows and columns instead, followed by the number of instances it draws when that is fewer. With Selection Only it lists the Repeat objects in the selection. The Document Info report and Package's report list them too (`document.info {category: "repeats"}`, `repeatObjects`). The Brushes panel menu's Select All Unused selects the brushes that are not used in the document, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. A brush counts as used when a stroke paints with it in the art (opacity masks included), in symbols, graph designs, pattern tiles or graphic styles, or in the art of a used brush (`brush.unused`). From 3937473e54b40ecde00826fae336f7fb9d71ec7f Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 22:11:51 -0700 Subject: [PATCH 130/260] Brushes: the Delete Brush question for brushes in use no longer mentions expanding strokes The dialog offers Remove Strokes and Cancel, so the question asks only about taking the brushes off the strokes. Both questions are reworded in every catalog. --- crates/ui-egui/src/dialogs/brush_delete.rs | 4 ++-- crates/ui-egui/src/i18n/bg.tsv | 4 ++-- crates/ui-egui/src/i18n/bs.tsv | 4 ++-- crates/ui-egui/src/i18n/ca.tsv | 4 ++-- crates/ui-egui/src/i18n/cs.tsv | 4 ++-- crates/ui-egui/src/i18n/da.tsv | 4 ++-- crates/ui-egui/src/i18n/de.tsv | 4 ++-- crates/ui-egui/src/i18n/el.tsv | 4 ++-- crates/ui-egui/src/i18n/es.tsv | 4 ++-- crates/ui-egui/src/i18n/fi.tsv | 4 ++-- crates/ui-egui/src/i18n/fr.tsv | 4 ++-- crates/ui-egui/src/i18n/hu.tsv | 4 ++-- crates/ui-egui/src/i18n/id.tsv | 4 ++-- crates/ui-egui/src/i18n/it.tsv | 4 ++-- crates/ui-egui/src/i18n/ja.tsv | 4 ++-- crates/ui-egui/src/i18n/ka.tsv | 4 ++-- crates/ui-egui/src/i18n/ko.tsv | 4 ++-- crates/ui-egui/src/i18n/nl.tsv | 4 ++-- crates/ui-egui/src/i18n/pl.tsv | 4 ++-- crates/ui-egui/src/i18n/pt-br.tsv | 4 ++-- crates/ui-egui/src/i18n/ru.tsv | 4 ++-- crates/ui-egui/src/i18n/sv.tsv | 4 ++-- crates/ui-egui/src/i18n/tr.tsv | 4 ++-- crates/ui-egui/src/i18n/uk.tsv | 4 ++-- crates/ui-egui/src/i18n/vi.tsv | 4 ++-- crates/ui-egui/src/i18n/zh-hans.tsv | 4 ++-- crates/ui-egui/src/i18n/zh-hant.tsv | 4 ++-- crates/ui-egui/src/panels/brushes/tests.rs | 19 +++++++++++-------- docs/target-app-parity.md | 2 +- 29 files changed, 66 insertions(+), 63 deletions(-) diff --git a/crates/ui-egui/src/dialogs/brush_delete.rs b/crates/ui-egui/src/dialogs/brush_delete.rs index 9488d14bec..ee4d6c964e 100644 --- a/crates/ui-egui/src/dialogs/brush_delete.rs +++ b/crates/ui-egui/src/dialogs/brush_delete.rs @@ -21,9 +21,9 @@ pub(super) const SPEC: DialogSpec = /// Ask whether to delete the brushes `params` names (`used`: one of them is in use). pub fn ask(app: &mut VectorcraftApp, params: Value, used: bool) { let message = if used { - tl!("One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed.") + tl!("Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes?") } else { - tl!("Delete the brush selection?") + tl!("Delete the selected brushes?") }; app.ui.dialog = Some(Dialog::new(KIND, json!({"params": params, "used": used, "message": message}))); } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index e423aab1a6..43cef9353d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5899,8 +5899,8 @@ breakText Glyphs Глифи Gap 4 Разстояние 4 Dash 5 Тире 5 Gap 5 Разстояние 5 - Delete the brush selection? Да се изтрият избраните четки? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Една или повече от четките се използват и не могат да бъдат изтрити, докато щрихите им не бъдат разширени или премахнати. + Delete the selected brushes? Да се изтрият избраните четки? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Щрихи използват една или повече от тези четки. Да се премахнат ли четките от тези щрихи и да се изтрият четките? Remove Strokes Премахване на щрихи Yes Да No Не diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 6b48514683..0deb3e7c36 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5931,8 +5931,8 @@ shape Open Otvoren @msg `follow` must be "average", "a" or "b" `follow` mora biti "average", "a" ili "b" @msg the paths have nothing to merge there putanje tu nemaju šta spojiti @msg the path is locked or hidden putanja je zaključana ili skrivena - Delete the brush selection? Izbrisati odabrane četkice? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Jedna ili više četkica se koristi i ne mogu se izbrisati dok se njihovi potezi ne prošire ili uklone. + Delete the selected brushes? Izbrisati odabrane četkice? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Potezi koriste jednu ili više ovih četkica. Ukloniti četkice s tih poteza i izbrisati četkice? Remove Strokes Ukloni poteze Yes Da No Ne diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 970625ac0e..a83e611a34 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5999,8 +5999,8 @@ breakText Glyphs Glifs Gap 4 Separació 4 Dash 5 Guió 5 Gap 5 Separació 5 - Delete the brush selection? Voleu suprimir la selecció de pinzells? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Un o més pinzells estan en ús i no es poden suprimir fins que els traços s’expandeixin o s’eliminin. + Delete the selected brushes? Voleu suprimir els pinzells seleccionats? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Hi ha traços que fan servir un o més d’aquests pinzells. Voleu treure els pinzells d’aquests traços i suprimir els pinzells? Remove Strokes Elimina els traços Yes Sí No No diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index bc8c6b09bd..6fac8c5586 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6008,8 +6008,8 @@ breakText Glyphs Glyfy Gap 4 Mezera 4 Dash 5 Čárka 5 Gap 5 Mezera 5 - Delete the brush selection? Odstranit vybrané štětce? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Jeden nebo více štětců se používá a nelze je odstranit, dokud jejich tahy nebudou rozloženy nebo odebrány. + Delete the selected brushes? Odstranit vybrané štětce? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Tahy používají jeden nebo více z těchto štětců. Odebrat štětce z těchto tahů a odstranit štětce? Remove Strokes Odebrat tahy Yes Ano No Ne diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index fc45ef6e51..ef3b48df54 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5913,8 +5913,8 @@ breakText Glyphs Glyffer Gap 4 Mellemrum 4 Dash 5 Streg 5 Gap 5 Mellemrum 5 - Delete the brush selection? Slet de valgte pensler? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. En eller flere pensler er i brug og kan ikke slettes, før deres streger er udvidet eller fjernet. + Delete the selected brushes? Slet de valgte pensler? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Streger bruger en eller flere af disse pensler. Fjern penslerne fra stregerne, og slet penslerne? Remove Strokes Fjern streger Yes Ja No Nej diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index a36a57825e..9028735e09 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5594,8 +5594,8 @@ breakText Glyphs Glyphen Gap 4 Lücke 4 Dash 5 Strich 5 Gap 5 Lücke 5 - Delete the brush selection? Ausgewählte Pinsel löschen? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Ein oder mehrere Pinsel werden verwendet und können erst gelöscht werden, wenn ihre Konturen umgewandelt oder entfernt wurden. + Delete the selected brushes? Ausgewählte Pinsel löschen? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturen verwenden einen oder mehrere dieser Pinsel. Pinsel von diesen Konturen entfernen und die Pinsel löschen? Remove Strokes Konturen entfernen Yes Ja No Nein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7c9b2fa5c8..b8bd5f396b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5961,8 +5961,8 @@ breakText Glyphs Γλύφοι Gap 4 Διάκενο 4 Dash 5 Παύλα 5 Gap 5 Διάκενο 5 - Delete the brush selection? Να διαγραφούν τα επιλεγμένα πινέλα; - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Ένα ή περισσότερα πινέλα χρησιμοποιούνται και δεν μπορούν να διαγραφούν μέχρι να επεκταθούν ή να αφαιρεθούν τα περιγράμματά τους. + Delete the selected brushes? Να διαγραφούν τα επιλεγμένα πινέλα; + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Περιγράμματα χρησιμοποιούν ένα ή περισσότερα από αυτά τα πινέλα. Να αφαιρεθούν τα πινέλα από αυτά τα περιγράμματα και να διαγραφούν τα πινέλα; Remove Strokes Αφαίρεση περιγραμμάτων Yes Ναι No Όχι diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 70e009d067..ac1e149df1 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5951,8 +5951,8 @@ breakText Glyphs Glifos Gap 4 Hueco 4 Dash 5 Guion 5 Gap 5 Hueco 5 - Delete the brush selection? ¿Eliminar los pinceles seleccionados? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Uno o más pinceles están en uso y no se pueden eliminar hasta expandir o quitar sus trazos. + Delete the selected brushes? ¿Eliminar los pinceles seleccionados? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Algunos trazos usan uno o más de estos pinceles. ¿Quitar los pinceles de esos trazos y eliminar los pinceles? Remove Strokes Quitar trazos Yes Sí No No diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 51e68665ba..13107e11ec 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6039,8 +6039,8 @@ breakText Glyphs Merkit Gap 4 Väli 4 Dash 5 Viiva 5 Gap 5 Väli 5 - Delete the brush selection? Poistetaanko valitut siveltimet? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Yksi tai useampi sivellin on käytössä eikä niitä voi poistaa ennen kuin niiden viivat on laajennettu tai poistettu. + Delete the selected brushes? Poistetaanko valitut siveltimet? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Viivat käyttävät yhtä tai useampaa näistä siveltimistä. Irrotetaanko siveltimet näistä viivoista ja poistetaanko siveltimet? Remove Strokes Poista viivat Yes Kyllä No Ei diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 0c355f4785..f80a70246a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6006,8 +6006,8 @@ breakText Glyphs Glyphes Gap 4 Écart 4 Dash 5 Tiret 5 Gap 5 Écart 5 - Delete the brush selection? Supprimer les formes sélectionnées ? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Une ou plusieurs formes sont utilisées et ne peuvent pas être supprimées tant que leurs contours ne sont pas décomposés ou supprimés. + Delete the selected brushes? Supprimer les formes sélectionnées ? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Des contours utilisent une ou plusieurs de ces formes. Retirer les formes de ces contours et supprimer les formes ? Remove Strokes Supprimer les contours Yes Oui No Non diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 965e4ddb27..3e72e0c398 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5995,8 +5995,8 @@ breakText Glyphs Glifák Gap 4 Hézag 4 Dash 5 Vonal 5 Gap 5 Hézag 5 - Delete the brush selection? Törlöd a kijelölt ecseteket? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Egy vagy több ecset használatban van, és nem törölhető, amíg a körvonalait ki nem bontod vagy el nem távolítod. + Delete the selected brushes? Törlöd a kijelölt ecseteket? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Körvonalak használnak egyet vagy többet ezek közül az ecsetek közül. Leveszed az ecseteket ezekről a körvonalakról, és törlöd az ecseteket? Remove Strokes Körvonalak eltávolítása Yes Igen No Nem diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index ebfdabf544..00bbfac314 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5913,8 +5913,8 @@ breakText Glyphs Glif Gap 4 Jarak 4 Dash 5 Garis 5 Gap 5 Jarak 5 - Delete the brush selection? Hapus kuas yang dipilih? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Satu atau beberapa kuas sedang digunakan dan tidak dapat dihapus sampai stroke-nya diperluas atau dihapus. + Delete the selected brushes? Hapus kuas yang dipilih? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Stroke menggunakan satu atau beberapa kuas ini. Lepaskan kuas dari stroke tersebut dan hapus kuasnya? Remove Strokes Hapus Stroke Yes Ya No Tidak diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ffc95c4da3..81b4ec79fa 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5628,8 +5628,8 @@ breakText Glyphs Glifi Gap 4 Spazio 4 Dash 5 Tratto 5 Gap 5 Spazio 5 - Delete the brush selection? Eliminare i pennelli selezionati? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Uno o più pennelli sono in uso e non possono essere eliminati finché le tracce non vengono espanse o rimosse. + Delete the selected brushes? Eliminare i pennelli selezionati? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Alcune tracce usano uno o più di questi pennelli. Rimuovere i pennelli da queste tracce ed eliminare i pennelli? Remove Strokes Rimuovi tracce Yes Sì No No diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 754362ef57..3064294fd4 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5694,8 +5694,8 @@ breakText Glyphs 字形 Gap 4 間隔 4 Dash 5 線分 5 Gap 5 間隔 5 - Delete the brush selection? 選択したブラシを削除しますか? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. 使用中のブラシが含まれています。線を拡張または削除するまでブラシを削除できません。 + Delete the selected brushes? 選択したブラシを削除しますか? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? これらのブラシの 1 つ以上が線で使われています。それらの線からブラシを外して、ブラシを削除しますか? Remove Strokes 線を削除 Yes はい No いいえ diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b07dfd7fca..2d65308cba 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5998,8 +5998,8 @@ breakText Glyphs გლიფები Gap 4 შუალედი 4 Dash 5 ტირე 5 Gap 5 შუალედი 5 - Delete the brush selection? წაიშალოს არჩეული ფუნჯები? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. ერთი ან მეტი ფუნჯი გამოიყენება და მათი წაშლა შეუძლებელია, სანამ კონტურები არ გაიშლება ან არ მოიხსნება. + Delete the selected brushes? წაიშალოს არჩეული ფუნჯები? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? კონტურები იყენებს ამ ფუნჯებიდან ერთს ან მეტს. მოიხსნას ფუნჯები ამ კონტურებიდან და წაიშალოს ფუნჯები? Remove Strokes კონტურების მოხსნა Yes დიახ No არა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e487667b56..e9fa809c25 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5591,8 +5591,8 @@ breakText Glyphs 글리프 Gap 4 간격 4 Dash 5 대시 5 Gap 5 간격 5 - Delete the brush selection? 선택한 브러시를 삭제하시겠습니까? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. 하나 이상의 브러시가 사용 중이며 선을 확장하거나 제거할 때까지 삭제할 수 없습니다. + Delete the selected brushes? 선택한 브러시를 삭제하시겠습니까? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 선에서 이 브러시 중 하나 이상을 사용합니다. 해당 선에서 브러시를 제거하고 브러시를 삭제하시겠습니까? Remove Strokes 선 제거 Yes 예 No 아니요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 71d7a6d732..2fdb5d58b8 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5957,8 +5957,8 @@ breakText Glyphs Glyphs Gap 4 Tussenruimte 4 Dash 5 Streepje 5 Gap 5 Tussenruimte 5 - Delete the brush selection? Geselecteerde kwasten verwijderen? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Een of meer kwasten zijn in gebruik en kunnen pas worden verwijderd als hun contouren zijn uitgebreid of verwijderd. + Delete the selected brushes? Geselecteerde kwasten verwijderen? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Contouren gebruiken een of meer van deze kwasten. De kwasten van deze contouren halen en de kwasten verwijderen? Remove Strokes Contouren verwijderen Yes Ja No Nee diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 7a606131ff..73117d2fcf 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5864,8 +5864,8 @@ breakText Glyphs Glify Gap 4 Odstęp 4 Dash 5 Kreska 5 Gap 5 Odstęp 5 - Delete the brush selection? Usunąć zaznaczone pędzle? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Co najmniej jeden pędzel jest używany i nie można go usunąć, dopóki jego obrysy nie zostaną rozszerzone lub usunięte. + Delete the selected brushes? Usunąć zaznaczone pędzle? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Obrysy używają co najmniej jednego z tych pędzli. Zdjąć pędzle z tych obrysów i usunąć pędzle? Remove Strokes Usuń obrysy Yes Tak No Nie diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e1044cbbd7..b2282cb815 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5928,8 +5928,8 @@ breakText Glyphs Glifos Gap 4 Lacuna 4 Dash 5 Traço 5 Gap 5 Lacuna 5 - Delete the brush selection? Excluir os pincéis selecionados? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Um ou mais pincéis estão em uso e não podem ser excluídos até que seus traçados sejam expandidos ou removidos. + Delete the selected brushes? Excluir os pincéis selecionados? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Traçados usam um ou mais destes pincéis. Remover os pincéis desses traçados e excluir os pincéis? Remove Strokes Remover Traçados Yes Sim No Não diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d9cede6983..a25e32e226 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5986,8 +5986,8 @@ breakText Glyphs Глифы Gap 4 Зазор 4 Dash 5 Штрих 5 Gap 5 Зазор 5 - Delete the brush selection? Удалить выбранные кисти? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Одна или несколько кистей используются и не могут быть удалены, пока их обводки не будут разобраны или убраны. + Delete the selected brushes? Удалить выбранные кисти? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Обводки используют одну или несколько из этих кистей. Убрать кисти с этих обводок и удалить кисти? Remove Strokes Убрать обводки Yes Да No Нет diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 68239d409b..7075d1cd00 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6061,8 +6061,8 @@ breakText Glyphs Glyfer Gap 4 Mellanrum 4 Dash 5 Streck 5 Gap 5 Mellanrum 5 - Delete the brush selection? Radera de valda penslarna? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. En eller flera penslar används och kan inte raderas förrän deras konturer har expanderats eller tagits bort. + Delete the selected brushes? Radera de valda penslarna? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturer använder en eller flera av de här penslarna. Ta bort penslarna från konturerna och radera penslarna? Remove Strokes Ta bort konturer Yes Ja No Nej diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 44cc14ba51..65679691a9 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5966,8 +5966,8 @@ breakText Glyphs Glifler Gap 4 Boşluk 4 Dash 5 Çizgi 5 Gap 5 Boşluk 5 - Delete the brush selection? Seçili fırçalar silinsin mi? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Bir veya daha fazla fırça kullanılıyor ve konturları genişletilmeden veya kaldırılmadan silinemez. + Delete the selected brushes? Seçili fırçalar silinsin mi? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturlar bu fırçalardan birini veya daha fazlasını kullanıyor. Fırçalar bu konturlardan kaldırılsın ve fırçalar silinsin mi? Remove Strokes Konturları Kaldır Yes Evet No Hayır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 271b96793e..7229a24aff 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5608,8 +5608,8 @@ breakText Glyphs Гліфи Gap 4 Проміжок 4 Dash 5 Штрих 5 Gap 5 Проміжок 5 - Delete the brush selection? Видалити вибрані пензлі? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Один або кілька пензлів використовуються і не можуть бути видалені, доки їхні обведення не буде розібрано або забрано. + Delete the selected brushes? Видалити вибрані пензлі? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Обведення використовують один або кілька з цих пензлів. Забрати пензлі з цих обведень і видалити пензлі? Remove Strokes Забрати обведення Yes Так No Ні diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 66978c3703..7e5393289f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5610,8 +5610,8 @@ breakText Glyphs Glyph Gap 4 Khoảng hở 4 Dash 5 Nét 5 Gap 5 Khoảng hở 5 - Delete the brush selection? Xóa các cọ đã chọn? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Một hoặc nhiều cọ đang được sử dụng và không thể xóa cho đến khi nét được mở rộng hoặc gỡ bỏ. + Delete the selected brushes? Xóa các cọ đã chọn? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Có nét đang dùng một hoặc nhiều cọ này. Gỡ cọ khỏi các nét đó và xóa cọ? Remove Strokes Gỡ nét Yes Có No Không diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 85e1ffd3d9..5f0b5adcea 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5850,8 +5850,8 @@ breakText Glyphs 字形 Gap 4 间隔 4 Dash 5 虚线 5 Gap 5 间隔 5 - Delete the brush selection? 删除选中的画笔吗? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. 一个或多个画笔正在使用中,必须先扩展或移除其描边才能删除。 + Delete the selected brushes? 删除选中的画笔吗? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 有描边使用了其中一个或多个画笔。要从这些描边移除画笔并删除画笔吗? Remove Strokes 移除描边 Yes 是 No 否 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 44e077e904..65e66a36e7 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5647,8 +5647,8 @@ breakText Glyphs 字符 Gap 4 間隙 4 Dash 5 虛線 5 Gap 5 間隙 5 - Delete the brush selection? 要刪除選取的筆刷嗎? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. 一個或多個筆刷正在使用中,必須先擴展或移除其筆畫才能刪除。 + Delete the selected brushes? 要刪除選取的筆刷嗎? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 有筆畫使用了其中一個或多個筆刷。要從這些筆畫移除筆刷並刪除筆刷嗎? Remove Strokes 移除筆畫 Yes 是 No 否 diff --git a/crates/ui-egui/src/panels/brushes/tests.rs b/crates/ui-egui/src/panels/brushes/tests.rs index c4b794677a..0aef4fb634 100644 --- a/crates/ui-egui/src/panels/brushes/tests.rs +++ b/crates/ui-egui/src/panels/brushes/tests.rs @@ -160,9 +160,12 @@ fn assert_delete_dialog(app: &VectorcraftApp, message: &str) { let d = app.ui.dialog.as_ref().expect("Delete Brush asks first"); assert_eq!(d.kind, crate::dialogs::brush_delete::KIND); assert_eq!(d.str("message"), message); - assert_eq!(d.bool("used"), message.starts_with("One or more")); + assert_eq!(d.bool("used"), message == IN_USE); } +/// The Delete Brush question when a stroke uses one of the brushes. +const IN_USE: &str = "Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes?"; + /// Deleting several unused brushes asks one question about the selection, with no count in it. #[test] fn deleting_five_brushes_uses_one_selection_question() { @@ -226,7 +229,7 @@ fn shift_and_command_clicks_select_brushes_for_delete_and_duplicate() { assert_eq!(undo_count(&app), before.1 + 1); // The bottom bar's last button, Delete Brush. delete_button(&ctx, &mut app, egui::Modifiers::NONE, 5.0); - assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); + assert_delete_dialog(&app, IN_USE); assert_eq!(names(&mut app), [before.0.clone(), copies.to_vec()].concat()); assert_eq!(brush_of(&app, rect).as_deref(), Some(three[0].as_str())); assert_eq!(undo_count(&app), before.1 + 1); @@ -266,7 +269,7 @@ fn selecting_other_art_ends_the_brush_multi_selection() { let out = frame_with(&ctx, &mut app, vec![], egui::Modifiers::NONE, 4.0, show); assert_eq!(lit_tiles(&out), [1]); menu_click(&ctx, &mut app, "Delete Brush", 5.0); - assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); + assert_delete_dialog(&app, IN_USE); assert!(names(&mut app).contains(&three[1])); crate::dialogs::confirm(&mut app).unwrap(); let left = names(&mut app); @@ -335,7 +338,7 @@ fn select_all_unused_selects_the_brushes_no_stroke_paints_with() { let on: Vec<usize> = (0..tiles.len()).filter(|i| lit(&ctx, &out).contains(&tiles[*i])).collect(); assert_eq!(on, (0..tiles.len()).filter(|i| *i != 1).collect::<Vec<_>>()); menu_click(&ctx, &mut app, "Delete Brush", 3.0); - assert_delete_dialog(&app, "Delete the brush selection?"); + assert_delete_dialog(&app, "Delete the selected brushes?"); assert_eq!(names(&mut app).len(), list.len()); crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(names(&mut app), [list[1].0.clone()]); @@ -352,7 +355,7 @@ fn delete_button_cancel_keeps_selected_brushes_strokes_and_history() { let (three, _) = select_three(&ctx, &mut app, rect); let before = (names(&mut app), brush_of(&app, rect), undo_count(&app)); delete_button(&ctx, &mut app, egui::Modifiers::NONE, 3.0); - assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); + assert_delete_dialog(&app, IN_USE); assert_eq!((names(&mut app), brush_of(&app, rect), undo_count(&app)), before); crate::dialogs::cancel(&mut app); assert!(app.ui.dialog.is_none()); @@ -376,10 +379,10 @@ fn alt_delete_button_asks_when_a_selected_brush_is_used() { let (three, _) = select_three(&ctx, &mut app, rect); let before = undo_count(&app); delete_button(&ctx, &mut app, egui::Modifiers::NONE, 3.0); - assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); + assert_delete_dialog(&app, IN_USE); crate::dialogs::cancel(&mut app); delete_button(&ctx, &mut app, egui::Modifiers::ALT, 4.0); - assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); + assert_delete_dialog(&app, IN_USE); crate::dialogs::cancel(&mut app); let left = names(&mut app); assert!(three.iter().all(|name| left.contains(name))); @@ -414,7 +417,7 @@ fn menu_delete_used_brush_requires_remove_strokes_or_cancel() { let (three, _) = select_three(&ctx, &mut app, rect); let before = undo_count(&app); menu_click(&ctx, &mut app, "Delete Brush", 3.0); - assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); + assert_delete_dialog(&app, IN_USE); crate::dialogs::cancel(&mut app); assert_eq!(undo_count(&app), before); assert_eq!(brush_of(&app, rect).as_deref(), Some(three[0].as_str())); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a035815286..c53382a210 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -962,7 +962,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (<https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html>). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). In the Brushes panel, Shift-click selects a range of brushes and Ctrl/Cmd-click adds or removes one. Delete Brush and Duplicate Brush then act on all of them (`brush.delete {names}`, `brush.duplicate {names}`). - The Brushes panel's Delete Brush button and panel menu item ask "Delete the brush selection?" with Yes and No when none of the brushes is in use. Alt-click (Option-click on macOS) on the button deletes them without asking, as the [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists ("Delete without confirmation (except for Layers panel)"). When a stroke uses one of the brushes, the button, Alt-click and the menu item all ask with Remove Strokes and Cancel; Remove Strokes deletes the brushes and the strokes that used them become plain strokes. Tests: `panels::brushes::tests`, `dialogs::brush_delete::tests`. + The Brushes panel's Delete Brush button and panel menu item ask "Delete the selected brushes?" with Yes and No when none of the brushes is in use. Alt-click (Option-click on macOS) on the button deletes them without asking, as the [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page (archived copy) lists ("Delete without confirmation (except for Layers panel)"). When a stroke uses one of the brushes, the button, Alt-click and the menu item all ask with Remove Strokes and Cancel; Remove Strokes deletes the brushes and the strokes that used them become plain strokes. Tests: `panels::brushes::tests`, `dialogs::brush_delete::tests`. Document Info has a Brushes category after Graphic Styles. It lists the Brushes panel's brushes, or with Selection Only it lists the brushes that the selected objects' strokes use. The Document Info report and Package's report list them too (`document.info {category: "brushes"}`, `brushNames`). Document Info has a Repeat Objects category after Embedded Images. It lists each radial, grid and mirror Repeat object by name with its kind and the number of instances it makes. For a grid it gives the rows and columns instead, followed by the number of instances it draws when that is fewer. With Selection Only it lists the Repeat objects in the selection. The Document Info report and Package's report list them too (`document.info {category: "repeats"}`, `repeatObjects`). The Brushes panel menu's Select All Unused selects the brushes that are not used in the document, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. A brush counts as used when a stroke paints with it in the art (opacity masks included), in symbols, graph designs, pattern tiles or graphic styles, or in the art of a used brush (`brush.unused`). From 3a6770e7842558d8599dc50027be163835e3ba3d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 22:25:32 -0700 Subject: [PATCH 131/260] Brushes: Yes in Delete Brush asks again when a stroke started using a brush meanwhile The question for unused brushes checks again when Yes is chosen. If a stroke uses one of the brushes by then, the dialog asks with Remove Strokes and Cancel instead of deleting. --- crates/ui-egui/src/dialogs/brush_delete.rs | 22 ++++++++++++++++++- .../ui-egui/src/dialogs/brush_delete/tests.rs | 19 ++++++++++++++++ crates/ui-egui/src/panels/brushes.rs | 4 +--- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/brush_delete.rs b/crates/ui-egui/src/dialogs/brush_delete.rs index ee4d6c964e..84f2786d4f 100644 --- a/crates/ui-egui/src/dialogs/brush_delete.rs +++ b/crates/ui-egui/src/dialogs/brush_delete.rs @@ -28,6 +28,21 @@ pub fn ask(app: &mut VectorcraftApp, params: Value, used: bool) { app.ui.dialog = Some(Dialog::new(KIND, json!({"params": params, "used": used, "message": message}))); } +/// Whether a stroke uses one of `names` (`brush.unused`), or `None` when the query fails. +pub fn used(app: &mut VectorcraftApp, names: &[String]) -> Option<bool> { + let unused = app.run("brush.unused", json!({})).ok()?; + let unused = unused.get("names").and_then(Value::as_array).cloned().unwrap_or_default(); + Some(names.iter().any(|name| !unused.iter().any(|n| n.as_str() == Some(name)))) +} + +/// The brush names in `brush.delete` params (`name` or `names`). +fn names(params: &Value) -> Vec<String> { + match params.get("name").and_then(Value::as_str) { + Some(name) => vec![name.to_string()], + None => params.get("names").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(), + } +} + fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { let mut action = DialogAction::None; ui.horizontal(|ui| { @@ -50,9 +65,14 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogActi action } -/// Closes before running, so a dialog the command opens stays open. +/// Closes before running, so a dialog the command opens stays open. Yes on brushes that a stroke +/// has started to use since the question opened asks again with Remove Strokes and Cancel. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { let params = d.fields.get("params").cloned().unwrap_or_else(|| json!({})); + if !d.bool("used") && used(app, &names(¶ms)) == Some(true) { + ask(app, params, true); + return Ok(json!({})); + } app.ui.dialog = None; app.run("brush.delete", params) } diff --git a/crates/ui-egui/src/dialogs/brush_delete/tests.rs b/crates/ui-egui/src/dialogs/brush_delete/tests.rs index 407351c794..6f753505cb 100644 --- a/crates/ui-egui/src/dialogs/brush_delete/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_delete/tests.rs @@ -50,6 +50,25 @@ fn visible_yes_and_no_buttons_control_unused_deletion() { assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); } +#[test] +fn yes_asks_again_when_a_stroke_started_using_the_brush() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let name = "10 pt. Oval"; + let ctx = context(); + ask(&mut app, json!({"names": [name]}), false); + let path = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap()); + app.run("brush.apply", json!({"name": name})).unwrap(); + let before = app.session.active().unwrap().history.undo.len(); + press(&ctx, &mut app, "Yes", 0.0); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND && d.bool("used")), "asks again with Remove Strokes"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before); + let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap(); + assert_eq!(stroke.brush.as_deref(), Some(name)); + press(&ctx, &mut app, "Remove Strokes", 1.0); + assert!(app.run("brush.get", json!({"name": name})).is_err()); +} + #[test] fn visible_remove_strokes_and_cancel_buttons_control_used_deletion() { for choice in ["Cancel", "Remove Strokes"] { diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index 279677527f..6f99c8a36d 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -207,11 +207,9 @@ fn run_on(app: &mut VectorcraftApp, id: &str, names: &[String]) { /// Delete `names` after asking: Yes or No when none of them is in use, else Remove Strokes or /// Cancel. With `now` (Alt-click on the bottom button), brushes that are not in use go at once. fn delete(app: &mut VectorcraftApp, names: &[String], now: bool) { - let Ok(unused) = app.run("brush.unused", json!({})) else { + let Some(used) = crate::dialogs::brush_delete::used(app, names) else { return; }; - let unused = unused.get("names").and_then(Value::as_array).cloned().unwrap_or_default(); - let used = names.iter().any(|name| !unused.iter().any(|n| n.as_str() == Some(name))); if now && !used { run_on(app, "brush.delete", names); return; From bb563452904aedbfdcf96b59297953db090fb137 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 22:41:30 -0700 Subject: [PATCH 132/260] Brushes: the Delete Brush question deletes nothing once another document is active The question records the document it was opened for. If another document has become the active one by the time it is confirmed, it closes as Cancel does. --- crates/ui-egui/src/dialogs/brush_delete.rs | 17 +++++++++++++---- .../ui-egui/src/dialogs/brush_delete/tests.rs | 16 ++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/brush_delete.rs b/crates/ui-egui/src/dialogs/brush_delete.rs index 84f2786d4f..52a86dc167 100644 --- a/crates/ui-egui/src/dialogs/brush_delete.rs +++ b/crates/ui-egui/src/dialogs/brush_delete.rs @@ -2,8 +2,8 @@ //! use, else Remove Strokes or Cancel. Yes and Remove Strokes run `brush.delete`, which leaves the //! strokes that used the brushes as plain strokes. //! -//! Fields: `message` (the question, shown as the heading), `used` (whether a brush is in use) and -//! `params` (the `brush.delete` params). +//! Fields: `message` (the question, shown as the heading), `used` (whether a brush is in use), +//! `params` (the `brush.delete` params) and `__doc` (the uid of the document it asks about). use serde_json::{Value, json}; @@ -25,9 +25,13 @@ pub fn ask(app: &mut VectorcraftApp, params: Value, used: bool) { } else { tl!("Delete the selected brushes?") }; - app.ui.dialog = Some(Dialog::new(KIND, json!({"params": params, "used": used, "message": message}))); + let doc = app.session.active().map(|d| d.uid); + app.ui.dialog = Some(Dialog::new(KIND, json!({"params": params, "used": used, "message": message, DOC: doc}))); } +/// The field that holds the uid of the document the question is about. +const DOC: &str = "__doc"; + /// Whether a stroke uses one of `names` (`brush.unused`), or `None` when the query fails. pub fn used(app: &mut VectorcraftApp, names: &[String]) -> Option<bool> { let unused = app.run("brush.unused", json!({})).ok()?; @@ -66,9 +70,14 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogActi } /// Closes before running, so a dialog the command opens stays open. Yes on brushes that a stroke -/// has started to use since the question opened asks again with Remove Strokes and Cancel. +/// has started to use since the question opened asks again with Remove Strokes and Cancel. When +/// another document has become the active one, it closes as Cancel does and deletes nothing. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { let params = d.fields.get("params").cloned().unwrap_or_else(|| json!({})); + if d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|doc| doc.uid) { + app.ui.dialog = None; + return Ok(json!({})); + } if !d.bool("used") && used(app, &names(¶ms)) == Some(true) { ask(app, params, true); return Ok(json!({})); diff --git a/crates/ui-egui/src/dialogs/brush_delete/tests.rs b/crates/ui-egui/src/dialogs/brush_delete/tests.rs index 6f753505cb..4092d63387 100644 --- a/crates/ui-egui/src/dialogs/brush_delete/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_delete/tests.rs @@ -69,6 +69,22 @@ fn yes_asks_again_when_a_stroke_started_using_the_brush() { assert!(app.run("brush.get", json!({"name": name})).is_err()); } +#[test] +fn yes_deletes_nothing_after_another_document_became_active() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let name = app.run("brush.list", json!({})).unwrap()["brushes"][0]["name"].as_str().unwrap().to_string(); + let ctx = context(); + ask(&mut app, json!({"name": name}), false); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + press(&ctx, &mut app, "Yes", 0.0); + assert!(app.ui.dialog.is_none()); + assert!(app.run("brush.get", json!({"name": name})).is_ok(), "the second document keeps the brush"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(app.run("brush.get", json!({"name": name})).is_ok(), "the first document keeps the brush"); +} + #[test] fn visible_remove_strokes_and_cancel_buttons_control_used_deletion() { for choice in ["Cancel", "Remove Strokes"] { From beac4504fcaa0021c8e74f6de5d823acda904e15 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 01:29:21 -0700 Subject: [PATCH 133/260] Brushes: the French delete questions keep the no-break space before ? --- crates/ui-egui/src/i18n/fr.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index f80a70246a..b8bfd769a0 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6006,8 +6006,8 @@ breakText Glyphs Glyphes Gap 4 Écart 4 Dash 5 Tiret 5 Gap 5 Écart 5 - Delete the selected brushes? Supprimer les formes sélectionnées ? - Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Des contours utilisent une ou plusieurs de ces formes. Retirer les formes de ces contours et supprimer les formes ? + Delete the selected brushes? Supprimer les formes sélectionnées ? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Des contours utilisent une ou plusieurs de ces formes. Retirer les formes de ces contours et supprimer les formes ? Remove Strokes Supprimer les contours Yes Oui No Non From 34d58c1bfbd95bdccc280849f3af991f06a50bdc Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 01:22:03 +0700 Subject: [PATCH 134/260] i18n: one row per catalog entry after #4829 --- crates/ui-egui/src/i18n/bg.tsv | 2 -- crates/ui-egui/src/i18n/bs.tsv | 2 -- crates/ui-egui/src/i18n/ca.tsv | 2 -- crates/ui-egui/src/i18n/cs.tsv | 2 -- crates/ui-egui/src/i18n/da.tsv | 2 -- crates/ui-egui/src/i18n/de.tsv | 2 -- crates/ui-egui/src/i18n/el.tsv | 2 -- crates/ui-egui/src/i18n/es.tsv | 2 -- crates/ui-egui/src/i18n/fi.tsv | 2 -- crates/ui-egui/src/i18n/fr.tsv | 2 -- crates/ui-egui/src/i18n/hu.tsv | 2 -- crates/ui-egui/src/i18n/id.tsv | 2 -- crates/ui-egui/src/i18n/it.tsv | 2 -- crates/ui-egui/src/i18n/ja.tsv | 2 -- crates/ui-egui/src/i18n/ka.tsv | 2 -- crates/ui-egui/src/i18n/ko.tsv | 2 -- crates/ui-egui/src/i18n/nl.tsv | 2 -- crates/ui-egui/src/i18n/pl.tsv | 2 -- crates/ui-egui/src/i18n/pt-br.tsv | 2 -- crates/ui-egui/src/i18n/ru.tsv | 2 -- crates/ui-egui/src/i18n/sv.tsv | 2 -- crates/ui-egui/src/i18n/tr.tsv | 2 -- crates/ui-egui/src/i18n/uk.tsv | 2 -- crates/ui-egui/src/i18n/vi.tsv | 2 -- crates/ui-egui/src/i18n/zh-hans.tsv | 2 -- crates/ui-egui/src/i18n/zh-hant.tsv | 2 -- 26 files changed, 52 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 43cef9353d..0888ac645d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5902,8 +5902,6 @@ breakText Glyphs Глифи Delete the selected brushes? Да се изтрият избраните четки? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Щрихи използват една или повече от тези четки. Да се премахнат ли четките от тези щрихи и да се изтрият четките? Remove Strokes Премахване на щрихи - Yes Да - No Не # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Инструменти за подреждане Arrange in Grid… Подреждане в мрежа… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 0deb3e7c36..d89af156f8 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5934,8 +5934,6 @@ shape Open Otvoren Delete the selected brushes? Izbrisati odabrane četkice? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Potezi koriste jednu ili više ovih četkica. Ukloniti četkice s tih poteza i izbrisati četkice? Remove Strokes Ukloni poteze - Yes Da - No Ne # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Alati za raspoređivanje Arrange in Grid… Rasporedi u mrežu… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a83e611a34..15bd85222d 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6002,8 +6002,6 @@ breakText Glyphs Glifs Delete the selected brushes? Voleu suprimir els pinzells seleccionats? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Hi ha traços que fan servir un o més d’aquests pinzells. Voleu treure els pinzells d’aquests traços i suprimir els pinzells? Remove Strokes Elimina els traços - Yes Sí - No No # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Eines d’organització Arrange in Grid… Organitza en quadrícula… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 6fac8c5586..fe80401bc1 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6011,8 +6011,6 @@ breakText Glyphs Glyfy Delete the selected brushes? Odstranit vybrané štětce? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Tahy používají jeden nebo více z těchto štětců. Odebrat štětce z těchto tahů a odstranit štětce? Remove Strokes Odebrat tahy - Yes Ano - No Ne # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Nástroje uspořádání Arrange in Grid… Uspořádat do mřížky… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index ef3b48df54..74107e22cb 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5916,8 +5916,6 @@ breakText Glyphs Glyffer Delete the selected brushes? Slet de valgte pensler? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Streger bruger en eller flere af disse pensler. Fjern penslerne fra stregerne, og slet penslerne? Remove Strokes Fjern streger - Yes Ja - No Nej # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Arrangeringsværktøjer Arrange in Grid… Arrangér i gitter… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9028735e09..447c98350d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5597,8 +5597,6 @@ breakText Glyphs Glyphen Delete the selected brushes? Ausgewählte Pinsel löschen? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturen verwenden einen oder mehrere dieser Pinsel. Pinsel von diesen Konturen entfernen und die Pinsel löschen? Remove Strokes Konturen entfernen - Yes Ja - No Nein # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Anordnungswerkzeuge Arrange in Grid… In Raster anordnen… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b8bd5f396b..8dea59f7f0 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5964,8 +5964,6 @@ breakText Glyphs Γλύφοι Delete the selected brushes? Να διαγραφούν τα επιλεγμένα πινέλα; Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Περιγράμματα χρησιμοποιούν ένα ή περισσότερα από αυτά τα πινέλα. Να αφαιρεθούν τα πινέλα από αυτά τα περιγράμματα και να διαγραφούν τα πινέλα; Remove Strokes Αφαίρεση περιγραμμάτων - Yes Ναι - No Όχι # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Εργαλεία διάταξης Arrange in Grid… Διάταξη σε πλέγμα… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ac1e149df1..e6c7dd7690 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5954,8 +5954,6 @@ breakText Glyphs Glifos Delete the selected brushes? ¿Eliminar los pinceles seleccionados? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Algunos trazos usan uno o más de estos pinceles. ¿Quitar los pinceles de esos trazos y eliminar los pinceles? Remove Strokes Quitar trazos - Yes Sí - No No # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Herramientas de organización Arrange in Grid… Organizar en cuadrícula… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 13107e11ec..08122ed024 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6042,8 +6042,6 @@ breakText Glyphs Merkit Delete the selected brushes? Poistetaanko valitut siveltimet? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Viivat käyttävät yhtä tai useampaa näistä siveltimistä. Irrotetaanko siveltimet näistä viivoista ja poistetaanko siveltimet? Remove Strokes Poista viivat - Yes Kyllä - No Ei # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Järjestelytyökalut Arrange in Grid… Järjestä ruudukkoon… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index b8bfd769a0..b35297550a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6009,8 +6009,6 @@ breakText Glyphs Glyphes Delete the selected brushes? Supprimer les formes sélectionnées ? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Des contours utilisent une ou plusieurs de ces formes. Retirer les formes de ces contours et supprimer les formes ? Remove Strokes Supprimer les contours - Yes Oui - No Non # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Outils de disposition Arrange in Grid… Disposer en grille… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 3e72e0c398..cac7189ed7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5998,8 +5998,6 @@ breakText Glyphs Glifák Delete the selected brushes? Törlöd a kijelölt ecseteket? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Körvonalak használnak egyet vagy többet ezek közül az ecsetek közül. Leveszed az ecseteket ezekről a körvonalakról, és törlöd az ecseteket? Remove Strokes Körvonalak eltávolítása - Yes Igen - No Nem # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Elrendezőeszközök Arrange in Grid… Elrendezés rácsba… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 00bbfac314..29e87826ab 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5916,8 +5916,6 @@ breakText Glyphs Glif Delete the selected brushes? Hapus kuas yang dipilih? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Stroke menggunakan satu atau beberapa kuas ini. Lepaskan kuas dari stroke tersebut dan hapus kuasnya? Remove Strokes Hapus Stroke - Yes Ya - No Tidak # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Alat penyusunan Arrange in Grid… Susun dalam grid… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 81b4ec79fa..51870220aa 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5631,8 +5631,6 @@ breakText Glyphs Glifi Delete the selected brushes? Eliminare i pennelli selezionati? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Alcune tracce usano uno o più di questi pennelli. Rimuovere i pennelli da queste tracce ed eliminare i pennelli? Remove Strokes Rimuovi tracce - Yes Sì - No No # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Strumenti di disposizione Arrange in Grid… Disponi in griglia… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 3064294fd4..c6c4227b6b 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5697,8 +5697,6 @@ breakText Glyphs 字形 Delete the selected brushes? 選択したブラシを削除しますか? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? これらのブラシの 1 つ以上が線で使われています。それらの線からブラシを外して、ブラシを削除しますか? Remove Strokes 線を削除 - Yes はい - No いいえ # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 配置ツール Arrange in Grid… グリッドに配置… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 2d65308cba..c02d40eb17 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6001,8 +6001,6 @@ breakText Glyphs გლიფები Delete the selected brushes? წაიშალოს არჩეული ფუნჯები? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? კონტურები იყენებს ამ ფუნჯებიდან ერთს ან მეტს. მოიხსნას ფუნჯები ამ კონტურებიდან და წაიშალოს ფუნჯები? Remove Strokes კონტურების მოხსნა - Yes დიახ - No არა # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools განლაგების ხელსაწყოები Arrange in Grid… ბადეში განლაგება… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e9fa809c25..5c24bd9ca2 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5594,8 +5594,6 @@ breakText Glyphs 글리프 Delete the selected brushes? 선택한 브러시를 삭제하시겠습니까? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 선에서 이 브러시 중 하나 이상을 사용합니다. 해당 선에서 브러시를 제거하고 브러시를 삭제하시겠습니까? Remove Strokes 선 제거 - Yes 예 - No 아니요 # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 배치 도구 Arrange in Grid… 격자로 배치… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 2fdb5d58b8..282b0a4aad 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5960,8 +5960,6 @@ breakText Glyphs Glyphs Delete the selected brushes? Geselecteerde kwasten verwijderen? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Contouren gebruiken een of meer van deze kwasten. De kwasten van deze contouren halen en de kwasten verwijderen? Remove Strokes Contouren verwijderen - Yes Ja - No Nee # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Schikgereedschappen Arrange in Grid… In raster schikken… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 73117d2fcf..3999714470 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5867,8 +5867,6 @@ breakText Glyphs Glify Delete the selected brushes? Usunąć zaznaczone pędzle? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Obrysy używają co najmniej jednego z tych pędzli. Zdjąć pędzle z tych obrysów i usunąć pędzle? Remove Strokes Usuń obrysy - Yes Tak - No Nie # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Narzędzia układania Arrange in Grid… Ułóż w siatce… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index b2282cb815..4f75dd659d 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5931,8 +5931,6 @@ breakText Glyphs Glifos Delete the selected brushes? Excluir os pincéis selecionados? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Traçados usam um ou mais destes pincéis. Remover os pincéis desses traçados e excluir os pincéis? Remove Strokes Remover Traçados - Yes Sim - No Não # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Ferramentas de Organização Arrange in Grid… Organizar em Grade… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a25e32e226..d412fa13bc 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5989,8 +5989,6 @@ breakText Glyphs Глифы Delete the selected brushes? Удалить выбранные кисти? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Обводки используют одну или несколько из этих кистей. Убрать кисти с этих обводок и удалить кисти? Remove Strokes Убрать обводки - Yes Да - No Нет # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Инструменты размещения Arrange in Grid… Разместить по сетке… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 7075d1cd00..2a1ba37453 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6064,8 +6064,6 @@ breakText Glyphs Glyfer Delete the selected brushes? Radera de valda penslarna? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturer använder en eller flera av de här penslarna. Ta bort penslarna från konturerna och radera penslarna? Remove Strokes Ta bort konturer - Yes Ja - No Nej # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Ordningsverktyg Arrange in Grid… Ordna i rutnät… diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 65679691a9..215b7f8e6d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5969,8 +5969,6 @@ breakText Glyphs Glifler Delete the selected brushes? Seçili fırçalar silinsin mi? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturlar bu fırçalardan birini veya daha fazlasını kullanıyor. Fırçalar bu konturlardan kaldırılsın ve fırçalar silinsin mi? Remove Strokes Konturları Kaldır - Yes Evet - No Hayır # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Düzenleme Araçları Arrange in Grid… Izgarada Düzenle… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 7229a24aff..13fab3c518 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5611,8 +5611,6 @@ breakText Glyphs Гліфи Delete the selected brushes? Видалити вибрані пензлі? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Обведення використовують один або кілька з цих пензлів. Забрати пензлі з цих обведень і видалити пензлі? Remove Strokes Забрати обведення - Yes Так - No Ні # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Інструменти розміщення Arrange in Grid… Розмістити сіткою… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 7e5393289f..f45d5d04ae 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5613,8 +5613,6 @@ breakText Glyphs Glyph Delete the selected brushes? Xóa các cọ đã chọn? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Có nét đang dùng một hoặc nhiều cọ này. Gỡ cọ khỏi các nét đó và xóa cọ? Remove Strokes Gỡ nét - Yes Có - No Không # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Công cụ sắp xếp Arrange in Grid… Sắp xếp theo lưới… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f0b5adcea..4e105573f1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5853,8 +5853,6 @@ breakText Glyphs 字形 Delete the selected brushes? 删除选中的画笔吗? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 有描边使用了其中一个或多个画笔。要从这些描边移除画笔并删除画笔吗? Remove Strokes 移除描边 - Yes 是 - No 否 # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 排列工具 Arrange in Grid… 按网格排列… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 65e66a36e7..acb8291996 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5650,8 +5650,6 @@ breakText Glyphs 字符 Delete the selected brushes? 要刪除選取的筆刷嗎? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 有筆畫使用了其中一個或多個筆刷。要從這些筆畫移除筆刷並刪除筆刷嗎? Remove Strokes 移除筆畫 - Yes 是 - No 否 # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 排列工具 Arrange in Grid… 依格狀排列… From 012af4fd49914f68f40f9a3288e6d8ce03371f14 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 19:45:16 -0700 Subject: [PATCH 135/260] Brushes: each Pattern Brush Options tile can be set to a pattern swatch or None A menu under each of the five tiles in Pattern Brush Options lists None, Original and the document's pattern swatches; the corner menus keep the four automatic corners. A swatch choice copies the swatch's whole art and its tile frame into the brush, so the brush keeps drawing after the swatch is deleted, and the menu then shows that art as Original. Side cannot be None: OK shows "You must choose a side pattern." and keeps the dialog open. brush.options takes side_tile, outer_corner_tile, inner_corner_tile, start_tile and end_tile (a pattern name, none, original, the corner auto ids, or {"pattern": name} for a swatch named like one of those words), and rejects side_tile "none" and unknown names before editing. --- crates/brush/src/lib.rs | 43 ++++ crates/brush/src/tests.rs | 37 ++++ crates/brush/src/warp.rs | 22 +- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/brushes.rs | 70 ++++++ crates/engine/src/tests/brushsym.rs | 188 ++++++++++++++++ .../ui-egui/src/dialogs/brush_art_options.rs | 184 +++++++++++++--- crates/ui-egui/src/dialogs/brush_options.rs | 38 +++- .../src/dialogs/brush_options/tests.rs | 203 +++++++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/bs.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/widgets.rs | 2 +- docs/gaps.md | 8 +- docs/mcp.md | 7 +- docs/target-app-parity.md | 3 +- 39 files changed, 837 insertions(+), 48 deletions(-) diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index e76e67ba5b..fbec570112 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -386,10 +386,22 @@ impl CornerSource { #[serde(default)] pub struct PatternBrush { pub side: Node, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub side_frame: Option<Rect>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub side_swatch: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub outer_corner: Option<Node>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub outer_corner_frame: Option<Rect>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub outer_corner_swatch: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub inner_corner: Option<Node>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub inner_corner_frame: Option<Rect>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub inner_corner_swatch: Option<String>, /// What the outer corners take when there is no `outer_corner` art. Without art or a source, /// they take the `inner_corner` art. #[serde(skip_serializing_if = "Option::is_none")] @@ -400,8 +412,16 @@ pub struct PatternBrush { pub inner_source: Option<CornerSource>, #[serde(skip_serializing_if = "Option::is_none")] pub start: Option<Node>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start_frame: Option<Rect>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start_swatch: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub end: Option<Node>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end_frame: Option<Rect>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end_swatch: Option<String>, /// Scale in percent. pub scale: f64, /// Space between tiles in percent of the tile width. @@ -422,12 +442,22 @@ impl Default for PatternBrush { fn default() -> Self { Self { side: defaults::stitch_tile(), + side_frame: None, + side_swatch: None, outer_corner: None, + outer_corner_frame: None, + outer_corner_swatch: None, inner_corner: None, + inner_corner_frame: None, + inner_corner_swatch: None, outer_source: None, inner_source: None, start: None, + start_frame: None, + start_swatch: None, end: None, + end_frame: None, + end_swatch: None, scale: 100.0, spacing: 0.0, fit: PatternFit::Stretch, @@ -500,6 +530,14 @@ fn within_pair((a, b): (f64, f64), range: (f64, f64), fallback: f64) -> (f64, f6 (within(a, range, fallback), within(b, range, fallback)) } +fn valid_tile_frame(frame: Rect) -> bool { + [frame.x0, frame.y0, frame.x1, frame.y1].into_iter().all(f64::is_finite) + && frame.width().is_finite() + && frame.height().is_finite() + && frame.width() > 1e-9 + && frame.height() > 1e-9 +} + impl Colorization { /// A Hue Shift key colour that isn't a colour (components out of reach) becomes black. fn sanitize(&mut self) { @@ -600,6 +638,11 @@ impl Brush { BrushKind::Pattern(p) => { p.scale = within(p.scale, PatternBrush::SCALE_RANGE, 100.0); p.spacing = within(p.spacing, PatternBrush::SPACING_RANGE, 0.0); + for frame in [&mut p.side_frame, &mut p.outer_corner_frame, &mut p.inner_corner_frame, &mut p.start_frame, &mut p.end_frame] { + if frame.is_some_and(|f| !valid_tile_frame(f)) { + *frame = None; + } + } p.colorization.sanitize(); } BrushKind::Bristle(b) => { diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 28bbcda752..6362c8da8d 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -561,6 +561,43 @@ fn pattern_corner_source_none_leaves_that_kind_of_corner_empty() { assert!((outer == plain && inner == saved) || (inner == plain && outer == saved), "only the corners set to None are empty"); } +#[test] +fn pattern_without_start_tile_runs_side_to_path_start() { + let path = line(0.0, 0.0, 100.0, 0.0); + let doc = Document::new(1.0, 1.0); + let mut b = pattern_brush(PatternFit::Stretch, false); + if let BrushKind::Pattern(p) = &mut b.kind { + p.start = Some(rect_art(20.0, 4.0)); + } + let with_start = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(with_start[0].geometric_bounds().unwrap().width(), 20.0); + if let BrushKind::Pattern(p) = &mut b.kind { + p.start = None; + } + let without_start = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(without_start.len(), 10); + assert!(near(without_start[0].geometric_bounds().unwrap().x0, 0.0, 1e-6)); + assert!(near(without_start[0].geometric_bounds().unwrap().width(), 10.0, 1e-6)); +} + +#[test] +fn pattern_without_end_tile_runs_side_to_path_end() { + let path = line(0.0, 0.0, 100.0, 0.0); + let doc = Document::new(1.0, 1.0); + let mut b = pattern_brush(PatternFit::Stretch, false); + if let BrushKind::Pattern(p) = &mut b.kind { + p.end = Some(rect_art(20.0, 4.0)); + } + let with_end = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert!(with_end.iter().any(|n| near(n.geometric_bounds().unwrap().width(), 20.0, 1e-6))); + if let BrushKind::Pattern(p) = &mut b.kind { + p.end = None; + } + let without_end = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(without_end.len(), 10); + assert!(near(without_end.last().unwrap().geometric_bounds().unwrap().x1, 100.0, 1e-6)); +} + #[test] fn pattern_corner_sources_round_trip_and_stay_out_of_brushes_without_them() { let saved = serde_json::to_value(pattern_brush(PatternFit::Stretch, true)).unwrap(); diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index d66d5679fb..78c2f547f3 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -247,6 +247,16 @@ fn oriented(art: &Node, dir: Direction, flip_along: bool, flip_across: bool) -> (b.width() > 1e-9).then_some((a, b)) } +/// Orient a tile's repeat frame with its art. The frame can be smaller than the art. +fn oriented_tile(art: &Node, frame: Option<Rect>, flip_along: bool, flip_across: bool) -> Option<(Node, Rect)> { + let (node, bounds) = oriented(art, Direction::LeftToRight, flip_along, flip_across)?; + let Some(frame) = frame else { return Some((node, bounds)) }; + let x = if flip_along { (-frame.x1, -frame.x0) } else { (frame.x0, frame.x1) }; + let y = if flip_across { (-frame.y1, -frame.y0) } else { (frame.y0, frame.y1) }; + let frame = Rect::new(x.0, y.0, x.1, y.1); + (frame.width() > 1e-9 && frame.height() > 1e-9).then_some((node, frame)) +} + /// Piecewise-linear map from art x (offset from the art's left edge) to arc length. #[derive(Clone, Copy, Debug)] pub(crate) struct AlongMap { @@ -800,13 +810,13 @@ fn masked(n: Node, quad: &[Point], p: Point, towards: Vec2) -> Option<Node> { } pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node> { - let orient = |n: &Node| oriented(n, Direction::LeftToRight, pb.flip_along, pb.flip_across); - let Some(side) = orient(&pb.side) else { return vec![] }; + let orient = |n: &Node, frame| oriented_tile(n, frame, pb.flip_along, pb.flip_across); + let Some(side) = orient(&pb.side, pb.side_frame) else { return vec![] }; let k = weight * pb.scale.max(1.0) / 100.0; - let outer = pb.outer_corner.as_ref().and_then(orient); - let inner = pb.inner_corner.as_ref().and_then(orient); - let start = pb.start.as_ref().and_then(orient); - let end = pb.end.as_ref().and_then(orient); + let outer = pb.outer_corner.as_ref().and_then(|n| orient(n, pb.outer_corner_frame)); + let inner = pb.inner_corner.as_ref().and_then(|n| orient(n, pb.inner_corner_frame)); + let start = pb.start.as_ref().and_then(|n| orient(n, pb.start_frame)); + let end = pb.end.as_ref().and_then(|n| orient(n, pb.end_frame)); let tw = side.1.width() * k; let gap = tw * pb.spacing.max(0.0) / 100.0; // Each kind of corner takes its own art, else its source, else the other kind's art. diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 7b37fea769..3b9a476d42 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -134,7 +134,7 @@ pub fn specs() -> Vec<CommandSpec> { "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art). scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", has_doc, brush_options ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index f5e5c73fce..9cc52c82c8 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -390,7 +390,77 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> { let i = lib.iter().position(|b| b.name == name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?; let mut v = serde_json::to_value(&lib[i]).unwrap_or_default(); if let Some(params) = p.get("params") { + let original = v.clone(); merge(&mut v, params); + if lib[i].kind.type_id() == "pattern" { + let tiles = [ + ("side_tile", "side"), + ("outer_corner_tile", "outer_corner"), + ("inner_corner_tile", "inner_corner"), + ("start_tile", "start"), + ("end_tile", "end"), + ]; + // Resolve all Original choices against the brush before any tile can clear the art + // another corner borrows. Keep the matching frame with each copied tile. + let originals: Vec<_> = tiles + .iter() + .map(|(_, art)| { + let from = if art.ends_with("corner") + && original.get(art).is_none_or(Value::is_null) + && original.get(if *art == "outer_corner" { "outer_source" } else { "inner_source" }).is_none_or(Value::is_null) + { + if *art == "outer_corner" { "inner_corner" } else { "outer_corner" } + } else { + *art + }; + (original.get(from).cloned().unwrap_or(Value::Null), original.get(format!("{from}_frame")).cloned().unwrap_or(Value::Null)) + }) + .collect(); + for ((tile, art), (original_art, original_frame)) in tiles.into_iter().zip(originals) { + let frame = format!("{art}_frame"); + let swatch = format!("{art}_swatch"); + let Some(choice) = params.get(tile) else { + if params.get(art).is_some() { + if params.get(frame.as_str()).is_none() { + v[frame.as_str()] = Value::Null; + } + if params.get(swatch.as_str()).is_none() { + v[swatch.as_str()] = Value::Null; + } + } + continue; + }; + let (choice, swatch_only) = if let Some(name) = choice.as_object() { + (name.get("pattern").and_then(Value::as_str).ok_or_else(|| bad(C, "invalid pattern tile choice"))?, true) + } else { + (choice.as_str().ok_or_else(|| bad(C, "invalid pattern tile choice"))?, false) + }; + if art == "side" && choice == "none" && !swatch_only { + return Err(bad(C, "You must choose a side pattern.")); + } + if choice == "original" && !swatch_only { + v[art] = original_art; + v[frame.as_str()] = original_frame; + v[swatch.as_str()] = Value::Null; + } else if !swatch_only && (choice == "none" || (art.ends_with("corner") && brush::CornerSource::parse(choice).is_some())) { + v[art] = Value::Null; + v[frame.as_str()] = Value::Null; + v[swatch.as_str()] = Value::Null; + if art.ends_with("corner") { + v[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = json!(choice); + } + } else { + let pattern = s.doc()?.doc.pattern(choice).ok_or_else(|| bad(C, format!("no pattern named `{choice}`")))?; + let copy = Node::new(NodeId(0), NodeKind::Group { children: pattern.art.clone(), clip: false }); + v[art] = serde_json::to_value(copy).unwrap_or_default(); + v[frame.as_str()] = serde_json::to_value(pattern.tile).unwrap_or_default(); + v[swatch.as_str()] = json!(choice); + if art.ends_with("corner") { + v[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = Value::Null; + } + } + } + } } let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty() && *n != name).map(str::to_string); if let Some(nn) = &new_name { diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index bba39230bc..ef448da9de 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -832,6 +832,194 @@ fn art_brush_options_keep_the_scale_fields_an_edit_leaves_out() { assert_eq!(s.execute("brush.get", &json!({"name": "Bar"})).unwrap()["scale"], json!({"mode": "stretch"})); } +#[test] +fn pattern_tile_choices_copy_whole_swatch_art_and_reject_invalid_side() { + use std::sync::Arc; + use vectorcraft_doc::{PatternDef, StrokeLayer}; + use vectorcraft_geom::BezPath; + + let mut s = session(); + s.edit("Pattern", |d, _| { + let art = + Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), vectorcraft_doc::Appearance::default_art()); + d.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new("Wide", vec![Arc::new(art)]) }); + Ok(()) + }) + .unwrap(); + let side = s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap()["side"].clone(); + s.execute("brush.new", &json!({"type":"pattern", "name":"Plain Tiles", "params":{"side":side}})).unwrap(); + let original = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + for choice in ["none", "Missing"] { + let error = s.execute("brush.options", &json!({"name":"Plain Tiles", "params":{"side_tile":choice}})).unwrap_err().to_string(); + assert!(error.contains(if choice == "none" { "You must choose a side pattern." } else { "no pattern named" }), "{error}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap(), original); + } + s.execute("brush.options", &json!({"name":"Plain Tiles", "params":{"side_tile":"Wide", "fit":"addSpace"}})).unwrap(); + let saved = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap(); + assert_eq!(saved["side_frame"], json!(Rect::new(0.0, 0.0, 10.0, 4.0))); + assert_eq!(saved["side_swatch"], "Wide"); + let brush: vectorcraft_brush::Brush = serde_json::from_value(saved).unwrap(); + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((100.0, 0.0)); + let pieces = vectorcraft_brush::stroke_pieces( + &s.doc().unwrap().doc, + &brush, + &path, + &StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0), + ); + assert_eq!(pieces.len(), 10, "10 pt tile frame repeats ten times along 100 pt"); + assert!(pieces[0].geometric_bounds().unwrap().width() >= 29.9, "whole 30 pt art is copied"); + s.execute("brush.options", &json!({"name":"Plain Tiles", "params":{"inner_corner_tile":"Wide", "outer_corner_tile":"none"}})).unwrap(); + let corners: vectorcraft_brush::Brush = serde_json::from_value(s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap()).unwrap(); + let mut fallback = corners.clone(); + if let (vectorcraft_brush::BrushKind::Pattern(actual), vectorcraft_brush::BrushKind::Pattern(legacy)) = (&corners.kind, &mut fallback.kind) { + assert_eq!(actual.outer_source, Some(vectorcraft_brush::CornerSource::None)); + assert!(actual.inner_corner.is_some()); + legacy.outer_source = None; + } + let square = |clockwise: bool| { + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + if clockwise { + for point in [(100.0, 0.0), (100.0, 100.0), (0.0, 100.0)] { + p.line_to(point); + } + } else { + for point in [(0.0, 100.0), (100.0, 100.0), (100.0, 0.0)] { + p.line_to(point); + } + } + p.close_path(); + p + }; + let stroke = StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0); + assert!( + [false, true].into_iter().any(|clockwise| { + let path = square(clockwise); + vectorcraft_brush::stroke_pieces(&s.doc().unwrap().doc, &corners, &path, &stroke) + != vectorcraft_brush::stroke_pieces(&s.doc().unwrap().doc, &fallback, &path, &stroke) + }), + "explicit outer None omits the inner corner art on outer turns" + ); + let borrowed_art = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap()["inner_corner"].clone(); + s.execute("brush.new", &json!({"type":"pattern", "name":"Borrowed Corner", "params":{"side":original["side"], "inner_corner":borrowed_art}})) + .unwrap(); + s.execute("brush.options", &json!({"name":"Borrowed Corner", "params":{"outer_corner_tile":"original", "inner_corner_tile":"none"}})).unwrap(); + let borrowed = s.execute("brush.get", &json!({"name":"Borrowed Corner"})).unwrap(); + assert!(borrowed["outer_corner"].is_object()); + assert_eq!(borrowed["inner_source"], "none"); + s.edit("Delete pattern", |d, _| { + d.patterns.clear(); + Ok(()) + }) + .unwrap(); + let after: vectorcraft_brush::Brush = serde_json::from_value(s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap()).unwrap(); + assert_eq!( + vectorcraft_brush::stroke_pieces( + &s.doc().unwrap().doc, + &after, + &path, + &StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0) + ) + .len(), + 10 + ); + let copied = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap()["side"].clone(); + s.execute("brush.options", &json!({"name":"Plain Tiles", "params":{"side_tile":"original"}})).unwrap(); + let original_choice = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap(); + assert_eq!(original_choice["side"], copied); + assert!(original_choice.get("side_swatch").is_none()); +} + +#[test] +fn pattern_original_corner_keeps_borrowed_art_and_frame_when_source_is_cleared() { + let mut s = session(); + let chain = s.execute("brush.get", &json!({"name": "Chain"})).unwrap(); + let art = chain["outer_corner"].clone(); + let frame = json!(Rect::new(1.0, 2.0, 15.0, 18.0)); + for (name, source, borrowed) in [("Borrow Outer", "inner", "outer"), ("Borrow Inner", "outer", "inner")] { + let source_art = format!("{source}_corner"); + let source_frame = format!("{source_art}_frame"); + let borrowed_art = format!("{borrowed}_corner"); + let borrowed_frame = format!("{borrowed_art}_frame"); + let source_tile = format!("{source_art}_tile"); + let borrowed_tile = format!("{borrowed_art}_tile"); + s.execute("brush.new", &json!({"type":"pattern", "name":name, "params":{"side":chain["side"], source_art:art, source_frame:frame}})).unwrap(); + s.execute("brush.options", &json!({"name":name, "params":{source_tile:"none", borrowed_tile:"original"}})).unwrap(); + let saved = s.execute("brush.get", &json!({"name":name})).unwrap(); + assert_eq!(saved[&borrowed_art], chain["outer_corner"], "{borrowed} art"); + assert_eq!(saved[&borrowed_frame], frame, "{borrowed} frame"); + assert_eq!(saved[format!("{source}_source")], "none"); + } +} + +#[test] +fn pattern_tile_object_selects_reserved_swatch_names() { + use std::sync::Arc; + use vectorcraft_doc::PatternDef; + + let mut s = session(); + let names = ["none", "original", "autoCentered", "autoBetween", "autoSliced", "autoOverlap"]; + s.edit("Patterns", |doc, _| { + for name in names { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), + vectorcraft_doc::Appearance::default_art(), + ); + doc.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new(name, vec![Arc::new(art)]) }); + } + Ok(()) + }) + .unwrap(); + let before = s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap(); + for invalid in [json!({}), json!({"pattern": null}), json!({"pattern": 1})] { + let error = s.execute("brush.options", &json!({"name":"Diamonds", "params":{"side_tile":invalid}})).unwrap_err().to_string(); + assert!(error.contains("invalid pattern tile choice"), "{error}"); + assert_eq!(s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap(), before); + } + let slots = ["side_tile", "outer_corner_tile", "inner_corner_tile", "start_tile", "end_tile"]; + for (slot, name) in slots.into_iter().zip(names) { + s.execute("brush.options", &json!({"name":"Diamonds", "params":{(slot):{"pattern":name}}})).unwrap(); + } + let saved = s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap(); + for (art, name) in ["side", "outer_corner", "inner_corner", "start", "end"].into_iter().zip(names) { + assert_eq!(saved[format!("{art}_swatch")], name); + assert_eq!(saved[format!("{art}_frame")], json!(Rect::new(0.0, 0.0, 10.0, 4.0))); + } + s.execute("brush.options", &json!({"name":"Diamonds", "params":{"outer_corner_tile":{"pattern":"autoOverlap"}}})).unwrap(); + assert_eq!(s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap()["outer_corner_swatch"], "autoOverlap"); +} + +#[test] +fn pattern_end_tile_none_choices_leave_side_art_at_both_path_ends() { + use vectorcraft_doc::StrokeLayer; + use vectorcraft_geom::BezPath; + + let mut s = session(); + let side = s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap()["side"].clone(); + let cap = s.execute("brush.get", &json!({"name":"Chain"})).unwrap()["outer_corner"].clone(); + s.execute("brush.new", &json!({"type":"pattern", "name":"Capped", "params":{"side":side, "start":cap, "end":cap}})).unwrap(); + s.execute("brush.options", &json!({"name":"Capped", "params":{"start_tile":"none", "end_tile":"none"}})).unwrap(); + let def = s.execute("brush.get", &json!({"name":"Capped"})).unwrap(); + assert!(def.get("start").is_none() && def.get("end").is_none()); + let brush: vectorcraft_brush::Brush = serde_json::from_value(def).unwrap(); + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((100.0, 0.0)); + let pieces = vectorcraft_brush::stroke_pieces( + &s.doc().unwrap().doc, + &brush, + &path, + &StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0), + ); + let bounds = pieces.iter().fold(None, |bounds, node| vectorcraft_geom::union_opt(bounds, node.geometric_bounds())).unwrap(); + assert!((bounds.x0 - 0.0).abs() < 1e-6 && (bounds.x1 - 100.0).abs() < 1e-6, "{bounds:?}"); +} + // ---------- symbols ---------- fn make_symbol(s: &mut Session) -> (NodeId, String, Rect) { diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index f9b5bf5584..c9071fd376 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -26,7 +26,7 @@ use egui::{Color32, Sense, Stroke, pos2, vec2}; use serde_json::{Map, Value, json}; use vectorcraft_brush::{ArtBrush, ArtScale, Brush, BrushKind, Colorization, CornerSource, Direction, PatternBrush, PatternFit, Scatter, Variation}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, PatternDef}; use super::brush_options::{clamped, mode_key, stroke_preview}; use crate::VectorcraftApp; @@ -44,6 +44,55 @@ const DIRECTIONS: [Direction; 4] = [Direction::LeftToRight, Direction::RightToLe const TILES: [(&str, &str); 5] = [("outer_corner", "outerCorner"), ("side", "side"), ("inner_corner", "innerCorner"), ("start", "start"), ("end", "end")]; +fn tile_key(field: &str) -> String { + match field { + "outer_corner" => "outerCornerTile".into(), + "inner_corner" => "innerCornerTile".into(), + _ => format!("{field}Tile"), + } +} + +pub(super) fn pattern_names(d: &Dialog) -> Vec<String> { + d.fields + .get("__patterns") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|v| v.get("name").and_then(Value::as_str).map(str::to_string)) + .collect() +} + +fn pattern_choice(d: &Dialog, choice: &str) -> Option<String> { + let name = choice.strip_prefix("pattern:").unwrap_or(choice); + let reserved = choice == "none" || choice == "original" || CornerSource::parse(choice).is_some(); + (!reserved && pattern_names(d).iter().any(|candidate| candidate == name)).then(|| name.to_string()) +} + +pub(super) fn original_available(d: &Dialog, field: &str) -> bool { + let choice = d.str(&tile_key(field)); + let drawn = if field.ends_with("corner") { corner_art_field(d.fields.get("__def"), field) } else { Some(field) }; + drawn.is_some() && pattern_choice(d, &choice).is_none() +} + +pub(super) fn reconcile_pattern_choices(f: &mut Map<String, Value>) { + let names: Vec<String> = f + .get("__patterns") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|v| v.get("name").and_then(Value::as_str).map(str::to_string)) + .collect(); + let def = f.get("__def").cloned().unwrap_or_default(); + for (art, _) in TILES { + let swatch = def.get(format!("{art}_swatch")).and_then(Value::as_str); + if let Some(name) = swatch.filter(|name| names.iter().any(|n| n == name)) { + f.insert(tile_key(art), json!(format!("pattern:{name}"))); + } else if !art.ends_with("corner") { + f.insert(tile_key(art), json!(if def.get(art).is_some_and(|v| !v.is_null()) { "original" } else { "none" })); + } + } +} + /// Pattern brush corner tiles: (dialog field, art field of the definition, source field, art field /// of the other kind of corner). const CORNER_TILES: [(&str, &str, &str, &str); 2] = @@ -63,20 +112,20 @@ fn corner_art_field<'a>(def: Option<&Value>, field: &'a str) -> Option<&'a str> } } -/// The dialog field that records that corner tile `key`'s menu was set. +/// The dialog field that records that tile `key`'s menu was set. fn corner_set_key(key: &str) -> String { format!("__{key}Set") } -/// Sets corner tile `key` to `choice` from its menu. +/// Sets tile `key` to `choice` from its menu. pub(super) fn choose_corner(d: &mut Dialog, key: &str, choice: &str) { d.fields.insert(key.into(), json!(choice)); note_set(d, key); } -/// Records that field `field` was set, from its menu or `ui.dialog.set`, when it is a corner tile. +/// Records that a tile field was set from its menu or `ui.dialog.set`. pub(super) fn note_set(d: &mut Dialog, field: &str) { - if CORNER_TILES.iter().any(|(key, ..)| *key == field) { + if CORNER_TILES.iter().any(|(key, ..)| *key == field) || TILES.iter().any(|(art, _)| tile_key(art) == field) { d.fields.insert(corner_set_key(field), json!(true)); } } @@ -259,18 +308,34 @@ pub(super) fn params(d: &Dialog) -> Value { let def = d.fields.get("__def"); for (key, art, source, other) in CORNER_TILES { let choice = d.str(key); + if let Some(name) = pattern_choice(d, &choice) { + if d.bool(&corner_set_key(key)) { + p[format!("{art}_tile")] = json!({"pattern": name}); + } + continue; + } let unset = |f: &str| def.and_then(|d| d.get(f)).is_none_or(Value::is_null); if choice == CornerSource::None.id() && !d.bool(&corner_set_key(key)) && unset(source) && corner_art_field(def, art).is_none() { continue; } if let Some(s) = CornerSource::parse(&choice) { - p[art] = Value::Null; - p[source] = json!(s.id()); + p[format!("{art}_tile")] = json!(s.id()); } else if choice == "original" && let Some(from) = corner_art_field(def, art).filter(|f| *f != art) && CORNER_TILES.iter().find(|(_, a, _, _)| *a == other).is_some_and(|(k, ..)| d.str(k) != "original") { p[art] = def.and_then(|d| d.get(from)).cloned().unwrap_or_default(); + p[format!("{art}_frame")] = def.and_then(|d| d.get(format!("{from}_frame"))).cloned().unwrap_or(Value::Null); + } + if choice == "original" && d.bool(&corner_set_key(key)) { + p[format!("{art}_tile")] = json!("original"); + } + } + for art in ["side", "start", "end"] { + let key = tile_key(art); + if d.bool(&corner_set_key(&key)) { + let choice = d.str(&key); + p[format!("{art}_tile")] = pattern_choice(d, &choice).map_or_else(|| json!(choice), |name| json!({"pattern": name})); } } p @@ -302,6 +367,35 @@ pub(super) fn edited_def(d: &Dialog) -> Value { if let (Some(o), Value::Object(p)) = (def.as_object_mut(), params(d)) { o.extend(p); } + if d.str("__type") == "pattern" { + for (art, _) in TILES { + let key = tile_key(art); + if !d.bool(&corner_set_key(&key)) { + continue; + } + let choice = d.str(&key); + if choice == "none" || (art.ends_with("corner") && CornerSource::parse(&choice).is_some()) { + def[art] = Value::Null; + def[format!("{art}_frame")] = Value::Null; + def[format!("{art}_swatch")] = Value::Null; + if art.ends_with("corner") { + def[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = json!(choice); + } + } else if choice == "original" { + def[format!("{art}_swatch")] = Value::Null; + } else if let Some(name) = pattern_choice(d, &choice) + && let Some(pattern) = d.fields.get("__patterns").and_then(Value::as_array).and_then(|a| a.iter().find(|p| p["name"] == name)) + && let Ok(pattern) = serde_json::from_value::<PatternDef>(pattern.clone()) + { + def[art] = serde_json::to_value(Node::new(NodeId(0), NodeKind::Group { children: pattern.art, clip: false })).unwrap_or_default(); + def[format!("{art}_frame")] = json!(pattern.tile); + def[format!("{art}_swatch")] = json!(name); + if art.ends_with("corner") { + def[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = Value::Null; + } + } + } + } def } @@ -447,12 +541,12 @@ fn pattern_body(ui: &mut egui::Ui, d: &mut Dialog) { radios(ui, d, "fit", &fits); } -/// What a corner tile can be: (choice, label). Original (the corner art the brush draws there) is -/// offered only when the brush draws corner art there. +/// Built-in corner choices. Original is disabled when the slot has no retained art or a listed +/// swatch was selected. fn corner_choices() -> [(&'static str, &'static str); 6] { [ - ("original", tl!("Original")), (CornerSource::None.id(), tl!("None")), + ("original", tl!("Original")), (CornerSource::AutoCentered.id(), tl!("Auto-Centered")), (CornerSource::AutoBetween.id(), tl!("Auto-Between")), (CornerSource::AutoSliced.id(), tl!("Auto-Sliced")), @@ -460,31 +554,47 @@ fn corner_choices() -> [(&'static str, &'static str); 6] { ] } -/// The pattern's five tiles, each with its art (or None when the brush has no such tile). Below -/// each corner tile, a menu sets it to the brush's art, None or a tile made from the side tile. +pub(super) fn tile_choices(d: &Dialog, corner: bool) -> Vec<(String, String)> { + let mut choices: Vec<(String, String)> = if corner { + corner_choices().into_iter().map(|(id, label)| (id.into(), label.into())).collect() + } else { + vec![("none".into(), tl!("None").into()), ("original".into(), tl!("Original").into())] + }; + choices.extend(pattern_names(d).into_iter().map(|name| (format!("pattern:{name}"), name))); + choices +} + +/// The pattern's five tiles, each with its art (or None when the brush has no such tile). A menu +/// below each preview selects retained art, no art, or a document pattern; corners also offer +/// generated choices. fn tiles(ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); let names = [tl!("Outer Corner Tile"), tl!("Side Tile"), tl!("Inner Corner Tile"), tl!("Start Tile"), tl!("End Tile")]; - let keys = d.fields.get("__tiles").cloned(); + let preview_def = edited_def(d); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 6.0; - for ((field, slot), name) in TILES.into_iter().zip(names) { + for ((field, _slot), name) in TILES.into_iter().zip(names) { let corner = CORNER_TILES.iter().find(|(_, art, _, _)| *art == field).map(|(key, ..)| *key); // The art the tile draws with: its own, or a corner's that falls back on the other's. - let drawn = if corner.is_some() { corner_art_field(d.fields.get("__def"), field) } else { Some(field) }; - let drawn_slot = drawn.and_then(|f| TILES.iter().find(|(tf, _)| *tf == f)).map_or(slot, |(_, s)| *s); - let choices: Vec<(&str, &str)> = corner_choices().into_iter().filter(|(c, _)| drawn.is_some() || *c != "original").collect(); - let choice = corner.map(|key| d.str(key)); + let drawn = if corner.is_some() { corner_art_field(Some(&preview_def), field) } else { Some(field) }; + let choice = d.str(&tile_key(field)); + let original_enabled = original_available(d, field); + let choices = tile_choices(d, corner.is_some()); // The label of the corner's choice when it shows no art. - let shown = choice.as_deref().filter(|c| *c != "original"); - let label = shown.and_then(|c| choices.iter().find(|(id, _)| *id == c)).map_or(tl!("None"), |(_, l)| *l); + let shown = (choice != "original" && pattern_choice(d, &choice).is_none()).then_some(choice.as_str()); + let label = shown.and_then(|c| choices.iter().find(|(id, _)| id == c)).map_or(tl!("None"), |(_, l)| l.as_str()); ui.vertical(|ui| { let (r, resp) = ui.allocate_exact_size(vec2(76.0, 44.0), Sense::hover()); ui.painter().rect_filled(r, 0.0, Color32::WHITE); - let key = keys.as_ref().filter(|_| shown.is_none()).and_then(|k| k.get(drawn_slot)).and_then(Value::as_str); - let tex = key.and_then(|key| { + let art_value = drawn.and_then(|f| preview_def.get(f)).filter(|_| shown.is_none()); + let key = art_value.map(|art| { + let mut h = std::collections::hash_map::DefaultHasher::new(); + art.to_string().hash(&mut h); + format!("brush-tile:{:x}", h.finish()) + }); + let tex = key.as_deref().and_then(|key| { widgets::doc_preview(ui, key, r.size(), |w, h| { - let art: Node = serde_json::from_value(d.fields.get("__def")?.get(drawn?)?.clone()).ok()?; + let art: Node = serde_json::from_value(art_value?.clone()).ok()?; tile_doc(&art, w, h) }) }); @@ -499,14 +609,26 @@ fn tiles(ui: &mut egui::Ui, d: &mut Dialog) { ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); resp.on_hover_text(name); ui.add_sized(vec2(76.0, 14.0), egui::Label::new(egui::RichText::new(name).size(10.5).color(t.text_dim)).truncate()); - if let (Some(key), Some(cur)) = (corner, &choice) { - let current = choices.iter().find(|(id, _)| id == cur).map_or(tl!("None"), |(_, l)| *l); - let labels: Vec<&str> = choices.iter().map(|(_, l)| *l).collect(); - if let Some((id, _)) = - widgets::dropdown_named(ui, ("brush-pattern-corner", key), Some(name), current, &labels, 76.0).and_then(|i| choices.get(i)) - { - choose_corner(d, key, id); - } + let current = choices.iter().find(|(id, _)| id == &choice).map_or(tl!("None"), |(_, l)| l.as_str()); + if let Some(id) = widgets::combo_named(ui, ("brush-pattern-tile", field), Some(name), current, 76.0, |ui| { + choices.iter().enumerate().find_map(|(i, (id, label))| { + ui.add_enabled(id != "original" || original_enabled, egui::Button::selectable(id == &choice, label.as_str())) + .clicked() + .then_some(i) + }) + }) + .and_then(|i| choices.get(i).map(|(id, _)| id.clone())) + { + let key = corner.unwrap_or_else(|| { + if field == "side" { + "sideTile" + } else if field == "start" { + "startTile" + } else { + "endTile" + } + }); + choose_corner(d, key, &id); } }); } diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index f03518b161..19a8e9c6e6 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -97,6 +97,10 @@ pub fn open(app: &mut VectorcraftApp, name: Option<&str>) -> Result<Value, Strin let b: Brush = serde_json::from_value(def.clone()).map_err(|e| e.to_string())?; let mut f = fields(&b, def)?; f.insert("__brush".into(), json!(b.name)); + if let Some(st) = app.session.active() { + f.insert("__patterns".into(), serde_json::to_value(&st.doc.patterns).unwrap_or_default()); + } + brush_art_options::reconcile_pattern_choices(&mut f); app.ui.dialog = Some(Dialog { kind: KIND.into(), fields: f }); Ok(Value::Null) } @@ -149,6 +153,7 @@ fn target(app: &VectorcraftApp) -> Option<String> { /// opens. pub(super) fn open_new(app: &mut VectorcraftApp, ty: &str, ids: Option<Value>) -> Result<Value, String> { let st = app.session.active().ok_or("no document open")?; + let patterns = serde_json::to_value(&st.doc.patterns).unwrap_or_default(); let title: String = ty.chars().take(1).flat_map(char::to_uppercase).chain(ty.chars().skip(1)).collect(); let name = vectorcraft_brush::unique_name(&vectorcraft_brush::library(&st.doc), &format!("New {title} Brush")); let mut def = json!({ "name": name, "type": ty }); @@ -169,6 +174,8 @@ pub(super) fn open_new(app: &mut VectorcraftApp, ty: &str, ids: Option<Value>) - b.sanitize(); let def = serde_json::to_value(&b).map_err(|e| e.to_string())?; let mut f = fields(&b, def)?; + f.insert("__patterns".into(), patterns); + brush_art_options::reconcile_pattern_choices(&mut f); f.insert(CREATE.into(), json!(true)); if let Some(ids) = ids { f.insert(IDS.into(), ids); @@ -183,9 +190,38 @@ pub(super) fn open_new(app: &mut VectorcraftApp, ty: &str, ids: Option<Value>) - /// dialog closes once the brush is made. fn create(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { let mut brush_params = params(d); + if d.str("__type") == "pattern" { + if d.str("sideTile") == "none" { + return Err("You must choose a side pattern.".into()); + } + let preview = brush_art_options::edited_def(d); + for key in [ + "side", + "side_frame", + "side_swatch", + "outer_corner", + "outer_corner_frame", + "outer_corner_swatch", + "outer_source", + "inner_corner", + "inner_corner_frame", + "inner_corner_swatch", + "inner_source", + "start", + "start_frame", + "start_swatch", + "end", + "end_frame", + "end_swatch", + ] { + if let Some(value) = preview.get(key) { + brush_params[key] = value.clone(); + } + } + } if let Some(def) = d.fields.get("__def") { for key in ["art", "side"] { - if let Some(art) = def.get(key).filter(|v| !v.is_null()) { + if let Some(art) = def.get(key).filter(|v| !v.is_null() && brush_params.get(key).is_none_or(Value::is_null)) { brush_params[key] = art.clone(); } } diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 9adeffed1b..83fe73e3c1 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -458,7 +458,7 @@ fn pattern_options_set_each_corner_tile_to_original_none_or_an_automatic_tile() assert!(roles.contains(&egui::accesskit::Role::ComboBox), "a menu named {name}: {roles:?}"); } for name in ["Side Tile", "Start Tile", "End Tile"] { - assert!(!shown_tree.iter().any(|n| n.label() == Some(name) && n.role() == egui::accesskit::Role::ComboBox), "no menu for {name}"); + assert!(shown_tree.iter().any(|n| n.label() == Some(name) && n.role() == egui::accesskit::Role::ComboBox), "a menu for {name}"); } set(&mut app, json!({"outerCornerTile": "autoBetween", "innerCornerTile": "autoOverlap"})); let text = shown(&mut app); @@ -492,6 +492,98 @@ fn pattern_options_set_each_corner_tile_to_original_none_or_an_automatic_tile() assert_eq!(app.ui.dialog.as_ref().unwrap().str("outerCornerTile"), "autoSliced"); } +#[test] +fn pattern_tile_menus_use_document_patterns_and_side_none_keeps_dialog_open() { + use std::sync::Arc; + use vectorcraft_doc::{Node, PatternDef}; + use vectorcraft_geom::Rect; + + let mut app = app(); + app.session + .edit("Pattern", |doc, _| { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), + vectorcraft_doc::Appearance::default_art(), + ); + doc.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new("Wide", vec![Arc::new(art)]) }); + Ok(()) + }) + .unwrap(); + let before = app.run("brush.get", json!({"name":"Diamonds"})).unwrap(); + app.run("ui.brushOptions", json!({"name":"Diamonds"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(crate::dialogs::brush_art_options::pattern_names(d), vec!["Wide".to_string()]); + for key in ["sideTile", "outerCornerTile", "innerCornerTile", "startTile", "endTile"] { + assert!(d.fields.contains_key(key), "{key}"); + } + for corner in [false, true] { + let ids: Vec<_> = crate::dialogs::brush_art_options::tile_choices(d, corner).into_iter().map(|(id, _)| id).collect(); + assert!(ids.contains(&"pattern:Wide".to_string())); + if corner { + for auto in ["autoCentered", "autoBetween", "autoSliced", "autoOverlap"] { + assert!(ids.contains(&auto.to_string())); + } + } else { + assert_eq!(ids.first().map(String::as_str), Some("none")); + assert_eq!(ids.get(1).map(String::as_str), Some("original")); + } + } + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::brush_art_options::choose_corner(d, "sideTile", "Wide"); + assert!(!crate::dialogs::brush_art_options::original_available(d, "side")); + let preview = crate::dialogs::brush_art_options::edited_def(d); + assert_eq!(preview["side_frame"], json!(Rect::new(0.0, 0.0, 10.0, 4.0))); + assert_ne!(preview["side"], before["side"]); + super::super::confirm(&mut app).unwrap(); + app.session + .edit("Delete pattern", |doc, _| { + doc.patterns.clear(); + Ok(()) + }) + .unwrap(); + app.run("ui.brushOptions", json!({"name":"Diamonds"})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("sideTile"), "original"); + let saved = app.run("brush.get", json!({"name":"Diamonds"})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::brush_art_options::choose_corner(d, "sideTile", "none"); + let error = super::super::confirm(&mut app).unwrap_err(); + assert!(error.contains("You must choose a side pattern."), "{error}"); + assert!(app.ui.dialog.is_some()); + assert_eq!(app.run("brush.get", json!({"name":"Diamonds"})).unwrap(), saved); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); +} + +#[test] +fn new_pattern_brush_keeps_a_tile_swatch_choice() { + use std::sync::Arc; + use vectorcraft_doc::{Node, PatternDef}; + use vectorcraft_geom::Rect; + + let mut app = app(); + app.run("shape.rectangle", json!({"x":0,"y":0,"width":20,"height":4})).unwrap(); + app.session + .edit("Pattern", |doc, _| { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), + vectorcraft_doc::Appearance::default_art(), + ); + doc.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new("Wide", vec![Arc::new(art)]) }); + Ok(()) + }) + .unwrap(); + super::open_new(&mut app, "pattern", None).unwrap(); + let name = app.ui.dialog.as_ref().unwrap().str("name"); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::brush_art_options::choose_corner(d, "sideTile", "Wide"); + super::super::confirm(&mut app).unwrap(); + let def = app.run("brush.get", json!({"name":name})).unwrap(); + assert_eq!(def["side_swatch"], "Wide"); + assert_eq!(def["side_frame"], json!(Rect::new(0.0, 0.0, 10.0, 4.0))); +} + /// A pattern brush with art for one kind of corner draws it at both kinds. Its other corner tile /// shows that art as Original, and OK keeps it there when the first corner tile changes. #[test] @@ -509,6 +601,115 @@ fn pattern_options_keep_the_corner_art_a_corner_borrows() { assert_eq!(def["outer_source"], json!("none")); } +#[test] +fn pattern_options_preview_and_save_borrowed_corner_before_clearing_source() { + use vectorcraft_geom::Rect; + + let mut app = app(); + let chain = app.run("brush.get", json!({"name": "Chain"})).unwrap(); + let art = chain["outer_corner"].clone(); + let frame = json!(Rect::new(1.0, 2.0, 15.0, 18.0)); + for (name, source, borrowed) in [("Borrow Outer", "inner", "outer"), ("Borrow Inner", "outer", "inner")] { + let source_art = format!("{source}_corner"); + let source_frame = format!("{source_art}_frame"); + let borrowed_art = format!("{borrowed}_corner"); + let borrowed_frame = format!("{borrowed_art}_frame"); + let source_tile = format!("{source}CornerTile"); + let borrowed_tile = format!("{borrowed}CornerTile"); + app.run("brush.new", json!({"type":"pattern", "name":name, "params":{"side":chain["side"], source_art:art, source_frame:frame}})).unwrap(); + app.run("ui.brushOptions", json!({"name":name})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::brush_art_options::choose_corner(d, &source_tile, "none"); + crate::dialogs::brush_art_options::choose_corner(d, &borrowed_tile, "original"); + let preview = crate::dialogs::brush_art_options::edited_def(d); + assert_eq!(preview[&borrowed_art], chain["outer_corner"], "{borrowed} preview art"); + assert_eq!(preview[&borrowed_frame], frame, "{borrowed} preview frame"); + super::super::confirm(&mut app).unwrap(); + let saved = app.run("brush.get", json!({"name":name})).unwrap(); + assert_eq!(saved[&borrowed_art], chain["outer_corner"], "{borrowed} saved art"); + assert_eq!(saved[&borrowed_frame], frame, "{borrowed} saved frame"); + } +} + +#[test] +fn pattern_options_borrowed_swatch_corner_keeps_its_frame() { + use std::sync::Arc; + use vectorcraft_doc::{Node, PatternDef}; + use vectorcraft_geom::Rect; + + let mut app = app(); + app.session + .edit("Pattern", |doc, _| { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), + vectorcraft_doc::Appearance::default_art(), + ); + doc.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new("Corner", vec![Arc::new(art)]) }); + Ok(()) + }) + .unwrap(); + let side = app.run("brush.get", json!({"name":"Diamonds"})).unwrap()["side"].clone(); + app.run("brush.new", json!({"type":"pattern", "name":"Borrow", "params":{"side":side}})).unwrap(); + app.run("brush.options", json!({"name":"Borrow", "params":{"outer_corner_tile":{"pattern":"Corner"}}})).unwrap(); + let before = app.run("brush.get", json!({"name":"Borrow"})).unwrap(); + app.run("ui.brushOptions", json!({"name":"Borrow"})).unwrap(); + set(&mut app, json!({"outerCornerTile":"none"})); + super::super::confirm(&mut app).unwrap(); + let after = app.run("brush.get", json!({"name":"Borrow"})).unwrap(); + assert_eq!(after["inner_corner"], before["outer_corner"]); + assert_eq!(after["inner_corner_frame"], before["outer_corner_frame"]); + assert_eq!(after["outer_source"], json!("none")); +} + +#[test] +fn pattern_options_selects_swatches_with_reserved_names() { + use std::sync::Arc; + use vectorcraft_doc::{Node, PatternDef}; + use vectorcraft_geom::Rect; + + let mut app = app(); + let names = ["none", "original", "autoCentered", "autoBetween", "autoSliced", "autoOverlap"]; + app.session + .edit("Patterns", |doc, _| { + for name in names { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), + vectorcraft_doc::Appearance::default_art(), + ); + doc.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new(name, vec![Arc::new(art)]) }); + } + Ok(()) + }) + .unwrap(); + app.run("ui.brushOptions", json!({"name":"Diamonds"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + for name in names { + let choice = (format!("pattern:{name}"), name.to_string()); + assert!(crate::dialogs::brush_art_options::tile_choices(d, true).contains(&choice)); + } + for (field, name) in [ + ("sideTile", "none"), + ("outerCornerTile", "original"), + ("innerCornerTile", "autoCentered"), + ("startTile", "autoBetween"), + ("endTile", "autoSliced"), + ] { + crate::dialogs::brush_art_options::choose_corner(app.ui.dialog.as_mut().unwrap(), field, &format!("pattern:{name}")); + } + let preview = crate::dialogs::brush_art_options::edited_def(app.ui.dialog.as_ref().unwrap()); + assert_eq!(preview["side_swatch"], "none"); + super::super::confirm(&mut app).unwrap(); + let saved = app.run("brush.get", json!({"name":"Diamonds"})).unwrap(); + for (art, name) in + [("side", "none"), ("outer_corner", "original"), ("inner_corner", "autoCentered"), ("start", "autoBetween"), ("end", "autoSliced")] + { + assert_eq!(saved[format!("{art}_swatch")], name); + assert_eq!(saved[format!("{art}_frame")], json!(Rect::new(0.0, 0.0, 10.0, 4.0))); + } +} + /// OK leaves the corner fields of a corner tile the menus were not set to as they were: a corner /// without art keeps borrowing the other kind's art when it gets some, and a corner that borrows /// art still borrows it. A None picked from the menu is saved, after another choice too. diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 0888ac645d..2104ac7af6 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5899,6 +5899,9 @@ breakText Glyphs Глифи Gap 4 Разстояние 4 Dash 5 Тире 5 Gap 5 Разстояние 5 +@msg You must choose a side pattern. Трябва да изберете страничен шаблон. +@msg invalid pattern tile choice невалиден избор на плочка за шаблон +@msg no pattern named `{choice}` няма шаблон с име `{choice}` Delete the selected brushes? Да се изтрият избраните четки? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Щрихи използват една или повече от тези четки. Да се премахнат ли четките от тези щрихи и да се изтрият четките? Remove Strokes Премахване на щрихи diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d89af156f8..2d42bf75d5 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5931,6 +5931,9 @@ shape Open Otvoren @msg `follow` must be "average", "a" or "b" `follow` mora biti "average", "a" ili "b" @msg the paths have nothing to merge there putanje tu nemaju šta spojiti @msg the path is locked or hidden putanja je zaključana ili skrivena +@msg You must choose a side pattern. Morate odabrati bočni uzorak. +@msg invalid pattern tile choice nevažeći izbor pločice uzorka +@msg no pattern named `{choice}` nema uzorka pod nazivom `{choice}` Delete the selected brushes? Izbrisati odabrane četkice? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Potezi koriste jednu ili više ovih četkica. Ukloniti četkice s tih poteza i izbrisati četkice? Remove Strokes Ukloni poteze diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 15bd85222d..b7a1506662 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5999,6 +5999,9 @@ breakText Glyphs Glifs Gap 4 Separació 4 Dash 5 Guió 5 Gap 5 Separació 5 +@msg You must choose a side pattern. Heu de triar un patró lateral. +@msg invalid pattern tile choice opció de mosaic de patró no vàlida +@msg no pattern named `{choice}` no hi ha cap patró anomenat `{choice}` Delete the selected brushes? Voleu suprimir els pinzells seleccionats? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Hi ha traços que fan servir un o més d’aquests pinzells. Voleu treure els pinzells d’aquests traços i suprimir els pinzells? Remove Strokes Elimina els traços diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index fe80401bc1..75765ab754 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6008,6 +6008,9 @@ breakText Glyphs Glyfy Gap 4 Mezera 4 Dash 5 Čárka 5 Gap 5 Mezera 5 +@msg You must choose a side pattern. Musíte zvolit boční vzorek. +@msg invalid pattern tile choice neplatná volba dlaždice vzorku +@msg no pattern named `{choice}` vzorek s názvem `{choice}` neexistuje Delete the selected brushes? Odstranit vybrané štětce? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Tahy používají jeden nebo více z těchto štětců. Odebrat štětce z těchto tahů a odstranit štětce? Remove Strokes Odebrat tahy diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 74107e22cb..8140d38e19 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5913,6 +5913,9 @@ breakText Glyphs Glyffer Gap 4 Mellemrum 4 Dash 5 Streg 5 Gap 5 Mellemrum 5 +@msg You must choose a side pattern. Du skal vælge et sidemønster. +@msg invalid pattern tile choice ugyldigt valg af mønsterflise +@msg no pattern named `{choice}` intet mønster med navnet `{choice}` Delete the selected brushes? Slet de valgte pensler? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Streger bruger en eller flere af disse pensler. Fjern penslerne fra stregerne, og slet penslerne? Remove Strokes Fjern streger diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 447c98350d..fa638758f3 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5594,6 +5594,9 @@ breakText Glyphs Glyphen Gap 4 Lücke 4 Dash 5 Strich 5 Gap 5 Lücke 5 +@msg You must choose a side pattern. Sie müssen ein Seitenmuster auswählen. +@msg invalid pattern tile choice ungültige Auswahl einer Musterkachel +@msg no pattern named `{choice}` kein Muster mit dem Namen `{choice}` Delete the selected brushes? Ausgewählte Pinsel löschen? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturen verwenden einen oder mehrere dieser Pinsel. Pinsel von diesen Konturen entfernen und die Pinsel löschen? Remove Strokes Konturen entfernen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 8dea59f7f0..baf6f52ec9 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5961,6 +5961,9 @@ breakText Glyphs Γλύφοι Gap 4 Διάκενο 4 Dash 5 Παύλα 5 Gap 5 Διάκενο 5 +@msg You must choose a side pattern. Πρέπει να επιλέξετε πλευρικό μοτίβο. +@msg invalid pattern tile choice μη έγκυρη επιλογή πλακιδίου μοτίβου +@msg no pattern named `{choice}` δεν υπάρχει μοτίβο με όνομα `{choice}` Delete the selected brushes? Να διαγραφούν τα επιλεγμένα πινέλα; Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Περιγράμματα χρησιμοποιούν ένα ή περισσότερα από αυτά τα πινέλα. Να αφαιρεθούν τα πινέλα από αυτά τα περιγράμματα και να διαγραφούν τα πινέλα; Remove Strokes Αφαίρεση περιγραμμάτων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index e6c7dd7690..7b5b6aae3e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5951,6 +5951,9 @@ breakText Glyphs Glifos Gap 4 Hueco 4 Dash 5 Guion 5 Gap 5 Hueco 5 +@msg You must choose a side pattern. Debe elegir un motivo lateral. +@msg invalid pattern tile choice selección de mosaico de motivo no válida +@msg no pattern named `{choice}` no hay ningún motivo llamado `{choice}` Delete the selected brushes? ¿Eliminar los pinceles seleccionados? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Algunos trazos usan uno o más de estos pinceles. ¿Quitar los pinceles de esos trazos y eliminar los pinceles? Remove Strokes Quitar trazos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 08122ed024..606118dba8 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6039,6 +6039,9 @@ breakText Glyphs Merkit Gap 4 Väli 4 Dash 5 Viiva 5 Gap 5 Väli 5 +@msg You must choose a side pattern. Valitse sivukuvio. +@msg invalid pattern tile choice virheellinen kuviolaatan valinta +@msg no pattern named `{choice}` kuviota nimeltä `{choice}` ei löydy Delete the selected brushes? Poistetaanko valitut siveltimet? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Viivat käyttävät yhtä tai useampaa näistä siveltimistä. Irrotetaanko siveltimet näistä viivoista ja poistetaanko siveltimet? Remove Strokes Poista viivat diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index b35297550a..5e8203d511 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6006,6 +6006,9 @@ breakText Glyphs Glyphes Gap 4 Écart 4 Dash 5 Tiret 5 Gap 5 Écart 5 +@msg You must choose a side pattern. Vous devez choisir un motif latéral. +@msg invalid pattern tile choice choix de tuile de motif non valide +@msg no pattern named `{choice}` aucun motif nommé `{choice}` Delete the selected brushes? Supprimer les formes sélectionnées ? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Des contours utilisent une ou plusieurs de ces formes. Retirer les formes de ces contours et supprimer les formes ? Remove Strokes Supprimer les contours diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index cac7189ed7..aec44044da 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5995,6 +5995,9 @@ breakText Glyphs Glifák Gap 4 Hézag 4 Dash 5 Vonal 5 Gap 5 Hézag 5 +@msg You must choose a side pattern. Válasszon oldalsó mintát. +@msg invalid pattern tile choice érvénytelen mintacsempe-választás +@msg no pattern named `{choice}` nincs `{choice}` nevű minta Delete the selected brushes? Törlöd a kijelölt ecseteket? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Körvonalak használnak egyet vagy többet ezek közül az ecsetek közül. Leveszed az ecseteket ezekről a körvonalakról, és törlöd az ecseteket? Remove Strokes Körvonalak eltávolítása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 29e87826ab..5329eea88d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5913,6 +5913,9 @@ breakText Glyphs Glif Gap 4 Jarak 4 Dash 5 Garis 5 Gap 5 Jarak 5 +@msg You must choose a side pattern. Anda harus memilih pola sisi. +@msg invalid pattern tile choice pilihan ubin pola tidak valid +@msg no pattern named `{choice}` tidak ada pola bernama `{choice}` Delete the selected brushes? Hapus kuas yang dipilih? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Stroke menggunakan satu atau beberapa kuas ini. Lepaskan kuas dari stroke tersebut dan hapus kuasnya? Remove Strokes Hapus Stroke diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 51870220aa..34c18549d2 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5628,6 +5628,9 @@ breakText Glyphs Glifi Gap 4 Spazio 4 Dash 5 Tratto 5 Gap 5 Spazio 5 +@msg You must choose a side pattern. Devi scegliere un motivo laterale. +@msg invalid pattern tile choice scelta della tessera motivo non valida +@msg no pattern named `{choice}` nessun motivo chiamato `{choice}` Delete the selected brushes? Eliminare i pennelli selezionati? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Alcune tracce usano uno o più di questi pennelli. Rimuovere i pennelli da queste tracce ed eliminare i pennelli? Remove Strokes Rimuovi tracce diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c6c4227b6b..5d8e120742 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5694,6 +5694,9 @@ breakText Glyphs 字形 Gap 4 間隔 4 Dash 5 線分 5 Gap 5 間隔 5 +@msg You must choose a side pattern. 側面パターンを選択してください。 +@msg invalid pattern tile choice パターンタイルの選択が無効です +@msg no pattern named `{choice}` `{choice}` というパターンはありません Delete the selected brushes? 選択したブラシを削除しますか? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? これらのブラシの 1 つ以上が線で使われています。それらの線からブラシを外して、ブラシを削除しますか? Remove Strokes 線を削除 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index c02d40eb17..ab0f0704d5 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5998,6 +5998,9 @@ breakText Glyphs გლიფები Gap 4 შუალედი 4 Dash 5 ტირე 5 Gap 5 შუალედი 5 +@msg You must choose a side pattern. აირჩიეთ გვერდითი ნიმუში. +@msg invalid pattern tile choice ნიმუშის ფილა არასწორად არის არჩეული +@msg no pattern named `{choice}` ნიმუში სახელით `{choice}` არ არსებობს Delete the selected brushes? წაიშალოს არჩეული ფუნჯები? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? კონტურები იყენებს ამ ფუნჯებიდან ერთს ან მეტს. მოიხსნას ფუნჯები ამ კონტურებიდან და წაიშალოს ფუნჯები? Remove Strokes კონტურების მოხსნა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 5c24bd9ca2..5da60d2476 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5591,6 +5591,9 @@ breakText Glyphs 글리프 Gap 4 간격 4 Dash 5 대시 5 Gap 5 간격 5 +@msg You must choose a side pattern. 측면 패턴을 선택해야 합니다. +@msg invalid pattern tile choice 잘못된 패턴 타일 선택 +@msg no pattern named `{choice}` `{choice}` 이름의 패턴이 없습니다 Delete the selected brushes? 선택한 브러시를 삭제하시겠습니까? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 선에서 이 브러시 중 하나 이상을 사용합니다. 해당 선에서 브러시를 제거하고 브러시를 삭제하시겠습니까? Remove Strokes 선 제거 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 282b0a4aad..ee4e09b61f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5957,6 +5957,9 @@ breakText Glyphs Glyphs Gap 4 Tussenruimte 4 Dash 5 Streepje 5 Gap 5 Tussenruimte 5 +@msg You must choose a side pattern. Kies een zijpatroon. +@msg invalid pattern tile choice ongeldige keuze voor patroontegel +@msg no pattern named `{choice}` geen patroon met de naam `{choice}` Delete the selected brushes? Geselecteerde kwasten verwijderen? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Contouren gebruiken een of meer van deze kwasten. De kwasten van deze contouren halen en de kwasten verwijderen? Remove Strokes Contouren verwijderen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 3999714470..5c90b4d977 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5864,6 +5864,9 @@ breakText Glyphs Glify Gap 4 Odstęp 4 Dash 5 Kreska 5 Gap 5 Odstęp 5 +@msg You must choose a side pattern. Musisz wybrać wzór boczny. +@msg invalid pattern tile choice nieprawidłowy wybór kafelka wzoru +@msg no pattern named `{choice}` nie ma wzoru o nazwie `{choice}` Delete the selected brushes? Usunąć zaznaczone pędzle? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Obrysy używają co najmniej jednego z tych pędzli. Zdjąć pędzle z tych obrysów i usunąć pędzle? Remove Strokes Usuń obrysy diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4f75dd659d..0694d8f183 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5928,6 +5928,9 @@ breakText Glyphs Glifos Gap 4 Lacuna 4 Dash 5 Traço 5 Gap 5 Lacuna 5 +@msg You must choose a side pattern. Você deve escolher um padrão lateral. +@msg invalid pattern tile choice escolha inválida de ladrilho de padrão +@msg no pattern named `{choice}` não há padrão chamado `{choice}` Delete the selected brushes? Excluir os pincéis selecionados? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Traçados usam um ou mais destes pincéis. Remover os pincéis desses traçados e excluir os pincéis? Remove Strokes Remover Traçados diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d412fa13bc..105ba72d17 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5986,6 +5986,9 @@ breakText Glyphs Глифы Gap 4 Зазор 4 Dash 5 Штрих 5 Gap 5 Зазор 5 +@msg You must choose a side pattern. Выберите боковой узор. +@msg invalid pattern tile choice недопустимый выбор плитки узора +@msg no pattern named `{choice}` узор с именем `{choice}` не найден Delete the selected brushes? Удалить выбранные кисти? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Обводки используют одну или несколько из этих кистей. Убрать кисти с этих обводок и удалить кисти? Remove Strokes Убрать обводки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 2a1ba37453..4831119887 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6061,6 +6061,9 @@ breakText Glyphs Glyfer Gap 4 Mellanrum 4 Dash 5 Streck 5 Gap 5 Mellanrum 5 +@msg You must choose a side pattern. Du måste välja ett sidomönster. +@msg invalid pattern tile choice ogiltigt val av mönsterplatta +@msg no pattern named `{choice}` inget mönster med namnet `{choice}` Delete the selected brushes? Radera de valda penslarna? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturer använder en eller flera av de här penslarna. Ta bort penslarna från konturerna och radera penslarna? Remove Strokes Ta bort konturer diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 215b7f8e6d..23bdb68391 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5966,6 +5966,9 @@ breakText Glyphs Glifler Gap 4 Boşluk 4 Dash 5 Çizgi 5 Gap 5 Boşluk 5 +@msg You must choose a side pattern. Bir yan desen seçmelisiniz. +@msg invalid pattern tile choice geçersiz desen döşemesi seçimi +@msg no pattern named `{choice}` `{choice}` adlı desen yok Delete the selected brushes? Seçili fırçalar silinsin mi? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturlar bu fırçalardan birini veya daha fazlasını kullanıyor. Fırçalar bu konturlardan kaldırılsın ve fırçalar silinsin mi? Remove Strokes Konturları Kaldır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 13fab3c518..dde23c7422 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5608,6 +5608,9 @@ breakText Glyphs Гліфи Gap 4 Проміжок 4 Dash 5 Штрих 5 Gap 5 Проміжок 5 +@msg You must choose a side pattern. Виберіть бічний візерунок. +@msg invalid pattern tile choice недійсний вибір плитки візерунка +@msg no pattern named `{choice}` візерунка з назвою `{choice}` немає Delete the selected brushes? Видалити вибрані пензлі? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Обведення використовують один або кілька з цих пензлів. Забрати пензлі з цих обведень і видалити пензлі? Remove Strokes Забрати обведення diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f45d5d04ae..e060c09993 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5610,6 +5610,9 @@ breakText Glyphs Glyph Gap 4 Khoảng hở 4 Dash 5 Nét 5 Gap 5 Khoảng hở 5 +@msg You must choose a side pattern. Bạn phải chọn mẫu bên. +@msg invalid pattern tile choice lựa chọn ô mẫu không hợp lệ +@msg no pattern named `{choice}` không có mẫu tên `{choice}` Delete the selected brushes? Xóa các cọ đã chọn? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Có nét đang dùng một hoặc nhiều cọ này. Gỡ cọ khỏi các nét đó và xóa cọ? Remove Strokes Gỡ nét diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 4e105573f1..65842950a7 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5850,6 +5850,9 @@ breakText Glyphs 字形 Gap 4 间隔 4 Dash 5 虚线 5 Gap 5 间隔 5 +@msg You must choose a side pattern. 必须选择侧边图案。 +@msg invalid pattern tile choice 图案拼块选项无效 +@msg no pattern named `{choice}` 没有名为 `{choice}` 的图案 Delete the selected brushes? 删除选中的画笔吗? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 有描边使用了其中一个或多个画笔。要从这些描边移除画笔并删除画笔吗? Remove Strokes 移除描边 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index acb8291996..fb06daa662 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5647,6 +5647,9 @@ breakText Glyphs 字符 Gap 4 間隙 4 Dash 5 虛線 5 Gap 5 間隙 5 +@msg You must choose a side pattern. 必須選擇側邊圖樣。 +@msg invalid pattern tile choice 圖樣拼塊選項無效 +@msg no pattern named `{choice}` 沒有名為 `{choice}` 的圖樣 Delete the selected brushes? 要刪除選取的筆刷嗎? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 有筆畫使用了其中一個或多個筆刷。要從這些筆畫移除筆刷並刪除筆刷嗎? Remove Strokes 移除筆畫 diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 107350b749..c6b855ffdc 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -40,7 +40,7 @@ pub use color::{ pub use drag::{PanelDrag, SwatchRows, art_drop, doc_preview, drag_source}; #[cfg(test)] use dropdowns::combo_button_id; -pub(crate) use dropdowns::{combo, combo_menu}; +pub(crate) use dropdowns::{combo, combo_menu, combo_named}; pub use dropdowns::{ dropdown, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, dropdown_with_named, list_scroll_style, menu_room, menu_scroll, panel_scroll, popover, set_menu_floor, strip_scroll, diff --git a/docs/gaps.md b/docs/gaps.md index b7ffe7f758..072ee477a3 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -536,13 +536,11 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall dragging one onto the Brushes panel adds it; Save Brushes / Save Brush Library writes the document's brushes as a `.vectorcraft` library into the user library folder (listed under User Defined) or a file (`brush.libraries`, `brush.addFromLibrary`, `brush.saveLibrary`, `brush.loadLibrary`). -- **Missing:** the Art brush's Overlap, auto-generated Pattern brush corners, new tile art in Pattern Brush - Options; more built-in brush, symbol and graphic-style libraries (original, generated in code, never - Adobe's); dynamic symbols; Global Edit of similar groups (edits to an object inside a group reaching the - matching objects of similar groups, [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)), +- **Missing:** the Art brush's Overlap; more built-in brush, symbol and graphic-style libraries (original, + generated in code, never Adobe's); dynamic symbols; Global Edit of similar groups (edits to an object inside a + group reaching the matching objects of similar groups, [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)), rotated copies as matches, Shift-click to leave a match out and highlighting matches before the start; drawing the 9-slice guides on the canvas in symbol edit mode and scaling by them. - Options; more built-in brush and symbol libraries (original, never Adobe's); dynamic symbols; Start Global Edit; drawing the 9-slice guides on the canvas in symbol edit mode and scaling by them. - **Estimate:** 15–26 h. ## G3 3D and Materials diff --git a/docs/mcp.md b/docs/mcp.md index 1f843271e9..0595340df1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1578,7 +1578,12 @@ already walks Image Trace. Short agent entry points: what that kind of corner draws when the brush has no `outer_corner` or `inner_corner` art for it: `none` draws no corner tile, and `autoCentered`, `autoBetween`, `autoSliced` and `autoOverlap` make one from the side tile. Without a source, the corner draws the other kind of corner's art. `brush.options {params: {outer_corner: null}}` removes - the art. + the art. Pattern Brush Options also accepts `side_tile`, `outer_corner_tile`, `inner_corner_tile`, + `start_tile` and `end_tile` in `params`. Each takes `none`, `original` or the name of a pattern + swatch in the active document, and `{"pattern": "<name>"}` names a swatch even when its name is one of those + words. Corner tiles also take `autoCentered`, `autoBetween`, `autoSliced` and `autoOverlap`. A swatch choice copies its whole art and tile frame into the brush. `original` + keeps the current art and clears its swatch label. `side_tile: "none"` fails with "You must choose a + side pattern." An unknown swatch name also fails; neither error edits the brush or adds an Undo step. - Variables: `variable.list`, `variable.define {name, kind: text|visibility|image|graph}`, `variable.bind {variable, ids?}`, `variable.makeTextDynamic`, `variable.makeVisibilityDynamic`, `variable.makeImageDynamic`, `variable.makeGraphDynamic`, `variable.unbind`, `variable.rename`, `variable.delete`, `variable.highlight` (image values are file paths, graph diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c53382a210..3d706ba6bb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -954,7 +954,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. Points in different models mix in display RGB, and a CMYK document stores the result as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty more arrowheads, and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. - - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random or Pressure with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values or Pressure from the first at the lightest pressure to the second at the heaviest; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Still to come: the Art brush's Overlap, auto-generated Pattern brush corners, new tile art picked in Pattern Brush Options, Stylus Wheel, Tilt, Bearing and Rotation, and pen pressure on macOS. + - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random or Pressure with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values or Pressure from the first at the lightest pressure to the second at the heaviest; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Still to come: the Art brush's Overlap, Stylus Wheel, Tilt, Bearing and Rotation, and pen pressure on macOS. Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method (<https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html>) and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. Stylus Wheel, Tilt, Bearing and Rotation are not built. @@ -968,6 +968,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Brushes panel menu's Select All Unused selects the brushes that are not used in the document, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. A brush counts as used when a stroke paints with it in the art (opacity masks included), in symbols, graph designs, pattern tiles or graphic styles, or in the art of a used brush (`brush.unused`). A rename in Brush Options and Delete Brush change every stroke that paints with the brush: in the layers and opacity masks, symbols, graph designs, pattern tiles, graphic styles and the art of other brushes. A rename gives those strokes the new name, and Delete Brush makes them plain strokes, in one undo step. In Pattern Brush Options, a menu below the Outer Corner Tile and the Inner Corner Tile sets each to the brush's own corner art (Original), None, or a tile made from the side tile: Auto-Centered stretches one side tile around the corner, Auto-Between bends a side tile on each side into the corner's diagonal, Auto-Sliced cuts a side tile on each side along the diagonal, and Auto-Overlap runs a side tile on each side past the corner. Auto-Sliced masks the tiles at the diagonal, so their outlines stay as drawn. Brushes saved without these choices draw their corners as before (`brush.options` `outer_source`, `inner_source`). Evidence: `tests::pattern_auto_corners_fill_each_corner_of_a_square`, `tests::pattern_corner_source_none_leaves_that_kind_of_corner_empty` (vectorcraft-brush), `dialogs::brush_options::tests::pattern_options_set_each_corner_tile_to_original_none_or_an_automatic_tile` (vectorcraft-ui-egui). + - The [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) page describes up to five Pattern brush tiles: sides, inner corner, outer corner, beginning and end. The archived [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says to add pattern tiles to the Swatches panel and select a swatch from the scroll list for each tile. Pattern Brush Options offers document pattern swatches in all five tile menus, including swatches named like built-in choices. The brush copies each swatch's whole art and tile frame. Side requires art; explicit None on a corner prevents fallback to the other corner's art. After a swatch is deleted, the brush keeps drawing its copied art and shows it as Original. The cited pages do not describe copying the whole art, requiring Side, suppressing corner fallback after explicit None, or showing deleted swatch art as Original. `brush.options` accepts swatch names and an object form for names that match built-in choices, and rejects unknown patterns before editing. Evidence: `tests::brushsym::pattern_tile_choices_copy_whole_swatch_art_and_reject_invalid_side` and `tests::brushsym::pattern_tile_object_selects_reserved_swatch_names` (vectorcraft-engine), `tests::pattern_corner_source_none_leaves_that_kind_of_corner_empty` (vectorcraft-brush), and `dialogs::brush_options::tests::pattern_tile_menus_use_document_patterns_and_side_none_keeps_dialog_open`, `dialogs::brush_options::tests::pattern_options_borrowed_swatch_corner_keeps_its_frame`, and `dialogs::brush_options::tests::pattern_options_selects_swatches_with_reserved_names` (vectorcraft-ui-egui). - **Appearance:** the Appearance panel's selected row drives every paint, stroke, gradient and transparency edit (`item` on the commands); effects apply to one fill or stroke; per-item Opacity popups, whose blend-mode list and opacity slider stay open inside them (#430; the Control bar's Stroke popover too); Mixed Appearances, Layers target dots and basic-appearance rules. Effects can be reordered, moved between items and copied by dragging; Show All Hidden Attributes; clicking an effect edits it in place; the object thumbnail drags onto art; effects render on type, images, symbols, blends, envelopes, meshes and repeats, and per-item raster effects export. Groups, layers and type have their own fills, strokes and effects (Contents and Characters rows); the Layers panel's target circles target layers, groups and objects; Expand Appearance turns fills, strokes, effects and brushes into objects. Fill and stroke paint (Fill, Stroke, None, Apply Last Color and Apply Last Gradient, also on characters selected with the Type tool), the Stroke panel's options, gradient and freeform point edits, Swap Fill and Stroke, Default Fill and Stroke, the Eyedropper, and the Appearance panel's item edits, Clear Appearance, Reduce to Basic Appearance, Remove Item, item reordering and Move Appearance record no undo step when they change nothing. An image's own fills and strokes draw the shape that a Convert to Shape or Outline Object effect on them gives them (the image's box or its frame, reshaped by the effects after it), under or over the image as its Contents row says, on the canvas, in exports and through Expand Appearance; new fills and strokes on an image go under it. Without one of those effects they draw nothing, and Use Preview Bounds measures an image by its frame. From 9896f633dabeb52e04cbf3ddafcf6798d784eb95 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 1 Nov 2026 00:39:08 +0700 Subject: [PATCH 136/260] Type: Kerning has an Optical option that spaces characters by their shapes Squashed from #4825 onto main. --- crates/doc/src/tests.rs | 12 + crates/doc/src/text/char_style.rs | 6 +- crates/doc/src/text/tabs_lists.rs | 1 + crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/panelcmds.rs | 19 +- crates/engine/src/cmd/textedit.rs | 97 ++++++- crates/engine/src/cmd/textstyles.rs | 1 + crates/engine/src/cmd/textstyles/tests.rs | 14 + crates/engine/src/tests/textedit.rs | 164 ++++++++++- crates/text/src/shape.rs | 282 ++++++++++++++++++- crates/text/src/test_fonts.rs | 75 +++++ crates/text/src/tests/typo.rs | 261 +++++++++++++++++ crates/text/src/tests/vertical.rs | 24 ++ crates/ui-egui/src/i18n/bg.tsv | 4 +- crates/ui-egui/src/i18n/bs.tsv | 4 +- crates/ui-egui/src/i18n/ca.tsv | 4 +- crates/ui-egui/src/i18n/cs.tsv | 4 +- crates/ui-egui/src/i18n/da.tsv | 4 +- crates/ui-egui/src/i18n/de.tsv | 4 +- crates/ui-egui/src/i18n/el.tsv | 4 +- crates/ui-egui/src/i18n/es.tsv | 4 +- crates/ui-egui/src/i18n/fi.tsv | 4 +- crates/ui-egui/src/i18n/fr.tsv | 4 +- crates/ui-egui/src/i18n/hu.tsv | 4 +- crates/ui-egui/src/i18n/id.tsv | 4 +- crates/ui-egui/src/i18n/it.tsv | 4 +- crates/ui-egui/src/i18n/ja.tsv | 4 +- crates/ui-egui/src/i18n/ka.tsv | 4 +- crates/ui-egui/src/i18n/ko.tsv | 4 +- crates/ui-egui/src/i18n/nl.tsv | 4 +- crates/ui-egui/src/i18n/pl.tsv | 4 +- crates/ui-egui/src/i18n/pt-br.tsv | 4 +- crates/ui-egui/src/i18n/ru.tsv | 4 +- crates/ui-egui/src/i18n/sv.tsv | 4 +- crates/ui-egui/src/i18n/tests.rs | 2 +- crates/ui-egui/src/i18n/tr.tsv | 4 +- crates/ui-egui/src/i18n/uk.tsv | 4 +- crates/ui-egui/src/i18n/vi.tsv | 4 +- crates/ui-egui/src/i18n/zh-hans.tsv | 4 +- crates/ui-egui/src/i18n/zh-hant.tsv | 4 +- crates/ui-egui/src/panels/character.rs | 60 +++- crates/ui-egui/src/panels/character/tests.rs | 32 +++ crates/ui-egui/src/widgets.rs | 2 +- crates/ui-egui/src/widgets/numeric.rs | 59 +++- docs/mcp.md | 13 +- docs/target-app-parity.md | 3 +- docs/typography-lettering.md | 2 +- 47 files changed, 1165 insertions(+), 69 deletions(-) diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index a13fb21680..0b205a5b16 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -388,6 +388,18 @@ fn char_position_round_trips() { assert!((scale - 0.583).abs() < 1e-9 && (shift + 3.33).abs() < 1e-9); } +#[test] +fn optical_kerning_round_trips_and_old_style_defaults_to_auto() { + let st = CharStyle { optical_kerning: true, kerning: Some(120.0), ..CharStyle::default() }; + let value = serde_json::to_value(&st).unwrap(); + assert_eq!(value["opticalKerning"], true); + assert_eq!(serde_json::from_value::<CharStyle>(value.clone()).unwrap(), st); + let mut old = value; + old.as_object_mut().unwrap().remove("opticalKerning"); + assert!(!serde_json::from_value::<CharStyle>(old).unwrap().optical_kerning); + assert!(serde_json::to_value(CharStyle::default()).unwrap().get("opticalKerning").is_none()); +} + #[test] fn units() { assert_eq!(Unit::Inches.parse("1"), Some(72.0)); diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index 0e3aea70e9..5189e7aa28 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -25,9 +25,12 @@ pub struct CharStyle { /// Tracking in 1/1000 em. #[serde(default)] pub tracking: f64, - /// Kerning: None = Auto (metrics), Some(v) = manual in 1/1000 em. + /// Manual pair spacing in 1/1000 em; None uses the automatic mode. #[serde(default, skip_serializing_if = "Option::is_none")] pub kerning: Option<f64>, + /// Use glyph shapes for automatic pair spacing; false uses font metrics. + #[serde(default, rename = "opticalKerning", skip_serializing_if = "crate::skip::is_default")] + pub optical_kerning: bool, #[serde(default)] pub baseline_shift: f64, #[serde(default = "hundred")] @@ -266,6 +269,7 @@ impl Default for CharStyle { leading: None, tracking: 0.0, kerning: None, + optical_kerning: false, baseline_shift: 0.0, h_scale: 100.0, v_scale: 100.0, diff --git a/crates/doc/src/text/tabs_lists.rs b/crates/doc/src/text/tabs_lists.rs index 47106d7882..b66795e890 100644 --- a/crates/doc/src/text/tabs_lists.rs +++ b/crates/doc/src/text/tabs_lists.rs @@ -223,6 +223,7 @@ impl ParaList { position: CharPosition::Normal, tracking: 0.0, kerning: None, + optical_kerning: first.optical_kerning, tate_chu_yoko: false, underline: false, strikethrough: false, diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 2d9fea923f..8758262628 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -87,6 +87,7 @@ pub mod swatchlib; pub mod symbollib; pub(crate) mod tabs; mod textedit; +pub use textedit::effective_kerning; pub mod textstyles; pub(crate) mod textwrap; pub(crate) mod threads; diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 969daf4f6b..4c52da717e 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", has_doc, set_format ), @@ -323,7 +323,13 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { let kerning = match p.get("kerning") { None | Some(Value::Null) => None, Some(Value::String(a)) if a.eq_ignore_ascii_case("auto") => Some(None), - Some(v) => Some(Some(v.as_f64().ok_or_else(|| bad(C, "kerning must be a number or \"auto\""))?.clamp(-1000.0, 10000.0))), + Some(Value::String(a)) if a.eq_ignore_ascii_case("optical") => None, + Some(v) => Some(Some(v.as_f64().ok_or_else(|| bad(C, "kerning must be a number, \"auto\", or \"optical\""))?.clamp(-1000.0, 10000.0))), + }; + let optical_kerning = match p.get("kerning") { + Some(Value::String(a)) if a.eq_ignore_ascii_case("auto") => Some(false), + Some(Value::String(a)) if a.eq_ignore_ascii_case("optical") => Some(true), + _ => None, }; let keys = [ "kerning", @@ -479,6 +485,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { if let Some(k) = kerning { st.kerning = k; } + if let Some(v) = optical_kerning { + st.optical_kerning = v; + } if let Some(v) = baseline_shift { st.baseline_shift = v; } @@ -649,7 +658,11 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { } Ok(()) })?; - Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })) + let mut result = json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }); + if let Some(kerning) = p.get("kerning") { + result["kerning"] = kerning.clone(); + } + Ok(result) } /// The part of a story paragraph in one frame, as [`convert_list_to_text`] reads it: the frame, diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index cb4a51354a..8d393a58e9 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> { "Reset Tracking and Kerning", [], Some("Cmd+Alt+Q"), - "{ids?: [id…]} set tracking to 0 and kerning to Auto (the font's own kerning, which the Character panel shows as 0) in all the text of the type objects in `ids`, else in the text the Type tool has selected (at a caret: only the kerning of the character before it), else in every selected type object, as one undo step → {ids}", + "{ids?: [id…]} set tracking to 0 and clear manual kerning without changing the automatic method in all the text of the type objects in `ids`, else in the text the Type tool has selected (at a caret: only the kerning of the character before it), else in every selected type object, as one undo step → {ids}", has_selection, reset_tracking ), @@ -300,6 +300,7 @@ pub(crate) struct CharChange { leading: Option<Option<f64>>, tracking: Option<f64>, kerning: Option<Option<f64>>, + optical_kerning: Option<bool>, baseline_shift: Option<f64>, h_scale: Option<f64>, v_scale: Option<f64>, @@ -476,7 +477,17 @@ impl CharChange { size: num("size"), leading: auto_or_num(p, "leading", cmd)?, tracking: num("tracking"), - kerning: auto_or_num(p, "kerning", cmd)?, + kerning: match p.get("kerning") { + None | Some(Value::Null) => None, + Some(Value::String(v)) if v.eq_ignore_ascii_case("optical") => None, + Some(Value::String(v)) if v.eq_ignore_ascii_case("auto") => Some(None), + Some(v) => Some(Some(v.as_f64().ok_or_else(|| bad(cmd, "kerning must be a number, \"auto\", or \"optical\""))?)), + }, + optical_kerning: match p.get("kerning") { + Some(Value::String(v)) if v.eq_ignore_ascii_case("optical") => Some(true), + Some(Value::String(v)) if v.eq_ignore_ascii_case("auto") => Some(false), + _ => None, + }, baseline_shift: num("baselineShift"), h_scale: num("hScale"), v_scale: num("vScale"), @@ -521,6 +532,7 @@ impl CharChange { && self.leading.is_none() && self.tracking.is_none() && self.kerning.is_none() + && self.optical_kerning.is_none() && self.baseline_shift.is_none() && self.h_scale.is_none() && self.v_scale.is_none() @@ -583,6 +595,9 @@ impl CharChange { if let Some(v) = self.kerning { st.kerning = v.map(|k| k.clamp(-1000.0, 10000.0)); } + if let Some(v) = self.optical_kerning { + st.optical_kerning = v; + } if let Some(v) = self.baseline_shift { st.baseline_shift = v; } @@ -734,18 +749,53 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result<Value> { if let Some(w) = super::fonts::set_font_warning(set) { out["warning"] = json!(w); } + if let Some(kerning) = p.get("kerning") { + out["kerning"] = kerning.clone(); + } Ok(out) } /// The em a laid-out glyph's kerning and tracking are measured in, in text space: the size it /// was shaped at (superscript, small caps and Shrink Text to Fit included). -fn glyph_em(t: &TextObject, g: &vectorcraft_text::PositionedGlyph) -> Option<f64> { - let face = vectorcraft_text::FontDb::global().face_by_id(g.font_id)?; +fn glyph_em(db: &vectorcraft_text::FontDb, t: &TextObject, g: &vectorcraft_text::PositionedGlyph) -> Option<f64> { + let face = db.face_by_id(g.font_id)?; let h_scale = edit::slice_runs(&t.runs, g.byte, g.byte + g.len).first()?.style.h_scale / 100.0; let [a, b, ..] = g.xf.as_coeffs(); Some(a.hypot(b) * face.units_per_em() / h_scale).filter(|em| em.is_finite() && *em > 0.0) } +/// The current pair correction in thousandths of an em, including an automatic correction. +pub fn effective_kerning(db: &vectorcraft_text::FontDb, t: &TextObject, lay: &vectorcraft_text::TextLayout, x: usize, y: usize) -> f64 { + if let Some(value) = edit::slice_runs(&t.runs, x, y).first().and_then(|r| r.style.kerning) { + return value; + } + // Measure both layouts without wrapping so the same pair stays on one line. + let mut trial = t.clone(); + trial.kind = TextKind::Point; + let unwrapped = (!matches!(t.kind, TextKind::Point)).then(|| vectorcraft_text::layout(db, &trial)); + let original = unwrapped.as_ref().unwrap_or(lay); + edit::style_range(&mut trial.runs, x, y, |st| st.kerning = Some(0.0)); + let base = vectorcraft_text::layout(db, &trial); + let owner = original.glyphs.iter().find(|g| g.byte == x); + let rtl = owner.is_some_and(|g| g.rtl); + let drawn_gap = |layout: &vectorcraft_text::TextLayout| { + let first = layout.glyphs.iter().find(|g| g.byte == if rtl { y } else { x })?; + let following = layout.glyphs.iter().find(|g| g.byte == if rtl { x } else { y })?; + if first.line != following.line { + return None; + } + let axis = vectorcraft_geom::Vec2::new(first.angle.cos(), first.angle.sin()); + let along = if rtl { -axis } else { axis }; + let drawn = |g: &vectorcraft_text::PositionedGlyph| { + let [_, _, _, _, tx, ty] = g.xf.as_coeffs(); + Point::new(tx, ty) + }; + Some((drawn(following) - drawn(first)).dot(along)) + }; + let em = owner.and_then(|g| glyph_em(db, t, g)).unwrap_or(0.0); + if em > 0.0 { drawn_gap(original).zip(drawn_gap(&base)).map_or(0.0, |(a, b)| (a - b) * 1000.0 / em) } else { 0.0 } +} + fn touch_type(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.touchType"; let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; @@ -780,18 +830,21 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> { // A list marker's glyphs (length 0) stand for no character. let prev = lay.glyphs.iter().find(|h| h.line == g.line && h.len > 0 && h.byte + h.len == a); let pr = prev.map(|h| (h.byte, h.byte + h.len)); - let em = glyph_em(&t, g).ok_or_else(|| bad(C, "the character's size can't be measured"))?; + let db = vectorcraft_text::FontDb::global(); + let em = glyph_em(db, &t, g).ok_or_else(|| bad(C, "the character's size can't be measured"))?; let em_prev = match prev { - Some(h) => Some(glyph_em(&t, h).ok_or_else(|| bad(C, "the character's size can't be measured"))?), + Some(h) => Some(glyph_em(db, &t, h).ok_or_else(|| bad(C, "the character's size can't be measured"))?), None if dx != 0.0 => return Err(bad(C, "the first character of a line has no character before it to kern: it moves only up and down (dy)")), None => None, }; - let kerning_in = |(x, y): (usize, usize)| edit::slice_runs(&t.runs, x, y).first().and_then(|r| r.style.kerning).unwrap_or(0.0); + let kerning_in = |(x, y): (usize, usize)| effective_kerning(db, &t, &lay, x, y); + let original_before = pr.map(kerning_in); + let original_own = kerning_in((a, b)); // The move along the line, in text space, limited to what kerning from -1000 to 10000 (1/1000 // em) on the character before it and on the character itself can give. let mut moved = dx / doc_len(along); - if let (Some(range), Some(ep)) = (pr, em_prev) { - let (kp, kc) = (kerning_in(range), kerning_in((a, b))); + if let (Some(_range), Some(ep)) = (pr, em_prev) { + let (kp, kc) = (original_before.unwrap_or(0.0), original_own); let hi = ((10000.0 - kp) * ep).min((kc + 1000.0) * em) / 1000.0; let lo = ((-1000.0 - kp) * ep).max((kc - 10000.0) * em) / 1000.0; if lo <= hi { @@ -803,7 +856,8 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> { let touch = |t: &mut TextObject, before: Option<f64>, own: Option<f64>, raise: f64| { for (range, by) in [(pr, before), (Some((a, b)), own)] { if let (Some((x, y)), Some(by)) = (range, by) { - edit::style_range(&mut t.runs, x, y, |st| st.kerning = Some((st.kerning.unwrap_or(0.0) + by).clamp(-1000.0, 10000.0))); + let original = if (x, y) == (a, b) { original_own } else { original_before.unwrap_or(0.0) }; + edit::style_range(&mut t.runs, x, y, |st| st.kerning = Some((original + by).clamp(-1000.0, 10000.0))); } } edit::style_range(&mut t.runs, a, b, |st| { @@ -1086,9 +1140,20 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> { } _ => None, })?; + let mut caret_kerning = Vec::with_capacity(ranges.len()); + for &(id, a, b, caret) in &ranges { + let value = if matches!(step, Step::Kerning) && caret { + let t = text_ref(s, id)?; + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + Some(effective_kerning(vectorcraft_text::FontDb::global(), &t, &lay, a, b)) + } else { + None + }; + caret_kerning.push(value); + } if !ranges.is_empty() { s.edit("Character", |d, _| { - for &(id, a, b, _) in &ranges { + for (range_index, &(id, a, b, _)) in ranges.iter().enumerate() { let t = text_mut(d, id).ok_or(EngineError::NoNode(id))?; let points = if matches!(step, Step::Size | Step::Leading | Step::BaselineShift) { t.style_scale().ok_or_else(|| bad(C, "text transform is collapsed or unrepresentable"))?.points @@ -1127,7 +1192,10 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> { st.leading = Some(super::typecmd::local_type_value(t, leading * points + inc, (0.1, 5000.0), false, C)?); } Step::Tracking => st.tracking = (st.tracking + inc).clamp(-1000.0, 10000.0), - Step::Kerning => st.kerning = Some((st.kerning.unwrap_or(0.0) + inc).clamp(-1000.0, 10000.0)), + Step::Kerning => { + let current = caret_kerning.get(range_index).copied().flatten().unwrap_or_else(|| st.kerning.unwrap_or(0.0)); + st.kerning = Some((current + inc).clamp(-1000.0, 10000.0)); + } Step::BaselineShift => { st.baseline_shift = super::typecmd::local_type_value(t, st.baseline_shift * points + inc, (-1296.0, 1296.0), false, C)?; } @@ -1142,9 +1210,10 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "ids": ranges.iter().map(|(id, ..)| id.0).collect::<Vec<_>>() })) } -/// Cmd/Ctrl+Alt+Q: tracking 0 and kerning Auto (0 in the Character panel) in the type objects in +/// Cmd/Ctrl+Alt+Q: tracking 0 and manual kerning cleared in the type objects in /// `ids`, else in the Type tool's selected text, else in every selected type object. At a caret, /// only the kerning of the character before it changes, as Alt+←/→ in horizontal type or Alt+↓/↑ in vertical type kerns there. +/// The automatic method remains selected. fn reset_tracking(s: &mut Session, p: &Value) -> Result<Value> { let ranges = type_ranges(s, p, "type.resetTracking", |text, a| Some((edit::prev_char(text, a), a)))?; if !ranges.is_empty() { diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 2a8d48fab5..c1312fa9ba 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -152,6 +152,7 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> { ("fontAxes", json!(v.font_axes)), ("leading", json!(v.leading)), ("kerning", json!(v.kerning)), + ("opticalKerning", json!(v.optical_kerning)), ("features", json!(v.features)), ("overprint_fill", json!(v.overprint_fill)), ("overprint_stroke", json!(v.overprint_stroke)), diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index 2cdcaf77af..670e3bbb7a 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -460,6 +460,20 @@ fn auto_leading_new_distinguishes_unset_attributes() { assert_eq!(s.doc().unwrap().doc.char_styles[2].attrs.get("leading"), Some(&Value::Null)); } +#[test] +fn optical_character_style_captures_and_redefines_automatic_mode() { + let (mut s, id) = session_with_text("III"); + s.execute("text.setRangeStyle", &json!({"id": id, "kerning": "optical"})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Profile", "id": id})).unwrap(); + assert_eq!(s.doc().unwrap().doc.char_styles[0].attrs.get("opticalKerning"), Some(&json!(true))); + s.execute("text.setRangeStyle", &json!({"id": id, "kerning": "auto"})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Profile", "id": id})).unwrap(); + assert!(runs(&s, id)[0].style.optical_kerning); + s.execute("text.setRangeStyle", &json!({"id": id, "kerning": "auto"})).unwrap(); + s.execute("charStyle.redefine", &json!({"name": "Profile", "id": id})).unwrap(); + assert_eq!(s.doc().unwrap().doc.char_styles[0].attrs.get("opticalKerning"), Some(&json!(false))); +} + #[test] fn paragraph_styles_and_survive_save() { let (mut s, id) = session_with_text("Body"); diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index be98613162..025cf6d30a 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -2,7 +2,7 @@ //! on-path type from paths, Fit Headline, Convert To Area/Point Type. use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, NodeKind, TextKind, TextObject}; +use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextKind, TextObject}; use vectorcraft_geom::Point; use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; @@ -87,6 +87,168 @@ fn set_range_style_splits_runs() { assert!(s.execute("text.setRangeStyle", &json!({"id": id.0, "size": -1})).is_err()); } +#[test] +fn optical_command_manual_pair_undo_redo_and_native_reopen() { + let mut s = session(); + let id = text(&mut s, "III"); + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": 70})).unwrap(); + let result = s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": "optical"})).unwrap(); + assert_eq!(result["kerning"], "optical"); + assert!(obj(&s, id).runs[0].style.optical_kerning); + assert_eq!(obj(&s, id).runs[0].style.kerning, Some(70.0)); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 1, "end": 2, "kerning": 0})).unwrap(); + let styled = obj(&s, id); + assert_eq!(styled.runs.iter().map(|r| r.style.kerning).collect::<Vec<_>>(), vec![Some(70.0), Some(0.0), Some(70.0)]); + assert!(styled.runs.iter().all(|r| r.style.optical_kerning)); + let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc); + let opened = vectorcraft_format::load(&bytes).unwrap(); + let NodeKind::Text(reopened) = &opened.node(id).unwrap().kind else { panic!("text missing") }; + assert_eq!( + reopened.runs.iter().map(|r| (r.style.optical_kerning, r.style.kerning)).collect::<Vec<_>>(), + styled.runs.iter().map(|r| (r.style.optical_kerning, r.style.kerning)).collect::<Vec<_>>() + ); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(obj(&s, id).runs[0].style.kerning, Some(70.0)); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(obj(&s, id).runs[1].style.kerning, Some(0.0)); + assert!(obj(&s, id).runs.iter().all(|r| r.style.optical_kerning)); +} + +#[test] +fn optical_set_format_keeps_existing_pair_override() { + let mut s = session(); + let id = text(&mut s, "III"); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 1, "kerning": 40})).unwrap(); + let result = s.execute("text.setFormat", &json!({"ids": [id.0], "kerning": "optical"})).unwrap(); + assert_eq!(result["kerning"], "optical"); + let t = obj(&s, id); + assert!(t.runs.iter().all(|r| r.style.optical_kerning)); + assert_eq!(t.runs[0].style.kerning, Some(40.0)); +} + +#[test] +fn optical_kerning_step_starts_from_the_automatic_pair() { + let mut s = session(); + let id = NodeId( + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "AVA", "size": 100, "font": "JetBrains Mono"})).unwrap()["id"].as_u64().unwrap(), + ); + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": "optical"})).unwrap(); + let t = obj(&s, id); + let optical = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let mut manual = t.clone(); + vectorcraft_text::edit::style_range(&mut manual.runs, 0, 1, |st| st.kerning = Some(0.0)); + let unkerned = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &manual); + let auto = (optical.glyphs[0].advance - unkerned.glyphs[0].advance) * 1000.0 / 100.0; + assert!(auto.abs() > 1.0, "the font needs a measurable shape correction"); + s.execute("type.step", &json!({"id": id.0, "start": 1, "end": 1, "attribute": "kerning", "by": 1})).unwrap(); + let after = obj(&s, id); + assert!((after.runs[0].style.kerning.unwrap() - auto - s.prefs.tracking_increment).abs() < 0.01); + assert!(after.runs.iter().all(|r| r.style.optical_kerning)); +} + +#[test] +fn metrics_pair_step_preserves_the_drawn_auto_position() { + use vectorcraft_text::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font}; + + let db = vectorcraft_text::FontDb::global(); + db.add_font(pair_kerning_font().unwrap()); + let mut s = session(); + let id = NodeId( + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "AV", "size": 100, "font": PAIR_KERNING_FAMILY})).unwrap()["id"].as_u64().unwrap(), + ); + let before = obj(&s, id); + let auto = vectorcraft_text::layout(db, &before); + let drawn_v = |layout: &vectorcraft_text::TextLayout| layout.glyphs.iter().find(|g| g.byte == 1).unwrap().xf.as_coeffs()[4]; + assert!((crate::cmd::effective_kerning(db, &before, &auto, 0, 1) + 160.0).abs() < 0.01); + let mut same = before.clone(); + vectorcraft_text::edit::style_range(&mut same.runs, 0, 1, |st| st.kerning = Some(-160.0)); + assert!((drawn_v(&vectorcraft_text::layout(db, &same)) - drawn_v(&auto)).abs() < 0.01); + + s.execute("type.step", &json!({"id": id.0, "start": 1, "end": 1, "attribute": "kerning", "by": 1})).unwrap(); + let after = obj(&s, id); + assert!((after.runs[0].style.kerning.unwrap() + 160.0 - s.prefs.tracking_increment).abs() < 0.01); + let moved = drawn_v(&vectorcraft_text::layout(db, &after)) - drawn_v(&auto); + assert!((moved - s.prefs.tracking_increment * 0.1).abs() < 0.01, "V moves by one kerning increment: {moved}"); +} + +#[test] +fn effective_auto_kerning_at_area_line_end_survives_unkerned_wrap() { + use vectorcraft_text::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font}; + + let db = vectorcraft_text::FontDb::global(); + db.add_font(pair_kerning_font().unwrap()); + let style = CharStyle { font_family: PAIR_KERNING_FAMILY.into(), size: 100.0, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "AV", style); + let mut wrapping_pair = None; + for width in 80..160 { + text.kind = TextKind::Area { frame: vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(width), 300.0)) }; + let auto = vectorcraft_text::layout(db, &text); + let mut trial = text.clone(); + vectorcraft_text::edit::style_range(&mut trial.runs, 0, 1, |st| st.kerning = Some(0.0)); + let unkerned = vectorcraft_text::layout(db, &trial); + if auto.glyphs.len() >= 2 + && unkerned.glyphs.len() >= 2 + && auto.glyphs[0].line == auto.glyphs[1].line + && unkerned.glyphs[0].line != unkerned.glyphs[1].line + { + wrapping_pair = Some((text.clone(), auto, unkerned)); + break; + } + } + let (text, auto, unkerned) = wrapping_pair.expect("the kerned pair fits on a line that wraps the unkerned pair"); + assert_ne!(unkerned.glyphs[0].line, unkerned.glyphs[1].line); + assert!((crate::cmd::effective_kerning(db, &text, &auto, 0, 1) + 160.0).abs() < 0.01); +} + +#[test] +fn effective_optical_kerning_reads_the_right_to_left_pair() { + use vectorcraft_text::test_fonts::{RIGHT_TO_LEFT_OPTICAL_FAMILY, right_to_left_optical_font}; + + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(right_to_left_optical_font().unwrap()), 1); + let style = CharStyle { font_family: RIGHT_TO_LEFT_OPTICAL_FAMILY.into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let text = TextObject::point(Point::ZERO, "אב", style); + let optical = vectorcraft_text::layout(&db, &text); + let mut manual = text.clone(); + manual.runs[0].style.kerning = Some(0.0); + let unkerned = vectorcraft_text::layout(&db, &manual); + let drawn_gap = |lay: &vectorcraft_text::TextLayout| { + let drawn = |byte| lay.glyphs.iter().find(|g| g.byte == byte).unwrap().xf.as_coeffs()[4]; + drawn(2) - drawn(0) + }; + let expected = (drawn_gap(&optical) - drawn_gap(&unkerned)) * 10.0; + assert!(expected.abs() > 1.0, "the outlined pair has a measurable Optical correction"); + let actual = crate::cmd::effective_kerning(&db, &text, &optical, 0, 2); + assert!((actual - expected).abs() < 0.01, "the caret reads the adjacent right-to-left pair"); +} + +#[test] +fn reset_tracking_clears_manual_pairs_without_changing_optical_mode() { + let mut s = session(); + let id = text(&mut s, "III"); + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": "optical"})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 1, "kerning": 80})).unwrap(); + s.select_tool("type", ViewInfo::default()).unwrap(); + let t = obj(&s, id); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let (a, b) = vectorcraft_text::caret_position(&lay, 1); + let p = t.xf * a.midpoint(b); + click(&mut s, p.x, p.y); + assert!(s.tool_wants_text()); + s.set_tool_option("select", &json!({"start": 1, "end": 1})); + s.execute("type.resetTracking", &json!({})).unwrap(); + let caret = obj(&s, id); + assert_eq!(caret.runs[0].style.kerning, None); + assert!(caret.runs.iter().all(|r| r.style.optical_kerning)); + + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": 60, "tracking": 30})).unwrap(); + s.set_tool_option("select", &json!({"start": 0, "end": 3})); + s.execute("type.resetTracking", &json!({})).unwrap(); + let range = obj(&s, id); + assert!(range.runs.iter().all(|r| r.style.kerning.is_none() && r.style.tracking == 0.0)); + assert!(range.runs.iter().all(|r| r.style.optical_kerning)); +} + /// A character style applied from byte 2^32 to 2^32 + 5 styles no character, as a range past the /// end does. A 32-bit build read the range as bytes 0 to 5 and styled "Hello". #[test] diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 2c79099b4b..5c69a6a935 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -1,5 +1,6 @@ //! Shaping: text runs -> positioned glyphs in points (before line breaking). +use std::collections::HashMap; use std::ops::Range; use std::sync::Arc; @@ -8,6 +9,7 @@ use unicode_script::{Script, UnicodeScript}; use unicode_segmentation::UnicodeSegmentation; use harfrust::{Direction, Feature, ShapeOptions, Tag, UnicodeBuffer}; +use kurbo::Shape; use skrifa::MetadataProvider; use skrifa::charmap::Charmap; use skrifa::instance::Size; @@ -446,6 +448,216 @@ pub(crate) fn shape_range( { o.sort_by_key(|g| g.byte); } + if !feats.vertical { + optical_pairs(db, text, out.get_mut(output_start..).unwrap_or_default(), runs); + } +} + +/// Line segments of a glyph outline in font units, cached for the current shaping pass. +type Profile = Vec<(f64, f64, f64, f64)>; +type CachedProfile = (Profile, (f64, f64)); + +fn outline_profile(db: &FontDb, g: &SGlyph, cache: &mut HashMap<(u32, u32), Option<Arc<CachedProfile>>>) -> Option<Arc<CachedProfile>> { + let key = (g.face.id(), g.gid); + cache + .entry(key) + .or_insert_with(|| { + let path = db.outline(&g.face, g.gid); + let bounds = path.bounding_box(); + if path.elements().is_empty() + || path.elements().len() > 512 + || ![bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite() && v.abs() <= 100_000.0) + { + return None; + } + let mut lines = Vec::new(); + let mut previous = None; + let mut contour_start = None; + kurbo::flatten(path.iter(), 2.0, |el| match el { + kurbo::PathEl::MoveTo(p) => { + previous = Some(p); + contour_start = Some(p); + } + kurbo::PathEl::LineTo(p) => { + if let Some(a) = previous + && lines.len() < 8192 + { + lines.push((a.x, a.y, p.x, p.y)); + } + previous = Some(p); + } + kurbo::PathEl::ClosePath => { + if let Some((a, b)) = previous.zip(contour_start) + && lines.len() < 8192 + { + lines.push((a.x, a.y, b.x, b.y)); + } + previous = None; + contour_start = None; + } + _ => {} + }); + (!lines.is_empty() && lines.len() < 8192).then(|| Arc::new((lines, (bounds.y0, bounds.y1)))) + }) + .clone() +} + +/// The left and right ink edges where a horizontal slice crosses an outline. +fn profile_edges(lines: &[(f64, f64, f64, f64)], y: f64, sx: f64, sy: f64, dx: f64, dy: f64) -> Option<(f64, f64)> { + let mut left = f64::INFINITY; + let mut right = f64::NEG_INFINITY; + for &(x0, y0, x1, y1) in lines { + let (a, b) = (y0 * sy + dy, y1 * sy + dy); + if (a <= y && y < b) || (b <= y && y < a) { + let x = (x0 + (x1 - x0) * (y - a) / (b - a)) * sx + dx; + left = left.min(x); + right = right.max(x); + } + } + (left.is_finite() && right.is_finite()).then_some((left, right)) +} + +#[allow(clippy::too_many_arguments)] +fn profile_correction( + a: &[(f64, f64, f64, f64)], + b: &[(f64, f64, f64, f64)], + left: (f64, f64, f64, f64), + right: (f64, f64, f64, f64), + advance: f64, + em: f64, + upem: f64, + low: f64, + high: f64, +) -> Option<f64> { + if !low.is_finite() || !high.is_finite() || high <= low || !em.is_finite() || em <= 0.0 || !upem.is_finite() || upem <= 0.0 { + return None; + } + let mut gaps = Vec::new(); + for j in 0..24 { + let y = low + (high - low) * (f64::from(j) + 0.5) / 24.0; + if let (Some((_, ar)), Some((bl, _))) = + (profile_edges(a, y, left.0, left.1, left.2, left.3), profile_edges(b, y, right.0, right.1, right.2, right.3)) + { + gaps.push(advance + bl - ar); + } + } + if gaps.is_empty() { + return None; + } + gaps.sort_by(f64::total_cmp); + let gap = gaps.get(gaps.len() / 2).copied().unwrap_or(0.0); + let unit = em / upem; + let correction = ((0.08 * em - gap).clamp(-0.25 * em, 0.25 * em) / unit).round() * unit; + let correction = correction.clamp(-0.25 * em, 0.25 * em); + correction.is_finite().then_some(correction) +} + +/// Move each Optical pair toward an ink gap of 0.08 em, at 24 overlapping vertical slices. +/// The median avoids a single narrow tip deciding the entire pair. Corrections are rounded to +/// one font unit and limited to 1/4 em in either direction. Missing ink gives zero correction. +fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range<usize>, &CharStyle)]) { + let mut cache = HashMap::new(); + let mut corrections: HashMap<[u64; 15], Option<f64>> = HashMap::new(); + let shaped_advances: Vec<f64> = glyphs.iter().map(|g| g.adv).collect(); + for i in 0..glyphs.len().saturating_sub(1) { + let Some((a, b)) = glyphs.get(i).zip(glyphs.get(i + 1)) else { continue }; + if a.level != b.level { + continue; + } + let Some(owner) = runs.get(a.run).map(|(_, s)| *s) else { continue }; + let invisible = |ch: char| matches!(ch, SOFT_HYPHEN | '\u{2028}') || ch.is_control(); + if !owner.optical_kerning + || a.byte == b.byte + || invisible(a.ch) + || invisible(b.ch) + || text.get(a.byte..b.byte).is_some_and(|between| between.chars().skip(1).any(invisible)) + || a.rotation != 0.0 + || b.rotation != 0.0 + { + continue; + } + if owner.kerning.is_some() { + continue; + } + let mut start = i; + while start > 0 && glyphs[start - 1].byte == a.byte { + start -= 1; + } + let mut end = i + 1; + while end + 1 < glyphs.len() && glyphs[end + 1].byte == b.byte { + end += 1; + } + // A mark may precede its base inside either direction's shaped cluster. + let first_base = glyphs[start..=i] + .iter() + .enumerate() + .max_by(|(a, _), (b, _)| shaped_advances[start + *a].total_cmp(&shaped_advances[start + *b])) + .map_or(start, |(offset, _)| start + offset); + let second_base = glyphs[i + 1..=end] + .iter() + .enumerate() + .max_by(|(a, _), (b, _)| shaped_advances[i + 1 + *a].total_cmp(&shaped_advances[i + 1 + *b])) + .map_or(i + 1, |(offset, _)| i + 1 + offset); + let (left_index, right_index, target, cluster_start, cluster_end) = + if a.level.is_rtl() { (second_base, first_base, end, i + 1, end) } else { (first_base, second_base, i, start, i) }; + let (left, right) = (&glyphs[left_index], &glyphs[right_index]); + if left.byte == right.byte + || left.is_space() + || right.is_space() + || is_mark(right.ch) + || left.inline.is_some() + || right.inline.is_some() + || left.ch == '\n' + || right.ch == '\n' + { + continue; + } + let left_y = left.dy - left.bshift; + let right_y = right.dy - right.bshift; + let Some(left_style) = runs.get(left.run).map(|(_, s)| *s) else { continue }; + let em = left.sx * left.face.upem / (left_style.h_scale / 100.0); + let tracking = left_style.tracking / 1000.0 * em; + let manual = left_style.kerning.unwrap_or(0.0) / 1000.0 * em; + let advance = glyphs[cluster_start..=cluster_end].iter().map(|g| g.adv).sum::<f64>() - tracking - manual; + let key = [ + u64::from(left.face.id()), + u64::from(left.gid), + u64::from(right.face.id()), + u64::from(right.gid), + left.sx.to_bits(), + left.sy.to_bits(), + left.dx.to_bits(), + left_y.to_bits(), + right.sx.to_bits(), + right.sy.to_bits(), + right.dx.to_bits(), + right_y.to_bits(), + advance.to_bits(), + em.to_bits(), + left.face.upem.to_bits(), + ]; + let correction = *corrections.entry(key).or_insert_with(|| { + let (Some(a), Some(b)) = (outline_profile(db, left, &mut cache), outline_profile(db, right, &mut cache)) else { return None }; + let low = (a.1.0 * left.sy + left_y).max(b.1.0 * right.sy + right_y); + let high = (a.1.1 * left.sy + left_y).min(b.1.1 * right.sy + right_y); + profile_correction( + &a.0, + &b.0, + (left.sx, left.sy, left.dx, left_y), + (right.sx, right.sy, right.dx, right_y), + advance, + em, + left.face.upem, + low, + high, + ) + }); + if let (Some(correction), Some(glyph)) = (correction, glyphs.get_mut(target)) + && !invisible(glyph.ch) + { + glyph.adv += correction; + } + } } /// Index in the original run list containing `byte`, limited to one coalesced shaping span. @@ -474,6 +686,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { leading: _, tracking, kerning: _, + optical_kerning: _, baseline_shift: _, h_scale, v_scale, @@ -696,6 +909,15 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe }; let manual = |byte: usize| run_at(byte).1.kerning.is_some(); let mixed_kerning = boundaries().any(|b| manual(b) != manual(range.start)); + let optical = |byte: usize| run_at(byte).1.optical_kerning; + let mode_boundaries: Vec<usize> = boundaries().filter(|&b| !feats.vertical && optical(b - 1) && !optical(b)).collect(); + if !mode_boundaries.is_empty() { + return shape_apart(mode_boundaries, out); + } + let manual_ends: Vec<usize> = boundaries().filter(|&b| manual(b - 1) && !manual(b)).collect(); + if !manual_ends.is_empty() { + return shape_apart(manual_ends, out); + } // Shape the segment as if all of it were in `st`, with the features `more` on top. let shape_in = |st: &CharStyle, more: &[Feature]| { @@ -793,17 +1015,43 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe } shaped }; - let Shaped { raw, proportional, vpal } = if mixed_kerning { + let first_optical = if optical(range.start) { Some(range.start) } else { boundaries().find(|&b| optical(b)) }; + let Shaped { raw, proportional, vpal } = if let Some(first) = first_optical.filter(|_| !feats.vertical) { + // The pair entering Optical keeps the left character's font kerning. Subsequent + // Optical pairs use outline spacing, so font pair features stop at its second character. + let optical_off = if first == range.start { + first + } else { + text.get(first..range.end).and_then(|s| s.chars().next()).map_or(range.end, |c| first + c.len_utf8()) + }; + let first_manual = if manual(range.start) { Some(range.start) } else { boundaries().find(|&b| manual(b)) }; + if let Some(start) = first_manual.filter(|&b| b > range.start) + && upper + && first_char(start).to_uppercase().nth(1).is_some() + { + return shape_apart(vec![start], out); + } + let manual_off = first_manual.map_or(range.end, |start| { + if start == range.start { + start + } else { + text.get(start..range.end).and_then(|s| s.chars().next()).map_or(range.end, |c| start + c.len_utf8()) + } + }); + let off = optical_off.min(manual_off); + let more: Vec<Feature> = [b"kern", b"apkn", b"vkrn", b"vapk"] + .into_iter() + .filter(|_| off < range.end) + .map(|t| Feature::new(Tag::new(t), 0, off..range.end)) + .collect(); + shape_in(&CharStyle { kerning: None, ..run_at(range.start).1.clone() }, &more) + } else if mixed_kerning { // A font's kerning pair applies after a character with automatic kerning and not after one // with manual kerning. The segment is shaped apart where manual kerning ends, so each piece // is text with automatic kerning followed by text with manual kerning. A piece is shaped // with the font's kerning on, and off (`kern`, and the `apkn`, `vkrn` and `vapk` that // `OtFeatures` turns off with it) from the second character with manual kerning on: a // pair is applied only when both of its glyphs have the feature on. - let ends: Vec<usize> = boundaries().filter(|&b| manual(b - 1) && !manual(b)).collect(); - if !ends.is_empty() { - return shape_apart(ends, out); - } let first = boundaries().find(|&b| manual(b)).unwrap_or(range.end); // A first character with manual kerning that All Caps or Small Caps sets as several letters // (ß as SS) gives them one cluster, which a feature range cannot split, so the font's @@ -879,3 +1127,27 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe }); } } + +#[cfg(test)] +mod optical_tests { + use super::*; + + fn box_profile(left: f64, right: f64) -> Profile { + vec![(left, 0.0, left, 100.0), (right, 0.0, right, 100.0)] + } + + #[test] + fn optical_side_profiles_tighten_loosen_and_stay_bounded() { + let a = box_profile(0.0, 80.0); + let b = box_profile(0.0, 20.0); + let place = (1.0, 1.0, 0.0, 0.0); + let tight = profile_correction(&a, &b, place, place, 120.0, 100.0, 1000.0, 0.0, 100.0).unwrap(); + let loose = profile_correction(&a, &b, place, place, 60.0, 100.0, 1000.0, 0.0, 100.0).unwrap(); + assert_eq!(tight, -25.0); + assert_eq!(loose, 25.0); + assert_eq!(profile_correction(&a, &b, place, place, 88.0, 100.0, 1000.0, 0.0, 100.0), Some(0.0)); + assert_eq!(profile_correction(&a, &b, place, place, 120.0, 100.0, 1000.0, 0.0, 100.0), Some(tight)); + assert_eq!(profile_correction(&a, &b, place, place, 120.0, 100.0, 1000.0, 100.0, 100.0), None); + assert_eq!(profile_correction(&[], &b, place, place, 120.0, 100.0, 1000.0, 0.0, 100.0), None); + } +} diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index f3619679ff..817f1689f4 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -412,6 +412,81 @@ pub fn lam_alef_font(feature: &[u8; 4]) -> Option<Vec<u8>> { /// The family of [`pair_kerning_font`]. pub const PAIR_KERNING_FAMILY: &str = "Pairtest Sans"; +/// The family of [`no_pair_kerning_font`]. +pub const NO_PAIR_KERNING_FAMILY: &str = "No Pairtest Sans"; + +/// A font with the bundled Source Sans 3 outlines and no `GPOS` or `kern` table. +pub fn no_pair_kerning_font() -> Option<Vec<u8>> { + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let family = NO_PAIR_KERNING_FAMILY; + let name = name_table(&[(1, family), (2, "Regular"), (4, "No Pairtest Sans Regular"), (6, "NoPairtestSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if !matches!(tag, t if t == Tag::new(b"name") || t == Tag::new(b"GPOS") || t == Tag::new(b"kern")) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + +/// The family of [`right_to_left_optical_font`]. +pub const RIGHT_TO_LEFT_OPTICAL_FAMILY: &str = "Right-to-left Profile Sans"; + +/// Two Hebrew characters mapped to the bundled Source Sans 3 A and V outlines. +pub fn right_to_left_optical_font() -> Option<Vec<u8>> { + use write_fonts::tables::cmap::Cmap; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let mapping = [('א', 'A'), ('ב', 'V')]; + let mappings = mapping.into_iter().map(|(c, source)| Some((c, write_fonts::types::GlyphId::new(charmap.map(source)?.to_u32())))); + let cmap = Cmap::from_mappings(mappings.collect::<Option<Vec<_>>>()?).ok()?; + let family = RIGHT_TO_LEFT_OPTICAL_FAMILY; + let name = name_table(&[(1, family), (2, "Regular"), (4, "Right-to-left Profile Sans Regular"), (6, "RtlProfileSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_table(&cmap).ok()?; + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if tag != Tag::new(b"GPOS") && tag != Tag::new(b"kern") && !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + +/// The family of [`soft_hyphen_outline_font`]. +pub const SOFT_HYPHEN_OUTLINE_FAMILY: &str = "Soft Hyphen Profile Sans"; + +/// A face that maps the invisible soft hyphen to the bundled hyphen outline. +pub fn soft_hyphen_outline_font() -> Option<Vec<u8>> { + use write_fonts::tables::cmap::Cmap; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let mappings = [('A', 'A'), ('V', 'V'), ('-', '-'), ('\u{00AD}', '-')] + .into_iter() + .map(|(c, source)| Some((c, write_fonts::types::GlyphId::new(charmap.map(source)?.to_u32())))); + let cmap = Cmap::from_mappings(mappings.collect::<Option<Vec<_>>>()?).ok()?; + let family = SOFT_HYPHEN_OUTLINE_FAMILY; + let name = name_table(&[(1, family), (2, "Regular"), (4, "Soft Hyphen Profile Sans Regular"), (6, "SoftHyphenProfileSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_table(&cmap).ok()?; + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if tag != Tag::new(b"GPOS") && tag != Tag::new(b"kern") && !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The bundled Source Sans 3 Regular as family [`PAIR_KERNING_FAMILY`], its `GPOS` replaced by two /// `kern` pairs, A followed by V and S followed by S: each takes 60 units off the first glyph's /// advance (the pair's first value record) and moves the second 100 units left (its second). diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 345340b52e..105c1b424e 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -18,6 +18,267 @@ fn run(text: &str, size: f64) -> TextRun { TextRun { text: text.into(), style: style(size), inline: None } } +#[test] +fn optical_pairs_cross_paint_runs_and_manual_and_tracking_are_independent() { + let st = CharStyle { font_family: "JetBrains Mono".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let mut t = TextObject::point(Point::ZERO, "III", st); + let advance = |t: &TextObject| layout(db(), t).glyphs.iter().map(|g| g.advance).collect::<Vec<_>>(); + let optical = advance(&t); + let mut plain = t.clone(); + plain.runs[0].style.kerning = Some(0.0); + let unkerned = advance(&plain); + assert!((optical[0] - unkerned[0]).abs() > 0.1, "Optical changes the monospaced pair"); + edit::style_range(&mut t.runs, 1, 2, |s| s.fill = vectorcraft_doc::color::Paint::solid(vectorcraft_doc::color::Color::rgb(1.0, 0.0, 0.0))); + let painted = advance(&t); + assert!((painted[0] - optical[0]).abs() < 0.01, "paint does not interrupt Optical"); + edit::style_range(&mut t.runs, 0, 1, |s| s.kerning = Some(0.0)); + let manual = advance(&t); + assert!((manual[0] - unkerned[0]).abs() < 0.01); + assert!((manual[1] - optical[1]).abs() < 0.01, "the next pair remains Optical"); + edit::style_range(&mut t.runs, 0, 3, |s| s.tracking = 100.0); + let tracked = advance(&t); + assert!((tracked[0] - manual[0] - 10.0).abs() < 0.01); + assert!((tracked[1] - manual[1] - 10.0).abs() < 0.01); + + for text in ["I I", "I\u{301}"] { + let sample = TextObject::point(Point::ZERO, text, CharStyle { kerning: None, ..t.runs[0].style.clone() }); + let mut zero = sample.clone(); + zero.runs[0].style.kerning = Some(0.0); + assert_eq!(advance(&sample), advance(&zero), "spaces and marks inside a cluster have no Optical correction"); + } + let mut vertical = TextObject::point(Point::ZERO, "II", CharStyle { kerning: None, ..t.runs[0].style.clone() }); + vertical.vertical = true; + let mut vertical_zero = vertical.clone(); + vertical_zero.runs[0].style.kerning = Some(0.0); + assert_eq!(advance(&vertical), advance(&vertical_zero), "vertical type keeps a neutral correction"); + let rtl = TextObject::point(Point::ZERO, "אב", CharStyle { kerning: None, ..t.runs[0].style.clone() }); + let rtl_advances = advance(&rtl); + assert!(rtl_advances.len() >= 2 && rtl_advances.iter().all(|v| v.is_finite())); + let mut rtl_zero = rtl.clone(); + rtl_zero.runs[0].style.kerning = Some(0.0); + assert!((rtl_advances[1] - advance(&rtl_zero)[1]).abs() <= 25.0, "right-to-left Optical corrections remain bounded"); + let mut rtl_manual = rtl.clone(); + edit::style_range(&mut rtl_manual.runs, 0, 2, |s| s.kerning = Some(200.0)); + let mut rtl_pair_zero = rtl.clone(); + edit::style_range(&mut rtl_pair_zero.runs, 0, 2, |s| s.kerning = Some(0.0)); + let pair_advance = |t: &TextObject| layout(db(), t).glyphs.iter().find(|g| g.byte == 0).map(|g| g.advance).unwrap(); + assert!((pair_advance(&rtl_pair_zero) - pair_advance(&rtl_zero)).abs() < 0.01, "manual zero replaces the right-to-left Optical correction"); + assert!((pair_advance(&rtl_manual) - pair_advance(&rtl_pair_zero) - 20.0).abs() < 0.01, "manual spacing changes the adjacent right-to-left pair"); +} + +#[test] +fn optical_pair_skips_an_invisible_soft_hyphen_with_an_outline() { + use crate::test_fonts::{SOFT_HYPHEN_OUTLINE_FAMILY, soft_hyphen_outline_font}; + + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(soft_hyphen_outline_font().unwrap()), 1); + let style = CharStyle { font_family: SOFT_HYPHEN_OUTLINE_FAMILY.into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let face = db.style_face(&style).unwrap(); + assert_ne!(face.glyph_for('\u{00AD}'), 0); + assert_eq!(face.glyph_for('\u{00AD}'), face.glyph_for('-')); + let paired = layout(&db, &TextObject::point(Point::ZERO, "AV", style.clone())); + let separated = layout(&db, &TextObject::point(Point::ZERO, "A\u{00AD}V", style.clone())); + let mut manual = style; + manual.kerning = Some(0.0); + let plain = layout(&db, &TextObject::point(Point::ZERO, "A\u{00AD}V", manual)); + + assert!((paired.glyphs[0].advance - plain.glyphs[0].advance).abs() > 0.1, "A-V has an Optical correction"); + // A keeps its uncorrected advance because neither pair across the invisible glyph is measured. + assert!((separated.glyphs[0].advance - plain.glyphs[0].advance).abs() < 0.01); + assert!(separated.glyphs.iter().filter(|g| g.byte == 1).all(|g| g.advance == 0.0), "the soft hyphen remains zero width if emitted"); + let v = |lay: &TextLayout| lay.glyphs.iter().find(|g| g.byte == 3).unwrap().origin.x; + assert!((v(&separated) - v(&plain)).abs() < 0.01, "the soft hyphen adds no spacing"); +} + +#[test] +fn optical_pair_after_separate_combining_mark_uses_base_outline() { + let st = CharStyle { font_family: "Source Sans 3".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let advances = |text: &str, manual: bool| { + let mut style = st.clone(); + if manual { + style.kerning = Some(0.0); + } + layout(db(), &TextObject::point(Point::ZERO, text, style)).glyphs.iter().map(|g| (g.byte, g.advance)).collect::<Vec<_>>() + }; + let plain = advances("II", false); + let plain_zero = advances("II", true); + let accented = advances("I\u{30d}I", false); + let accented_zero = advances("I\u{30d}I", true); + assert_eq!(accented.len(), 3, "the accent has its own glyph"); + assert_eq!(accented[0].0, accented[1].0, "the base and mark share a cluster"); + assert!((accented[0].1 - accented_zero[0].1).abs() < 0.01, "the base keeps its advance"); + let correction = accented[1].1 - accented_zero[1].1; + assert!((correction - (plain[0].1 - plain_zero[0].1)).abs() < 0.01, "the marked cluster uses the base outline"); + assert!(correction.abs() > 0.1, "Optical adjusts the pair after the accent"); +} + +#[test] +fn optical_pair_after_rtl_separate_mark_uses_base_outline() { + let st = CharStyle { font_family: "Noto Sans Arabic".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let shaped = |text: &str, manual: bool| { + let mut style = st.clone(); + if manual { + style.kerning = Some(0.0); + } + layout(db(), &TextObject::point(Point::ZERO, text, style)).glyphs.iter().map(|g| (g.byte, g.advance)).collect::<Vec<_>>() + }; + let plain = shaped("بب", false); + let plain_zero = shaped("بب", true); + let marked = shaped("بَب", false); + let marked_zero = shaped("بَب", true); + let marked_cluster = marked.iter().filter(|g| g.0 == 0).collect::<Vec<_>>(); + assert_eq!(marked_cluster.len(), plain.iter().filter(|g| g.0 == 0).count() + 1, "the mark has its own glyph in the base cluster"); + assert_eq!(marked_cluster.first().unwrap().1, 0.0, "the cluster starts with a nonspacing glyph"); + assert!(marked_cluster.last().unwrap().1 > 0.0, "the base follows the mark"); + let correction = marked.iter().filter(|g| g.0 == 4).map(|g| g.1).sum::<f64>() - marked_zero.iter().filter(|g| g.0 == 4).map(|g| g.1).sum::<f64>(); + let plain_correction = + plain.iter().filter(|g| g.0 == 2).map(|g| g.1).sum::<f64>() - plain_zero.iter().filter(|g| g.0 == 2).map(|g| g.1).sum::<f64>(); + assert!(plain_correction.abs() > 0.1, "Optical adjusts the unmarked pair"); + assert!((correction - plain_correction).abs() < 0.01, "the marked cluster uses the base outline"); +} + +#[test] +fn recurring_optical_pairs_have_equal_corrections() { + let st = CharStyle { font_family: "JetBrains Mono".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let text = "II".repeat(50); + let optical = layout(db(), &TextObject::point(Point::ZERO, &text, st.clone())).glyphs.iter().map(|g| g.advance).collect::<Vec<_>>(); + let zero = layout(db(), &TextObject::point(Point::ZERO, &text, CharStyle { kerning: Some(0.0), ..st })) + .glyphs + .iter() + .map(|g| g.advance) + .collect::<Vec<_>>(); + assert_eq!(optical.len(), zero.len()); + let correction = optical[0] - zero[0]; + assert!(correction.abs() > 0.1); + for i in 1..optical.len() - 1 { + assert_eq!(optical[i] - zero[i], correction, "pair {i} has the same correction"); + } +} + +#[test] +fn metrics_pair_survives_transition_to_optical() { + let st = CharStyle { font_family: "Source Sans 3".into(), size: 100.0, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "AVV", st); + let advances = |text: &TextObject| layout(db(), text).glyphs.iter().map(|g| g.advance).collect::<Vec<_>>(); + let metrics = advances(&text); + let mut unkerned = text.clone(); + unkerned.runs[0].style.kerning = Some(0.0); + assert!((metrics[0] - advances(&unkerned)[0]).abs() > 0.1, "the font supplies an AV pair"); + edit::style_range(&mut text.runs, 1, 3, |s| s.optical_kerning = true); + let mixed = advances(&text); + assert!((mixed[0] - metrics[0]).abs() < 0.01, "the metrics AV pair crosses the mode change"); + let mut optical = TextObject::point(Point::ZERO, "VV", text.runs[1].style.clone()); + let optical_pair = advances(&optical)[0]; + optical.runs[0].style.kerning = Some(0.0); + assert!((mixed[1] - optical_pair).abs() < 0.01, "the first Optical V keeps its next pair"); + assert!((mixed[1] - advances(&optical)[0]).abs() > 0.1, "Optical corrects the next pair"); +} + +#[test] +fn manual_pair_before_optical_does_not_gain_font_kerning() { + let st = CharStyle { font_family: "Source Sans 3".into(), size: 100.0, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "AVA", st); + edit::style_range(&mut text.runs, 1, 2, |s| s.kerning = Some(0.0)); + edit::style_range(&mut text.runs, 2, 3, |s| s.optical_kerning = true); + let mixed = layout(db(), &text).glyphs[1].advance; + let mut unkerned = TextObject::point(Point::ZERO, "VA", text.runs[1].style.clone()); + unkerned.runs[0].style.kerning = Some(0.0); + let manual = layout(db(), &unkerned).glyphs[0].advance; + assert!((mixed - manual).abs() < 0.01, "manual V keeps its unkerned pair with Optical A"); +} + +#[test] +fn optical_pair_uses_drawn_baseline() { + let st = CharStyle { font_family: "JetBrains Mono".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "II", st); + let first = |text: &TextObject| layout(db(), text).glyphs[0].advance; + let normal = first(&text); + edit::style_range(&mut text.runs, 1, 2, |s| s.baseline_shift = 80.0); + let shifted = first(&text); + assert!((shifted - normal).abs() > 0.1, "a displaced outline changes the Optical correction"); +} + +#[test] +fn optical_pair_skips_rotated_glyphs() { + let st = CharStyle { font_family: "JetBrains Mono".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "II", st); + let first = |text: &TextObject| layout(db(), text).glyphs[0].advance; + let unrotated = first(&text); + let mut plain = text.clone(); + plain.runs[0].style.kerning = Some(0.0); + assert!((unrotated - first(&plain)).abs() > 0.1, "the unrotated pair has an Optical correction"); + edit::style_range(&mut text.runs, 1, 2, |s| s.rotation = 20.0); + let rotated = first(&text); + let mut manual_zero = text.clone(); + edit::style_range(&mut manual_zero.runs, 0, 1, |s| s.kerning = Some(0.0)); + assert!((rotated - first(&manual_zero)).abs() < 0.01, "rotated pairs keep their uncorrected advance"); +} + +#[test] +fn optical_shaping_keeps_manual_value_on_first_run() { + let st = CharStyle { font_family: "Source Sans 3".into(), size: 100.0, optical_kerning: true, kerning: Some(0.0), ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "AVA", st); + let zero = layout(db(), &text).glyphs.iter().map(|g| g.advance).collect::<Vec<_>>(); + edit::style_range(&mut text.runs, 0, 1, |s| s.kerning = Some(120.0)); + let manual = layout(db(), &text).glyphs.iter().map(|g| g.advance).collect::<Vec<_>>(); + assert!((manual[0] - zero[0] - 12.0).abs() < 0.01, "the first run adds its manual value"); + assert!((manual[1] - zero[1]).abs() < 0.01, "the following run keeps its advance"); +} + +#[test] +fn ordinary_and_vertical_segments_keep_their_spacing() { + let st = CharStyle { font_family: "Source Sans 3".into(), size: 100.0, kerning: Some(100.0), ..CharStyle::default() }; + let plain = TextObject::point(Point::ZERO, "AVA", st); + let advances = |text: &TextObject| layout(db(), text).glyphs.iter().map(|g| g.advance).collect::<Vec<_>>(); + let expected = advances(&plain); + let mut split = plain.clone(); + edit::style_range(&mut split.runs, 1, 2, |s| s.fill = vectorcraft_doc::color::Paint::solid(vectorcraft_doc::color::Color::rgb(1.0, 0.0, 0.0))); + assert_eq!(advances(&split), expected, "a non-Optical segment keeps the same spacing across runs"); + + let mut vertical = plain; + vertical.vertical = true; + let expected = advances(&vertical); + edit::style_range(&mut vertical.runs, 0, 1, |s| s.kerning = Some(120.0)); + let manual = advances(&vertical); + assert!((manual[0] - expected[0] - 2.0).abs() < 0.01, "vertical manual spacing changes only its own advance"); + edit::style_range(&mut vertical.runs, 0, 3, |s| s.optical_kerning = true); + assert_eq!(advances(&vertical), manual, "vertical type keeps its spacing with Optical selected"); +} + +#[test] +fn optical_spacing_works_without_font_pair_tables() { + use crate::test_fonts::{NO_PAIR_KERNING_FAMILY, no_pair_kerning_font}; + + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(no_pair_kerning_font().unwrap()), 1); + let st = CharStyle { font_family: NO_PAIR_KERNING_FAMILY.into(), size: 100.0, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "AV", st); + let metrics = layout(&db, &text).glyphs[0].advance; + text.runs[0].style.kerning = Some(0.0); + let manual_zero = layout(&db, &text).glyphs[0].advance; + assert!((metrics - manual_zero).abs() < 0.01, "the font has no automatic pair correction"); + text.runs[0].style.kerning = None; + text.runs[0].style.optical_kerning = true; + let optical = layout(&db, &text).glyphs[0].advance; + assert!((optical - manual_zero).abs() > 0.1, "Optical uses outlines without a pair table"); +} + +#[test] +fn manual_pair_positions_match_under_auto_and_optical_in_both_directions() { + use crate::test_fonts::{RIGHT_TO_LEFT_OPTICAL_FAMILY, right_to_left_optical_font}; + + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(right_to_left_optical_font().unwrap()), 1); + for (letters, family) in [("AV", "Source Sans 3"), ("אב", RIGHT_TO_LEFT_OPTICAL_FAMILY)] { + let mut text = TextObject::point(Point::ZERO, letters, CharStyle { font_family: family.into(), size: 100.0, ..CharStyle::default() }); + edit::style_range(&mut text.runs, 0, letters.chars().next().unwrap().len_utf8(), |s| s.kerning = Some(200.0)); + let positions = |text: &TextObject| layout(&db, text).glyphs.iter().map(|g| (g.byte, g.origin, g.advance)).collect::<Vec<_>>(); + let auto = positions(&text); + edit::style_range(&mut text.runs, 0, letters.len(), |s| s.optical_kerning = true); + assert_eq!(positions(&text), auto, "{letters}: manual pair has the same positions in both modes"); + } +} + fn area_path(text: &str, st: CharStyle, frame: &BezPath, justify: Justify) -> TextObject { let mut t = TextObject::point(Point::ZERO, text, st); t.kind = TextKind::Area { frame: PathData::from_bezpath(frame) }; diff --git a/crates/text/src/tests/vertical.rs b/crates/text/src/tests/vertical.rs index d69b5df292..a2206df5eb 100644 --- a/crates/text/src/tests/vertical.rs +++ b/crates/text/src/tests/vertical.rs @@ -719,5 +719,29 @@ fn proportional_metrics_kern_the_glyphs_they_respace() { }; let (auto, manual) = (lay(true, None), lay(true, Some(0.0))); assert!(auto.iter().zip(&manual).any(|(a, b)| (a - b).abs() > 0.01), "kerned: {auto:?} {manual:?}"); + let optical = { + let s = CharStyle { font_family: "Noto Sans CJK SC".into(), optical_kerning: true, ..st(true, None) }; + layout(&db, &vertical_styled("「カタカナ」とトップ、ヤッホー。", s)).glyphs.iter().map(|g| g.advance).collect::<Vec<_>>() + }; + assert!(auto.iter().zip(&optical).all(|(a, b)| (a - b).abs() < 0.01), "vertical Optical uses font metrics: {auto:?} {optical:?}"); assert!(lay(false, None).iter().all(|a| (a - 20.0).abs() < 0.01), "off: an em each, as before"); } + +#[test] +fn vertical_optical_to_auto_keeps_the_fonts_pair() { + use crate::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(pair_kerning_font().unwrap()); + let style = CharStyle { font_family: PAIR_KERNING_FAMILY.into(), size: 100.0, ..CharStyle::default() }; + let positions = + |t: &TextObject| layout(&db, t).glyphs.iter().map(|g| (g.advance, g.origin, g.xf.as_coeffs()[4], g.xf.as_coeffs()[5])).collect::<Vec<_>>(); + let auto = vertical_styled("AV", style.clone()); + let mut mixed = auto.clone(); + edit::style_range(&mut mixed.runs, 0, 1, |s| s.optical_kerning = true); + let mut unkerned = auto.clone(); + edit::style_range(&mut unkerned.runs, 0, 1, |s| s.kerning = Some(0.0)); + let expected = positions(&auto); + assert_eq!(expected.len(), 2); + assert_ne!(expected, positions(&unkerned), "the font's A-V pair changes vertical positions"); + assert_eq!(positions(&mixed), expected, "vertical Optical keeps the A-V font pair across the style boundary"); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2104ac7af6..fbb0019ec4 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1587,7 +1587,7 @@ font-technology Variable Променливи Keep the pasted color as a new swatch with a numbered name. Запазване на поставения цвят като нов образец с номерирано име. Keep this row's colors (exclude) Запазване на цветовете на този ред (изключване) Keep: Запазване: - Kerning (0 = Auto) Кернинг (0 = Автоматично) + Kerning Кернинг Keyboard Increment Стъпка с клавиатурата Keyboard Shortcut Conflicts Конфликти на клавишни комбинации Keyboard Shortcut Set Набор клавишни комбинации @@ -2159,6 +2159,7 @@ font-technology Variable Променливи Open the URL in the web browser Отваряне на URL адреса в уеб браузъра Opened with {} note(s): {} Отворено с {} бележка(и): {} Open… Отваряне… + Optical Оптично Optical Margin Alignment Подравняване по оптично поле Optimize for fast web view Оптимизиране за бърз уеб преглед Optimized Оптимизирано @@ -3761,6 +3762,7 @@ axis Both И двете Float Tool Group Плаваща група инструменти @msg no library `{id}` няма библиотека `{id}` @msg select some type first първо изберете текст +@msg kerning must be a number, "auto", or "optical" Кернингът трябва да е число, „auto“ или „optical“ @msg {_1} has no {_2} style {_1} няма стил {_2} @msg a layer couldn't be read слой не можа да бъде прочетен @msg it has more than one artboard има повече от една работна област diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 2d42bf75d5..311580ce5e 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1411,7 +1411,8 @@ lighting Light Svjetlo Fractional Widths Djelimične širine Hide Options Sakrij opcije Horizontal Scale % Vodoravna skala % - Kerning (0 = Auto) Podrezivanje (0 = automatski) + Kerning Podrezivanje + Optical Optičko Leading Prored No Break Bez preloma Proportional Metrics Proporcionalna metrika @@ -4114,6 +4115,7 @@ imageTrace Outline Obris @plural {n} stroke|{n} strokes {n} potez|{n} poteza|{n} poteza @msg no library `{id}` nema biblioteke `{id}` @msg select some type first prvo odaberite tekst +@msg kerning must be a number, "auto", or "optical" Podrezivanje mora biti broj, „auto” ili „optical” @msg the selection has no gradient fill odabir nema ispunu gradijentom @msg the selection has no gradient stroke odabir nema potez gradijentom @msg the selection has no pattern fill odabir nema ispunu uzorkom diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index b7a1506662..442e051c03 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2046,8 +2046,8 @@ Keep visible surfaces only when expanding Conserva només les superfícies visibles en expandir Keep: Conserva: Keeps the document editable: VectorCraft reopens the PDF with nothing lost. For files you'll edit again. Manté el document editable: VectorCraft reobre el PDF sense perdre res. Per a fitxers que editaràs de nou. - Kerning (0 = Auto) Kerning (0 = automàtic) Key Color: Color clau: + Kerning Kerning Keyboard Increment Increment de teclat Keyboard Shortcut Conflicts Conflictes de dreceres de teclat Keyboard Shortcut Set Conjunt de dreceres de teclat @@ -2740,6 +2740,7 @@ Opens files in other apps Obre fitxers en altres aplicacions Opens network connections Obre connexions de xarxa Open… Obre… + Optical Òptic Optical Margin Alignment Alineació òptica de marges Optimize for fast web view Optimitza per a la visualització web ràpida Optimized Optimitzat @@ -5354,6 +5355,7 @@ @msg select paths or anchor points selecciona traçats o punts d’ancoratge @msg select paths to join selecciona traçats per unir @msg select some type first selecciona text primer +@msg kerning must be a number, "auto", or "optical" El kerning ha de ser un nombre, «auto» o «optical» @msg Select text or click into text with the Type tool to insert glyphs Selecciona text o fes clic dins del text amb l’eina de text per inserir glifs @msg select the art to export first selecciona primer la il·lustració que vols exportar @msg select the art to repeat selecciona la il·lustració que vols repetir diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 75765ab754..aa88620f4d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1436,7 +1436,6 @@ lighting Light Světlo Fractional Widths Zlomkové šířky Hide Options Skrýt možnosti Horizontal Scale % Vodorovná změna velikosti % - Kerning (0 = Auto) Vyrovnání párů (0 = automaticky) Leading Proklad No Break Nezalamovat Proportional Metrics Proporcionální metrika @@ -3514,6 +3513,7 @@ theme Appearance Motiv Identify Objects By Identifikovat objekty podle Include SVG Code Zahrnout kód SVG Italian Italština + Kerning Vyrovnání párů Keyboard Increment Krok klávesnice Language Options Možnosti jazyka Large Velké @@ -3556,6 +3556,7 @@ theme Appearance Motiv On Paste Při vložení On Screen Na obrazovce Open Documents As Tabs Otevírat dokumenty jako karty + Optical Optické Options Možnosti Output All Blacks Accurately Ve výstupu všechny černé přesně Output All Blacks as Rich Black Ve výstupu všechny černé jako sytou černou @@ -4151,6 +4152,7 @@ imageTrace Outline Obrys # Status and error messages @msg no library `{id}` knihovna `{id}` neexistuje @msg select some type first nejprve vyberte text +@msg kerning must be a number, "auto", or "optical" Vyrovnání párů musí být číslo, „auto“ nebo „optical“ @msg the selection has no gradient fill výběr nemá přechodovou výplň @msg the selection has no gradient stroke výběr nemá přechodový tah @msg the selection has no pattern fill výběr nemá vzorkovou výplň diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 8140d38e19..b7c6e23fda 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1351,7 +1351,6 @@ lighting Light Lys Fractional Widths Fraktionerede bredder Hide Options Skjul indstillinger Horizontal Scale % Vandret skalering % - Kerning (0 = Auto) Kerning (0 = automatisk) Leading Linjeafstand No Break Ingen ombrydning Proportional Metrics Proportionale metrikker @@ -3271,6 +3270,7 @@ theme Appearance Udseende Identify Objects By Identificér objekter ud fra Include SVG Code Medtag SVG-kode Italian Italiensk + Kerning Kerning Keyboard Increment Tastaturtrin Language Options Sprogindstillinger Large Stor @@ -3299,6 +3299,7 @@ theme Appearance Udseende On Paste Ved indsættelse On Screen På skærmen Open Documents As Tabs Åbn dokumenter som faner + Optical Optisk Options Indstillinger Output All Blacks Accurately Udskriv alle sorte nøjagtigt Output All Blacks as Rich Black Udskriv alle sorte som rich black @@ -3881,6 +3882,7 @@ imageTrace Outline Kontur @plural {n} stroke|{n} strokes {n} kontur|{n} konturer @msg no library `{id}` intet bibliotek `{id}` @msg select some type first markér først noget tekst +@msg kerning must be a number, "auto", or "optical" Kerning skal være et tal, „auto“ eller „optical“ @msg {_1} has no {_2} style {_1} har ingen {_2}-stil @msg a layer couldn't be read et lag kunne ikke læses @msg it has more than one artboard den har mere end én tegneflade diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index fa638758f3..2d1e728453 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1625,7 +1625,7 @@ file-filter Templates Vorlagen Keep the pasted color as a new swatch with a numbered name. Die eingefügte Farbe als neues Farbfeld mit nummeriertem Namen behalten. Keep this row's colors (exclude) Farben dieser Zeile beibehalten (ausschließen) Keep: Beibehalten: - Kerning (0 = Auto) Kerning (0 = Auto) + Kerning Kerning Keyboard Increment Schritte per Tastatur Keyboard Shortcut Conflicts Konflikte bei Tastaturbefehlen Keyboard Shortcut Set Tastaturbefehlssatz @@ -2172,6 +2172,7 @@ file-filter Templates Vorlagen Open the URL in the web browser Die URL im Webbrowser öffnen Opened with {} note(s): {} Mit {} Hinweis(en) geöffnet: {} Open… Öffnen… + Optical Optisch Optical Margin Alignment Optischer Randausgleich Optimize for fast web view Für schnelle Webanzeige optimieren Optimized Optimiert @@ -3763,6 +3764,7 @@ theme Appearance Erscheinungsbild # names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are. @msg no library `{id}` keine Bibliothek `{id}` @msg select some type first wählen Sie zuerst Text aus +@msg kerning must be a number, "auto", or "optical" Kerning muss eine Zahl, „auto“ oder „optical“ sein @msg the selection has no gradient fill die Auswahl hat keinen Flächenverlauf @msg the selection has no gradient stroke die Auswahl hat keinen Konturverlauf @msg the selection has no pattern fill die Auswahl hat kein Flächenmuster diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index baf6f52ec9..16fe9435e1 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1543,7 +1543,7 @@ font-technology Variable Μεταβλητές Keep Plain Text Διατήρηση απλού κειμένου Keep this row's colors (exclude) Διατήρηση των χρωμάτων αυτής της γραμμής (εξαίρεση) Keep: Διατήρηση: - Kerning (0 = Auto) Διαγραμμάτωση (0 = Αυτόματο) + Kerning Διαγραμμάτωση Keyboard Increment Βήμα πληκτρολογίου Keyboard Shortcut Conflicts Διενέξεις συντομεύσεων πληκτρολογίου Keyboard Shortcut Set Σύνολο συντομεύσεων πληκτρολογίου @@ -2080,6 +2080,7 @@ axis Both Και τα δύο Dock Panel Αγκύρωση πάνελ @msg no library `{id}` Δεν υπάρχει βιβλιοθήκη με αναγνωριστικό `{id}` @msg select some type first Επιλέξτε πρώτα κάποιο κείμενο +@msg kerning must be a number, "auto", or "optical" Η διαγραμμάτωση πρέπει να είναι αριθμός, «auto» ή «optical» @msg the selection has no gradient fill η επιλογή δεν έχει ντεγκραντέ γεμίσματος @msg the selection has no gradient stroke η επιλογή δεν έχει ντεγκραντέ περιγράμματος @msg the selection has no pattern fill η επιλογή δεν έχει μοτίβο γεμίσματος @@ -2886,6 +2887,7 @@ theme Appearance Εμφάνιση Open Swatch Library Άνοιγμα βιβλιοθήκης δειγμάτων χρωμάτων Open the URL in the web browser Άνοιγμα της διεύθυνσης στο πρόγραμμα περιήγησης Opened with {} note(s): {} Άνοιξε με {} σημειώσεις: {} + Optical Οπτική Optical Margin Alignment Οπτική στοίχιση περιθωρίου Optimize for fast web view Βελτιστοποίηση για γρήγορη προβολή στον ιστό Options for Selection… Επιλογές για την επιλογή… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 7b5b6aae3e..d4d2d20eb3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1625,7 +1625,7 @@ font-technology Variable Variables Keep the pasted color as a new swatch with a numbered name. Conservar el color pegado como una muestra nueva con nombre numerado. Keep this row's colors (exclude) Conservar los colores de esta fila (excluir) Keep: Conservar: - Kerning (0 = Auto) Interletraje (0 = auto) + Kerning Interletraje Keyboard Increment Incremento de teclado Keyboard Shortcut Conflicts Conflictos de métodos abreviados de teclado Keyboard Shortcut Set Conjunto de métodos abreviados de teclado @@ -2214,6 +2214,7 @@ font-technology Variable Variables Open the URL in the web browser Abrir la URL en el navegador web Opened with {} note(s): {} Abierto con {} nota(s): {} Open… Abrir… + Optical Óptico Optical Margin Alignment Alineación óptica de márgenes Optimize for fast web view Optimizar para vista web rápida Optimized Optimizado @@ -3843,6 +3844,7 @@ axis Both Ambos # names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are. @msg no library `{id}` no hay ninguna biblioteca `{id}` @msg select some type first selecciona primero algún texto +@msg kerning must be a number, "auto", or "optical" El interletraje debe ser un número, «auto» u «optical» @msg the selection has no gradient fill la selección no tiene un degradado de relleno @msg the selection has no gradient stroke la selección no tiene un degradado de trazo @msg the selection has no pattern fill la selección no tiene un motivo de relleno diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 606118dba8..e080c8f98d 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1411,7 +1411,6 @@ lighting Light Valo Fractional Widths Murtolukuleveydet Hide Options Piilota asetukset Horizontal Scale % Vaakaskaalaus % - Kerning (0 = Auto) Parivälistys (0 = automaattinen) Leading Riviväli No Break Ei katkoa Proportional Metrics Suhteelliset metriikat @@ -3453,6 +3452,7 @@ theme Appearance Ulkoasu Identify Objects By Tunnista objektit Include SVG Code Sisällytä SVG-koodi Italian Italia + Kerning Parivälistys Keyboard Increment Näppäimistön lisäys Language Options Kieliasetukset Large Suuri @@ -3481,6 +3481,7 @@ theme Appearance Ulkoasu On Paste Liitettäessä On Screen Näytöllä Open Documents As Tabs Avaa asiakirjat välilehtinä + Optical Optinen Options Asetukset Output All Blacks Accurately Tulosta kaikki mustat tarkasti Output All Blacks as Rich Black Tulosta kaikki mustat syvämustina @@ -4067,6 +4068,7 @@ imageTrace Outline Ääriviiva @plural {n} stroke|{n} strokes {n} viiva|{n} viivaa @msg no library `{id}` ei kirjastoa `{id}` @msg select some type first valitse ensin tekstiä +@msg kerning must be a number, "auto", or "optical" Parivälistyksen on oltava luku, ”auto” tai ”optical” @msg the selection has no gradient fill valinnalla ei ole liukuväritäyttöä @msg the selection has no gradient stroke valinnalla ei ole liukuväriviivaa @msg the selection has no pattern fill valinnalla ei ole kuviotäyttöä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 5e8203d511..dd9cc259a2 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1625,7 +1625,7 @@ font-technology Variable Variables Keep the pasted color as a new swatch with a numbered name. Conserver la couleur collée comme nouvelle nuance avec un nom numéroté. Keep this row's colors (exclude) Conserver les couleurs de cette ligne (exclure) Keep: Conserver : - Kerning (0 = Auto) Crénage (0 = auto) + Kerning Crénage Keyboard Increment Incrément clavier Keyboard Shortcut Conflicts Conflits de raccourcis clavier Keyboard Shortcut Set Jeu de raccourcis clavier @@ -2212,6 +2212,7 @@ font-technology Variable Variables Open the URL in the web browser Ouvrir l’URL dans le navigateur web Opened with {} note(s): {} Ouvert avec {} remarque(s) : {} Open… Ouvrir… + Optical Optique Optical Margin Alignment Alignement optique des marges Optimize for fast web view Optimiser pour un affichage web rapide Optimized Optimisé @@ -3839,6 +3840,7 @@ axis Both Les deux # names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are. @msg no library `{id}` aucune bibliothèque `{id}` @msg select some type first sélectionnez d’abord du texte +@msg kerning must be a number, "auto", or "optical" Le crénage doit être un nombre, « auto » ou « optical » @msg the selection has no gradient fill la sélection n’a pas de dégradé de fond @msg the selection has no gradient stroke la sélection n’a pas de dégradé de contour @msg the selection has no pattern fill la sélection n’a pas de motif de fond diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index aec44044da..671a569caa 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2044,8 +2044,8 @@ file-filter Templates Sablonok Keep visible surfaces only when expanding Kibontáskor csak a látható felületek megtartása Keep: Megtartás: Keeps the document editable: VectorCraft reopens the PDF with nothing lost. For files you'll edit again. Szerkeszthető marad a dokumentum: a VectorCraft veszteség nélkül nyitja meg újra a PDF-et. Azokhoz a fájlokhoz, amelyeket még szerkesztesz. - Kerning (0 = Auto) Alávágás (0 = automatikus) Key Color: Kulcsszín: + Kerning Alávágás Keyboard Increment Billentyűzetes lépésköz Keyboard Shortcut Conflicts Billentyűparancs-ütközések Keyboard Shortcut Set Billentyűparancs-készlet @@ -2688,6 +2688,7 @@ file-filter Templates Sablonok “{name}” already exists. Replace it? „{name}” már létezik. Felülírod? The name in the save panel was “{typed}”; VectorCraft added the file type's extension. Replacing the file overwrites its contents. A mentési panelen megadott név ez volt: „{typed}”, a VectorCraft pedig hozzáadta a fájltípus kiterjesztését. A fájl felülírásakor a tartalma elvész. Open… Megnyitás… + Optical Optikai Optical Margin Alignment Optikai margóigazítás Optimize for fast web view Optimalizálás gyors webes megtekintéshez Optimized Optimalizált @@ -5044,6 +5045,7 @@ imageTrace Outline Körvonal @msg select paths or anchor points jelölj ki útvonalakat vagy horgonypontokat @msg select paths to join jelöld ki az összekapcsolandó útvonalakat @msg select some type first előbb jelölj ki szöveget +@msg kerning must be a number, "auto", or "optical" Az alávágás szám, „auto” vagy „optical” lehet @msg the selection has no gradient fill a kijelölésnek nincs színátmenetes kitöltése @msg the selection has no gradient stroke a kijelölésnek nincs színátmenetes körvonala @msg the selection has no pattern fill a kijelölésnek nincs mintázatos kitöltése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 5329eea88d..664551a1fa 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1351,7 +1351,6 @@ lighting Light Cahaya Fractional Widths Lebar fraksional Hide Options Sembunyikan opsi Horizontal Scale % Skala horizontal % - Kerning (0 = Auto) Kerning (0 = Otomatis) Leading Leading No Break Tanpa pemenggalan Proportional Metrics Metrik proporsional @@ -3271,6 +3270,7 @@ theme Appearance Tampilan Identify Objects By Identifikasi objek berdasarkan Include SVG Code Sertakan kode SVG Italian Italia + Kerning Kerning Keyboard Increment Inkremen papan ketik Language Options Opsi bahasa Large Besar @@ -3299,6 +3299,7 @@ theme Appearance Tampilan On Paste Saat menempel On Screen Di layar Open Documents As Tabs Buka dokumen sebagai tab + Optical Optis Options Opsi Output All Blacks Accurately Keluarkan semua warna hitam secara akurat Output All Blacks as Rich Black Keluarkan semua warna hitam sebagai rich black @@ -3881,6 +3882,7 @@ imageTrace Outline Kontur @plural {n} stroke|{n} strokes {n} goresan @msg no library `{id}` tidak ada pustaka `{id}` @msg select some type first pilih beberapa teks terlebih dahulu +@msg kerning must be a number, "auto", or "optical" Kerning harus berupa angka, “auto”, atau “optical” @msg {_1} has no {_2} style {_1} tidak memiliki gaya {_2} @msg a layer couldn't be read satu lapisan tidak dapat dibaca @msg it has more than one artboard memiliki lebih dari satu artboard diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 34c18549d2..708378ba43 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1650,7 +1650,7 @@ file-filter Templates Modelli Keep the pasted color as a new swatch with a numbered name. Mantieni il colore incollato come nuovo campione con un nome numerato. Keep this row's colors (exclude) Mantieni i colori di questa riga (escludi) Keep: Mantieni: - Kerning (0 = Auto) Crenatura (0 = auto) + Kerning Crenatura Keyboard Increment Incremento da tastiera Keyboard Shortcut Conflicts Conflitti tra scelte rapide da tastiera Keyboard Shortcut Set Set di scelte rapide da tastiera @@ -2241,6 +2241,7 @@ file-filter Templates Modelli Open the URL in the web browser Apri l'URL nel browser web Opened with {} note(s): {} Aperto con note ({}): {} Open… Apri… + Optical Ottica Optical Margin Alignment Allineamento ottico dei margini Optimize for fast web view Ottimizza per visualizzazione web veloce Optimized Ottimizzato @@ -3883,6 +3884,7 @@ axis Both Entrambi # names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are. @msg no library `{id}` nessuna libreria `{id}` @msg select some type first seleziona prima del testo +@msg kerning must be a number, "auto", or "optical" La crenatura deve essere un numero, «auto» o «optical» @msg the selection has no gradient fill la selezione non ha una sfumatura di riempimento @msg the selection has no gradient stroke la selezione non ha una sfumatura di traccia @msg the selection has no pattern fill la selezione non ha un motivo di riempimento diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 5d8e120742..628f0ec033 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1880,7 +1880,7 @@ font-technology Variable バリアブル Keep Plain Text テキストのみを保持 Keep both sides the same width 両側を同じ幅に保つ Keep this row's colors (exclude) この行のカラーを保持 (除外) - Kerning (0 = Auto) カーニング (0 = 自動) + Kerning カーニング Keyboard Increment キー入力 Keyboard Shortcut Conflicts キーボードショートカットの競合 Keyboard Shortcut Set キーボードショートカットセット @@ -2346,6 +2346,7 @@ font-technology Variable バリアブル Open the URL in the web browser URL を Web ブラウザーで開く Optimize for fast web view Web ビュー用に最適化 Optimized 最適化 + Optical オプティカル Options オプション Options for Selection… 選択項目のオプション… Options: オプション: @@ -4573,6 +4574,7 @@ swatch Bright Violet ビビッドバイオレット @msg choose a folder to export to 書き出し先のフォルダーを選択してください @msg the selection has no URL (or they differ) 選択したオブジェクトに URL がありません (または URL がそれぞれ異なります) @msg select some type first 先にテキストを選択してください +@msg kerning must be a number, "auto", or "optical" カーニングは数値、「auto」または「optical」にしてください @msg the selection has no gradient fill 選択したオブジェクトに塗りのグラデーションがありません @msg the selection has no gradient stroke 選択したオブジェクトに線のグラデーションがありません @msg the selection has no pattern fill 選択したオブジェクトに塗りのパターンがありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index ab0f0704d5..4d44093f71 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1268,7 +1268,6 @@ lighting Light სინათლე Fractional Widths წილადი სიგანეები Hide Options პარამეტრების დამალვა Horizontal Scale % ჰორიზონტალური მასშტაბი % - Kerning (0 = Auto) კერნინგი (0 = ავტო) Leading სტრიქონთა დაშორება No Break გადატანის გარეშე Proportional Metrics პროპორციული მეტრიკა @@ -3082,6 +3081,7 @@ theme Appearance იერსახე Identify Objects By ობიექტების იდენტიფიკაცია: Include SVG Code SVG კოდის ჩართვა Italian იტალიური + Kerning კერნინგი Keyboard Increment კლავიატურის ბიჯი Language Options ენის პარამეტრები Large დიდი @@ -3110,6 +3110,7 @@ theme Appearance იერსახე On Paste ჩასმისას On Screen ეკრანზე Open Documents As Tabs დოკუმენტების ჩანართებად გახსნა + Optical ოპტიკური Options პარამეტრები Output All Blacks Accurately ყველა შავის ზუსტად გამოტანა Output All Blacks as Rich Black ყველა შავის მდიდარ შავად გამოტანა @@ -3647,6 +3648,7 @@ font-technology Variable ცვლადი @plural {n} stroke|{n} strokes კონტური: {n} @msg no library `{id}` ბიბლიოთეკა `{id}` არ არსებობს @msg select some type first ჯერ მონიშნეთ ტექსტი +@msg kerning must be a number, "auto", or "optical" კერნინგი უნდა იყოს რიცხვი, „auto“ ან „optical“ @msg the selection has no gradient fill მონიშნულს შევსების გრადიენტი არ აქვს @msg the selection has no gradient stroke მონიშნულს კონტურის გრადიენტი არ აქვს @msg the selection has no pattern fill მონიშნულს შევსების პატერნი არ აქვს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 5da60d2476..dea1f8f503 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1909,7 +1909,7 @@ font-technology Variable 가변 Keep Plain Text 일반 텍스트 유지 Keep both sides the same width 양쪽 너비를 같게 유지 Keep this row's colors (exclude) 이 행의 색상 유지 (제외) - Kerning (0 = Auto) 커닝 (0 = 자동) + Kerning 커닝 Keyboard Increment 키보드 증분 Keyboard Shortcut Conflicts 단축키 충돌 Keyboard Shortcut Set 단축키 세트 @@ -2337,6 +2337,7 @@ font-technology Variable 가변 Open the URL in the web browser 웹 브라우저에서 URL 열기 Optimize for fast web view 빠른 웹 보기용으로 최적화 Optimized 최적화됨 + Optical 광학 Options 옵션 Options for Selection… 선택 항목 옵션… Options: 옵션: @@ -4501,6 +4502,7 @@ theme Appearance 외관 @msg choose a folder to export to 내보낼 폴더를 선택하세요 @msg the selection has no URL (or they differ) 선택 항목에 URL이 없거나 서로 다릅니다 @msg select some type first 먼저 문자를 선택하세요 +@msg kerning must be a number, "auto", or "optical" 커닝은 숫자, “auto” 또는 “optical”이어야 합니다 @msg the selection has no gradient fill 선택 항목에 칠 그레이디언트가 없습니다 @msg the selection has no gradient stroke 선택 항목에 선 그레이디언트가 없습니다 @msg the selection has no pattern fill 선택 항목에 칠 패턴이 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ee4e09b61f..19fdc86635 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1365,7 +1365,6 @@ lighting Light Licht Fractional Widths Fractionele breedtes Hide Options Opties verbergen Horizontal Scale % Horizontale schaal % - Kerning (0 = Auto) Kerning (0 = Auto) Leading Regelafstand No Break Niet afbreken Proportional Metrics Proportionele metingen @@ -3285,6 +3284,7 @@ theme Appearance Vormgeving Identify Objects By Objecten identificeren op Include SVG Code SVG-code opnemen Italian Italiaans + Kerning Kerning Keyboard Increment Toetsenbordincrement Language Options Taalopties Large Groot @@ -3313,6 +3313,7 @@ theme Appearance Vormgeving On Paste Bij plakken On Screen Op scherm Open Documents As Tabs Documenten openen als tabbladen + Optical Optisch Options Opties Output All Blacks Accurately Alle zwarttinten nauwkeurig uitvoeren Output All Blacks as Rich Black Alle zwarttinten uitvoeren als rijk zwart @@ -3895,6 +3896,7 @@ imageTrace Outline Contour @plural {n} stroke|{n} strokes {n} lijn|{n} lijnen @msg no library `{id}` geen bibliotheek `{id}` @msg select some type first selecteer eerst wat tekst +@msg kerning must be a number, "auto", or "optical" Kerning moet een getal, ‘auto’ of ‘optical’ zijn @msg {_1} has no {_2} style {_1} heeft geen {_2}stijl @msg a layer couldn't be read een laag kon niet worden gelezen @msg it has more than one artboard het heeft meer dan één tekengebied diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 5c90b4d977..9debbef17a 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1350,7 +1350,6 @@ lighting Light Światło Fractional Widths Szerokości ułamkowe Hide Options Ukryj opcje Horizontal Scale % Skala pozioma % - Kerning (0 = Auto) Kerning (0 = auto) Leading Interlinia No Break Bez podziału Proportional Metrics Metryka proporcjonalna @@ -3392,6 +3391,7 @@ theme Appearance Wygląd Identify Objects By Identyfikuj obiekty według Include SVG Code Dołącz kod SVG Italian Włoski + Kerning Kerning Keyboard Increment Przyrost klawiatury Language Options Opcje języka Large Duże @@ -3420,6 +3420,7 @@ theme Appearance Wygląd On Paste Przy wklejaniu On Screen Na ekranie Open Documents As Tabs Otwieraj dokumenty jako karty + Optical Optyczny Options Opcje Output All Blacks Accurately Wyprowadzaj wszystkie czernie dokładnie Output All Blacks as Rich Black Wyprowadzaj wszystkie czernie jako czerń głęboką @@ -3975,6 +3976,7 @@ imageTrace Outline Kontur @plural {n} stroke|{n} strokes {n} obrys|{n} obrysy|{n} obrysów @msg no library `{id}` brak biblioteki `{id}` @msg select some type first najpierw zaznacz tekst +@msg kerning must be a number, "auto", or "optical" Kerning musi być liczbą, „auto” lub „optical” @msg the selection has no gradient fill zaznaczenie nie ma gradientu wypełnienia @msg the selection has no gradient stroke zaznaczenie nie ma gradientu obrysu @msg the selection has no pattern fill zaznaczenie nie ma wzorka wypełnienia diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0694d8f183..e40d32fb13 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1400,7 +1400,7 @@ Keep Plain Text Manter Texto Simples Keep both sides the same width Manter os dois lados com a mesma largura Keep this row's colors (exclude) Manter as cores desta linha (excluir) - Kerning (0 = Auto) Kerning (0 = Automático) + Kerning Kerning Keyboard Increment Incremento do Teclado Keyboard Shortcut Conflicts Conflitos de Atalhos de Teclado Keyboard Shortcut Set Conjunto de Atalhos de Teclado @@ -1810,6 +1810,7 @@ Open password: Senha de abertura: Open the URL in the web browser Abra a URL no navegador da web Open… Abrir… + Optical Óptico Optical Margin Alignment Alinhamento de Margem Óptica Optimize for fast web view Otimizar para visualização rápida na web Optimized Otimizado @@ -3430,6 +3431,7 @@ axis Both Ambos Drag to the window's left edge to dock Arraste até a borda esquerda da janela para encaixar @msg no library `{id}` nenhuma biblioteca `{id}` @msg select some type first selecione algum texto primeiro +@msg kerning must be a number, "auto", or "optical" O kerning deve ser um número, “auto” ou “optical” @msg the selection has no gradient fill a seleção não tem gradiente de preenchimento @msg the selection has no gradient stroke a seleção não tem gradiente de traçado @msg the selection has no pattern fill a seleção não tem padrão de preenchimento diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 105ba72d17..7bfca518c4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1648,7 +1648,7 @@ file-filter Templates Шаблоны Keep the pasted color as a new swatch with a numbered name. Сохранять вставленный цвет как новый образец с номерным именем. Keep this row's colors (exclude) Сохранить цвета этой строки (исключить) Keep: Сохранять: - Kerning (0 = Auto) Кернинг (0 = авто) + Kerning Кернинг Keyboard Increment Приращение с клавиатуры Keyboard Shortcut Conflicts Конфликты сочетаний клавиш Keyboard Shortcut Set Набор сочетаний клавиш @@ -2237,6 +2237,7 @@ file-filter Templates Шаблоны Open the URL in the web browser Открыть URL в веб-браузере Opened with {} note(s): {} Открыто с примечаниями ({}) : {} Open… Открыть… + Optical Оптический Optical Margin Alignment Оптическое выравнивание полей Optimize for fast web view Оптимизировать для быстрого просмотра в web Optimized Оптимизировано @@ -3879,6 +3880,7 @@ axis Both Оба # names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are. @msg no library `{id}` нет библиотеки `{id}` @msg select some type first сначала выделите текст +@msg kerning must be a number, "auto", or "optical" Кернинг должен быть числом, «auto» или «optical» @msg the selection has no gradient fill у выделения нет градиентной заливки @msg the selection has no gradient stroke у выделения нет градиентной обводки @msg the selection has no pattern fill у выделения нет узорной заливки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 4831119887..1bd22f672d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1587,7 +1587,7 @@ font-technology Variable Variabla Keep the pasted color as a new swatch with a numbered name. Behåll den inklistrade färgen som en ny färgruta med numrerat namn. Keep this row's colors (exclude) Behåll radens färger (undanta) Keep: Behåll: - Kerning (0 = Auto) Kerning (0 = auto) + Kerning Kerning Keyboard Increment Tangentbordssteg Keyboard Shortcut Conflicts Konflikter mellan kortkommandon Keyboard Shortcut Set Uppsättning kortkommandon @@ -2159,6 +2159,7 @@ font-technology Variable Variabla Open the URL in the web browser Öppna URL:en i webbläsaren Opened with {} note(s): {} Öppnad med {} anteckning(ar): {} Open… Öppna… + Optical Optisk Optical Margin Alignment Optisk marginaljustering Optimize for fast web view Optimera för snabb webbvisning Optimized Optimerad @@ -3761,6 +3762,7 @@ axis Both Båda Float Tool Group Gör verktygsgruppen flytande @msg no library `{id}` inget bibliotek `{id}` @msg select some type first markera någon text först +@msg kerning must be a number, "auto", or "optical" Kerning måste vara ett tal, ”auto” eller ”optical” @msg the selection has no gradient fill markeringen har ingen fyllnadsgradient @msg the selection has no gradient stroke markeringen har ingen konturgradient @msg the selection has no pattern fill markeringen har inget fyllnadsmönster diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 5e53f4fefe..41456bf052 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -576,7 +576,7 @@ fn character_panel_terms_agree_within_each_catalog() { for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { let (entries, _) = parse_entries(l.source); let row = |src: &str| entries.iter().find(|(ctx, s, _)| ctx.is_empty() && s == src).map(|(_, _, tr)| tr.to_lowercase()); - let kerning = row("Kerning (0 = Auto)").map(|tr| tr.split(" (").next().unwrap_or_default().trim().to_string()); + let kerning = row("Kerning"); let leading = row("Leading"); let tracking = row("Tracking"); for (a, b) in [(&kerning, &leading), (&kerning, &tracking), (&leading, &tracking)] { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 23bdb68391..deb3e95d78 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1474,7 +1474,7 @@ font-technology Variable Değişken Keep the pasted color as a new swatch with a numbered name. Yapıştırılan rengi numaralı bir adla yeni bir renk örneği olarak koruyun. Keep this row's colors (exclude) Bu satırın renklerini koru (hariç tut) Keep: Sakla: - Kerning (0 = Auto) Karakter Aralığı (0 = Otomatik) + Kerning Karakter aralığı Keyboard Increment Klavye Artışı Keyboard Shortcut Conflicts Klavye Kısayolu Çakışmaları Keyboard Shortcut Set Klavye Kısayol Seti @@ -2038,6 +2038,7 @@ shape Open Açık Open the URL in the web browser URL'yi web tarayıcısında açın Opened with {} note(s): {} {} notla açıldı: {} Open… Aç… + Optical Optik Optical Margin Alignment Optik Kenar Boşluğu Hizalaması Optimize for fast web view Hızlı web görünümü için optimize edin Optimized Optimize edilmiş @@ -3655,6 +3656,7 @@ axis Both Her İkisi Float Tool Group Araç Grubunu Yüzer Yap @msg no library `{id}` `{id}` kütüphanesi yok @msg select some type first önce bir tür seçin +@msg kerning must be a number, "auto", or "optical" Karakter aralığı sayı, “auto” veya “optical” olmalıdır @msg the selection has no gradient fill seçimin degrade dolgusu yok @msg the selection has no gradient stroke seçimin degrade konturu yok @msg the selection has no pattern fill seçimin desen dolgusu yok diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dde23c7422..d78f48b331 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1644,7 +1644,7 @@ file-filter Templates Шаблони Keep the pasted color as a new swatch with a numbered name. Зберігати вставлений колір як новий зразок із номерним ім’ям. Keep this row's colors (exclude) Зберегти кольори цього рядка (виключити) Keep: Зберігати: - Kerning (0 = Auto) Кернінг (0 = авто) + Kerning Кернінг Keyboard Increment Крок клавіатури Keyboard Shortcut Conflicts Конфлікти поєднань клавіш Keyboard Shortcut Set Набір клавіш @@ -2233,6 +2233,7 @@ file-filter Templates Шаблони Open the URL in the web browser Відкрити URL у веб-браузері Opened with {} note(s): {} Відкрито із примітками ({}) : {} Open… Відкрити… + Optical Оптичний Optical Margin Alignment Оптичне вирівнювання полів Optimize for fast web view Оптимізувати для швидкого перегляду web Optimized Оптимізовано @@ -3867,6 +3868,7 @@ axis Both Обидві Float Tool Group Від’єднати групу інструментів @msg no library `{id}` немає бібліотеки `{id}` @msg select some type first спочатку виділіть текст +@msg kerning must be a number, "auto", or "optical" Кернінг має бути числом, «auto» або «optical» @msg the selection has no gradient fill виділення не має градієнтної заливки @msg the selection has no gradient stroke виділення не має градієнтного обведення @msg the selection has no pattern fill виділення не має візерункової заливки diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index e060c09993..ade0a07aae 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1922,8 +1922,8 @@ file-filter Templates Mẫu Keep this row's colors (exclude) Giữ màu của hàng này (loại trừ) Keep visible surfaces only when expanding Chỉ giữ bề mặt hiển thị khi mở rộng Keep: Giữ: - Kerning (0 = Auto) Kerning (0 = Tự động) Key Color: Màu chủ: + Kerning Kerning Keyboard Increment Bước nhảy bàn phím Keyboard Shortcut Conflicts Xung đột phím tắt Keyboard Shortcut Set Bộ phím tắt @@ -2499,6 +2499,7 @@ file-filter Templates Mẫu “{name}” already exists. Replace it? “{name}” đã tồn tại. Thay thế tệp này? The name in the save panel was “{typed}”; VectorCraft added the file type's extension. Replacing the file overwrites its contents. Tên trong bảng lưu là “{typed}”, và VectorCraft đã thêm phần mở rộng của loại tệp. Thay thế tệp sẽ ghi đè nội dung của tệp. Open… Mở… + Optical Quang học Optical Margin Alignment Căn lề quang học Optimize for fast web view Tối ưu để xem web nhanh Optimized Đã tối ưu @@ -4696,6 +4697,7 @@ theme Appearance Giao diện @msg select paths or anchor points chọn đường dẫn hoặc điểm neo @msg select paths to join hãy chọn đường dẫn để nối @msg select some type first hãy chọn chữ trước +@msg kerning must be a number, "auto", or "optical" Kerning phải là số, “auto” hoặc “optical” @msg the selection has no gradient fill vùng chọn không có tô chuyển sắc @msg the selection has no gradient stroke vùng chọn không có nét chuyển sắc @msg the selection has no pattern fill vùng chọn không có tô họa tiết diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 65842950a7..acffa1e4e9 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1575,7 +1575,7 @@ file-filter Templates 模板 Keep the pasted color as a new swatch with a numbered name. 将粘贴的颜色保留为新色板,并以编号命名。 Keep this row's colors (exclude) 保留此行的颜色 (排除) Keep: 保留: - Kerning (0 = Auto) 字偶距 (0 = 自动) + Kerning 字偶距 Keyboard Increment 键盘增量 Keyboard Shortcut Conflicts 键盘快捷键冲突 Keyboard Shortcut Set 键盘快捷键组 @@ -2113,6 +2113,7 @@ file-filter Templates 模板 Opened with {} note(s): {} 已打开,附 {} 条附注:{} OpenType OpenType Open… 打开… + Optical 视觉 Optical Margin Alignment 视觉边界对齐 Optimize for fast web view 优化快速 Web 查看 Optimized 优化 @@ -4290,6 +4291,7 @@ imageTrace Outline 轮廓 @msg choose a folder to export to 请选择要导出到的文件夹 @msg the selection has no URL (or they differ) 所选对象没有 URL (或其 URL 各不相同) @msg select some type first 请先选择一些文字 +@msg kerning must be a number, "auto", or "optical" 字偶距必须是数字、“auto”或“optical” @msg the selection has no gradient fill 所选对象没有渐变填色 @msg the selection has no gradient stroke 所选对象没有渐变描边 @msg the selection has no pattern fill 所选对象没有图案填色 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index fb06daa662..3b560be95b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1614,7 +1614,7 @@ file-filter Templates 範本 Keep the pasted color as a new swatch with a numbered name. 將貼上的顏色保留為新色票,並以編號命名。 Keep this row's colors (exclude) 保留此列的顏色 (排除) Keep: 保留: - Kerning (0 = Auto) 字距微調 (0 = 自動) + Kerning 字距微調 Keyboard Increment 鍵盤增量 Keyboard Shortcut Conflicts 鍵盤快速鍵衝突 Keyboard Shortcut Set 鍵盤快速鍵組 @@ -2228,6 +2228,7 @@ file-filter Templates 範本 @msg choose a folder to export to 請選擇要匯出至的資料夾 @msg the selection has no URL (or they differ) 選取範圍沒有 URL (或其 URL 各不相同) @msg select some type first 請先選取一些文字 +@msg kerning must be a number, "auto", or "optical" 字距微調必須是數字、「auto」或「optical」 @msg the selection has no gradient fill 選取範圍沒有漸層填色 @msg the selection has no gradient stroke 選取範圍沒有漸層筆畫 @msg the selection has no pattern fill 選取範圍沒有圖樣填色 @@ -3047,6 +3048,7 @@ file-filter Templates 範本 Opened with {} note(s): {} 已開啟,附 {} 則附註:{} OpenType OpenType Open… 開啟… + Optical 視覺 Optical Margin Alignment 視覺邊界對齊 Optimize for fast web view 最佳化以便快速網頁檢視 Optimized 最佳化 diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 91dc0a7410..82445374b3 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -222,7 +222,7 @@ fn char_cmd(app: &mut VectorcraftApp, cmd: &str, p: Value) { range_style(app, p); } -/// Set the Kerning field's `value` (a number or "auto"). At a caret in text the Type tool edits +/// Set the Kerning field's `value` (a number, "auto", or "optical"). At a caret in text the Type tool edits /// it is the pair kerning after the character before the caret, as Alt+←/→ steps it /// (`type.step`); nowhere to set at the start of the text. Else it is a character attribute like /// the others: the selected range, or all the text. @@ -244,6 +244,37 @@ fn set_kerning(app: &mut VectorcraftApp, value: Value) { app.run("text.setRangeStyle", json!({"id": id.0, "start": start, "end": a, "kerning": value})).ok(); } +/// The pair before the caret, in 1/1000 em, using the layout the canvas draws. +fn caret_kerning(app: &VectorcraftApp, ui: &Ui) -> Option<(f64, bool)> { + let (id, a, b) = text_editing(app)?; + if a != b { + return None; + } + let NodeKind::Text(t) = &app.session.active()?.doc.node(id)?.kind else { return None }; + let text = t.plain_text(); + let start = vectorcraft_text::edit::prev_char(&text, a); + if start >= a { + return None; + } + let style = vectorcraft_text::edit::style_at(&t.runs, start + 1); + if let Some(v) = style.kerning { + return Some((v, false)); + } + let state = app.session.active()?; + let key = (state.uid, state.revision, id, a); + let slot = ui.scope_id().with("caret-kerning"); + if let Some((cached_key, value)) = ui.ctx().data(|d| d.get_temp::<((u64, u64, NodeId, usize), f64)>(slot)) + && cached_key == key + { + return Some((value, true)); + } + let original = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let value = vectorcraft_engine::cmd::effective_kerning(vectorcraft_text::FontDb::global(), t, &original, start, a); + let value = value.round(); + ui.ctx().data_mut(|d| d.insert_temp(slot, (key, value))); + Some((value, true)) +} + /// The faces Type › Bold and Type › Italic switch to. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Face { @@ -637,14 +668,33 @@ pub(crate) fn metrics_grid(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, s: & match widgets::spin_field_auto(ui, "ch-lead", leading, Some(auto), unit, fw, 1.0, 0.1, &SIZE_PRESETS) { Some(SpinPick::Value(v)) => style(app, json!({"leading": v})), Some(SpinPick::Auto) => style(app, json!({"leading": "auto"})), + Some(SpinPick::Optical) => {} None => {} } }); ui.end_row(); - cell(ui, "VA", tl!("Kerning (0 = Auto)"), |ui| { - let kerning = shared(app, |s| s.kerning.unwrap_or(0.0)); - if let Some(v) = widgets::spin_plain(ui, "ch-kern", kerning, "", 0, fw, 10.0, -1000.0, &TRACKING_PRESETS) { - set_kerning(app, if v == 0.0 { json!("auto") } else { json!(v) }); + cell(ui, "VA", tl!("Kerning"), |ui| { + let mode = shared(app, |s| (s.optical_kerning, s.kerning)); + let caret = text_editing(app).is_some_and(|(_, a, b)| a == b); + let at_caret = if caret { caret_kerning(app, ui) } else { None }; + let kerning = at_caret.map(|(v, _)| v).or_else(|| mode.map(|(_, manual)| manual.unwrap_or(0.0))); + let automatic = mode.map(|(optical, manual)| !optical && manual.is_none()); + let optical = mode.map(|(optical, _)| optical); + match widgets::spin_kerning( + ui, + "ch-kern", + kerning, + automatic, + optical, + tl!("Optical"), + at_caret.is_some_and(|(_, auto)| auto), + fw, + &TRACKING_PRESETS, + ) { + Some(SpinPick::Value(v)) => set_kerning(app, json!(v)), + Some(SpinPick::Auto) => set_kerning(app, json!("auto")), + Some(SpinPick::Optical) => set_kerning(app, json!("optical")), + None => {} } }); cell(ui, "VA↔", tl!("Tracking"), |ui| { diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index fe5e53b3eb..61ec42a218 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -130,6 +130,38 @@ fn kerning_at_a_caret_sets_the_pair_not_the_whole_text() { assert_eq!((kerning(&app, 1), kerning(&app, 2), kerning(&app, 3)), (Some(-50.0), Some(30.0), Some(30.0))); } +#[test] +fn character_kerning_setter_and_automatic_pair_value() { + let german = crate::i18n::Lang::from_code("de").unwrap(); + assert!(crate::i18n::has(german, "Optical")); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.run("text.create", json!({"x": 20, "y": 50, "text": "III", "size": 100, "font": "JetBrains Mono"})).unwrap(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + app.session.set_tool_option("select", &json!({"start": 1, "end": 1})); + set_kerning(&mut app, json!("optical")); + assert!(text_style(&app).unwrap().0.optical_kerning); + let ctx = egui::Context::default(); + let mut shown = None; + ctx.run_ui(Default::default(), |ui| { + shown = caret_kerning(&app, ui); + }) + .textures_delta + .clear(); + let (value, automatic) = shown.unwrap(); + assert!(automatic && value != 0.0); + set_kerning(&mut app, json!(50)); + ctx.run_ui(Default::default(), |ui| { + shown = caret_kerning(&app, ui); + }) + .textures_delta + .clear(); + assert_eq!(shown, Some((50.0, false))); + app.session.set_tool_option("select", &json!({"start": 0, "end": 2})); + assert_eq!(shared(&app, |s| (s.optical_kerning, s.kerning)), None, "a mixed range shows a blank Kerning field"); +} + /// Highlight Kerning and Highlight Tracking show the Character panel and give its field the /// keyboard focus with the value selected: what is typed replaces it, and Enter applies it. /// Highlight Font Name opens the font family menu with its search field focused. Without diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index c6b855ffdc..30a6fa2b71 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -51,7 +51,7 @@ pub(crate) use numeric::{ANY, round_to, set_bare_numbers_are_points, typed_unit} pub use numeric::{ SpinPick, mixed_field, mixed_field_named, num_field, num_field_named, num_field_within, opt_field, opt_field_named, range_field, range_field_named, range_field_stepped, size_field, size_field_named, slider, spin_field, spin_field_auto, spin_field_auto_named, - spin_field_named, spin_field_stops_named, spin_plain, spin_plain_named, + spin_field_named, spin_field_stops_named, spin_kerning, spin_plain, spin_plain_named, }; #[cfg(test)] use numeric::{decimal_point, share_of, spinner_step, step_through, step_to_multiple, within_a_millionth}; diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index 1867eb271b..9244c32bf6 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -346,7 +346,7 @@ pub fn range_field_named( let places = decimals.min(6) as i32; let value = value.into().map(|v| within(v, &range)); let label = take_previous_label(ui); - bounded_field(ui, id, label, name, value, suffix, decimals, width, &range, None).map(|v| within(round_to(v, places), &range)) + bounded_field(ui, id, label, name, value, suffix, decimals, width, &range, None, false).map(|v| within(round_to(v, places), &range)) } /// [`range_field`] whose ↑/↓ and wheel take `step`'s steps instead of whole numbers (see @@ -366,7 +366,7 @@ pub fn range_field_stepped( let places = decimals.min(6) as i32; let value = value.into().map(|v| within(v, &range)); let label = take_previous_label(ui); - bounded_field(ui, id, label, None, value, suffix, decimals, width, &range, Some(step)).map(|v| within(round_to(v, places), &range)) + bounded_field(ui, id, label, None, value, suffix, decimals, width, &range, Some(step), false).map(|v| within(round_to(v, places), &range)) } /// [`plain_field`] for a value the selected objects may not share: `None` shows a blank field. @@ -385,7 +385,7 @@ pub fn mixed_field_named( width: f32, ) -> Option<f64> { let label = take_previous_label(ui); - bounded_field(ui, id, label, name, value, suffix, decimals, width, &ANY, None) + bounded_field(ui, id, label, name, value, suffix, decimals, width, &ANY, None, false) } /// [`mixed_field`] whose ↑/↓, wheel and scrub stop at `bounds`; ↑/↓ and the wheel take `step`'s steps @@ -403,6 +403,7 @@ fn bounded_field( width: f32, bounds: &RangeInclusive<f64>, step: Option<fn(f64, f64) -> f64>, + parentheses: bool, ) -> Option<f64> { let armed = take_armed_focus(ui, &id); let id = id_with(ui.scope_id(), id); @@ -412,9 +413,9 @@ fn bounded_field( let suffix = suffix.trim(); let buf = decimal_point(buf); let bare = if suffix.is_empty() { buf.to_string() } else { buf.replace(suffix, "") }; - vectorcraft_doc::parse_number(&bare.replace(['%', '°'], "")) + vectorcraft_doc::parse_number(&bare.replace(['%', '°', '(', ')'], "")) }; - let shown = value.map(show).unwrap_or_default(); + let shown = value.map(|v| if parentheses { format!("({})", show(v)) } else { show(v) }).unwrap_or_default(); take_dialog_focus(ui, id, &shown); if armed { focus_field(ui, id, &shown); @@ -508,7 +509,7 @@ pub fn spin_field_stops_named( presets: &[f64], ) -> Option<f64> { let label = take_previous_label(ui); - spin_generic(ui, label, value, None, width, step, min, presets, presets, &|v| unit.format(v), &mut |ui, fw, label| { + spin_generic(ui, label, value, None, None, None, width, step, min, presets, presets, &|v| unit.format(v), &mut |ui, fw, label| { unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, presets) }) .and_then(SpinPick::value) @@ -519,6 +520,7 @@ pub fn spin_field_stops_named( pub enum SpinPick { Value(f64), Auto, + Optical, } impl SpinPick { @@ -527,6 +529,7 @@ impl SpinPick { match self { SpinPick::Value(v) => Some(v), SpinPick::Auto => None, + SpinPick::Optical => None, } } } @@ -563,7 +566,7 @@ pub fn spin_field_auto_named( presets: &[f64], ) -> Option<SpinPick> { let label = take_previous_label(ui); - spin_generic(ui, label, value, auto, width, step, min, presets, &[], &|v| unit.format(v), &mut |ui, fw, label| { + spin_generic(ui, label, value, auto, None, None, width, step, min, presets, &[], &|v| unit.format(v), &mut |ui, fw, label| { unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, &[]) }) } @@ -602,12 +605,43 @@ pub fn spin_plain_named( let label = take_previous_label(ui); let value = value.into(); let fmt = |v: f64| format!("{v}{suffix}"); - spin_generic(ui, label, value, None, width, step, min, presets, &[], &fmt, &mut |ui, fw, label| { - bounded_field(ui, id, label, name, value, suffix, decimals, fw, &(min..=f64::INFINITY), None) + spin_generic(ui, label, value, None, None, None, width, step, min, presets, &[], &fmt, &mut |ui, fw, label| { + bounded_field(ui, id, label, name, value, suffix, decimals, fw, &(min..=f64::INFINITY), None, false) }) .and_then(SpinPick::value) } +/// Kerning's numeric field and automatic method choices. +#[allow(clippy::too_many_arguments)] +pub fn spin_kerning( + ui: &mut Ui, + id: impl std::hash::Hash + Copy, + value: Option<f64>, + automatic: Option<bool>, + optical: Option<bool>, + optical_label: &str, + parentheses: bool, + width: f32, + presets: &[f64], +) -> Option<SpinPick> { + let label = take_previous_label(ui); + spin_generic( + ui, + label, + value, + automatic, + optical, + Some(optical_label), + width, + 10.0, + -1000.0, + presets, + &[], + &|v| format!("{v}"), + &mut |ui, fw, label| bounded_field(ui, id, label, None, value, "", 0, fw, &(-1000.0..=f64::INFINITY), None, parentheses), + ) +} + type SpinField<'a> = dyn FnMut(&mut Ui, f32, Option<PreviousLabel>) -> Option<f64> + 'a; #[allow(clippy::too_many_arguments)] @@ -616,6 +650,8 @@ fn spin_generic( label: Option<PreviousLabel>, value: Option<f64>, auto: Option<bool>, + optical: Option<bool>, + optical_label: Option<&str>, width: f32, step: f64, min: f64, @@ -674,6 +710,11 @@ fn spin_generic( { out = Some(SpinPick::Auto); } + if let Some(on) = optical + && ui.selectable_label(on, optical_label.unwrap_or_default()).clicked() + { + out = Some(SpinPick::Optical); + } let current = value.filter(|_| auto != Some(true)); for p in presets { if ui.selectable_label(current.is_some_and(|v| (v - p).abs() < 1e-6), fmt(*p)).clicked() { diff --git a/docs/mcp.md b/docs/mcp.md index 0595340df1..129d7346c3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3217,7 +3217,8 @@ Pen's second anchor at (150, 431), in line with the square's centre. leading (↑/↓ in horizontal type, ←/→ in vertical type), and baseline shift (Shift+↑/↓ in horizontal type, Shift+→/← in vertical type). Mixed selected text objects use the horizontal mapping; Cmd/Ctrl makes five steps. `type.resetTracking` (Cmd+Alt+Q, `press_key {key: "Q", mods: {cmd: true, alt: true}}`) sets tracking to 0 and - kerning to Auto in the type objects in `ids`, the Type tool's selected text or the selected type objects; at a caret + clears manual kerning in the type objects in `ids`, the Type tool's selected text or the selected type objects, + keeping Optical; at a caret it resets only the kerning of the character before it. `type.resetHorizontalScale` (Cmd+Shift+X, `press_key {key: "X", mods: {cmd: true, shift: true}}`) sets the horizontal scale to 100%, as the Character panel shows it, in the same text; at a caret it leaves the text as it is. In the app, `type.highlightKerning` (Cmd+Alt+K), @@ -4918,6 +4919,16 @@ the paragraph's text now starts; when the text before `at` starts no list, nothi {"name":"run_command","arguments":{"command":"text.convertListToText","params":{}}} ``` +## Kerning + +`text.setRangeStyle {id, start, end, kerning}` (a range) and `text.setFormat {ids?, kerning}` +(the selected type) accept `kerning: "auto" | "optical" | number` (1/1000 em). Auto uses the font's +pair metrics; Optical spaces horizontal pairs from their glyph shapes. Vertical text uses font +metrics in either mode. A number sets a manual pair value, +replacing that pair's automatic correction while tracking remains additive. Choosing Optical keeps +existing manual pair values; choosing `"auto"` clears them. New text and files without an Optical setting use Auto. The Character +panel offers both automatic modes. + ## Small Caps, Superscript and Subscript `text.setFormat {smallCaps, position}` (the selected type, or `ids`) and `text.setRangeStyle {id, start, end, smallCaps, position}` (a range) set what the Character panel's Small Caps, Superscript and Subscript buttons and menu items set. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3d706ba6bb..e6645bbbce 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -633,7 +633,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With the Artboard tool, Cmd/Ctrl+A after a click on a row of the Artboards panel selects every artboard, as the macOS menu bar's Select All does then; the active artboard stays active, and the art's selection does not change. After a press outside the panel's list, Cmd/Ctrl+A selects every object again. It used to select every object after a click in the panel too. Public reference: [Select artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/select-artboards.html). - Cmd/Ctrl+/ (`appearance.addFill`) and Cmd/Ctrl+Alt+/ (`appearance.addStroke`) add a new fill and a new stroke to the selected objects, as the Appearance panel's Add New Fill and Add New Stroke buttons do, on the keys the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for adding a new fill and a new stroke. Keyboard Shortcuts lists both under Window › Appearance. - Cmd/Ctrl+Alt+Shift+. and , (`type.size.increaseByFive`, `type.size.decreaseByFive`) step the font size of the selected type, or of the text the Type tool has selected, by five times the Size/Leading increment (Preferences › Type); Cmd/Ctrl+Shift+. and , still step it by one increment. - - Cmd/Ctrl+Alt+Q (`type.resetTracking`) sets the tracking of the selected type, or of the text the Type tool has selected, to 0 and its kerning to Auto (0 in the Character panel), in one undo step; at a caret it resets the kerning of the character before it. + - Cmd/Ctrl+Alt+Q (`type.resetTracking`) sets the tracking of the selected type, or of the text the Type tool has selected, to 0 and clears manual kerning while keeping the automatic method, in one undo step; at a caret it resets only the kerning of the character before it. - Cmd/Ctrl+Alt+K (`type.highlightKerning`) and Cmd/Ctrl+Alt+Shift+F (`type.highlightFontName`) show the Character panel and give its Kerning field the keyboard focus with the value selected, or open its font family menu with the search field focused, on the keys the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for highlighting kerning and the font name field. The page lists the same key for selecting the tracking value; `type.highlightTracking` focuses the Tracking field the same way and has no default key in Keyboard Shortcuts. - Cmd/Ctrl+Alt+L (`ui.newLayer`) opens Layer Options for a new layer, as an Alt-click on the Layers panel's New Layer button does, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for adding a layer through the New Layer dialog box. OK adds the layer above the current layer, and Cancel adds none. Cmd/Ctrl+L still adds a layer without the dialog. - F8 (`ui.symbolOptions`) opens Symbol Options for a new symbol made from the selection, as the Symbols panel's New Symbol button does, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for making a new symbol. OK makes the symbol and puts an instance of it in place of the art, and Cancel makes none. With nothing selected, F8 opens no dialog, and the status bar says that nothing is selected. Shift+F8 and Cmd/Ctrl+F8 still show the Transform and Info panels. @@ -840,6 +840,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Vertical type spacing shortcuts:** The [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page gives Alt+Down/Up for kerning at a caret or tracking of selected text, Alt+Left/Right for leading, and Alt+Shift+Right/Left for baseline shift. Alt+Shift+Down/Up also steps kerning or tracking. Down increases kerning or tracking, Left increases leading, and Shift+Right increases baseline shift; the opposite arrows decrease them. Cmd/Ctrl makes five steps. Horizontal type keeps its existing mapping; mixed horizontal and vertical text-object selections take the horizontal mapping for both objects in one undo step. Selected vertical point, area and path type use the same directions. Tests: `spacing_arrows_follow_each_text_objects_orientation`, `alt_arrows_rotate_for_selected_vertical_type`, `mixed_type_objects_take_horizontal_spacing_chords_in_both_orders`, and `selected_vertical_area_and_path_type_use_vertical_spacing_chords`. - **Vertical punctuation:** fullwidth `!` (U+FF01) and `?` (U+FF1F) use their nominal glyph upright when no vertical alternate is present, following the Tu fallback in [Unicode UAX #50 §3.1](https://www.unicode.org/reports/tr50/#vo). Code-built test fonts cover point and area type with and without `vert` alternates, retain the rotated fallback for a bracket and long vowel mark, and leave horizontal type unchanged. Tests: `crates/text/src/tests/vertical.rs`. - Free Distort's dialog (Effect › Distort & Transform › Free Distort…) shows a box in the proportions of the first selected object's bounds with a handle on each corner. Dragging a handle moves that corner. A handle focused by a click or Tab moves 1% of the box with each arrow key, and 10% with Shift. Reset puts the four corners back on the box. The preview and OK run `effect.apply`, or `effect.setParams` when the dialog edits an applied effect, and the Appearance panel's inline editor opens the dialog with Edit…. Behavior reference: Illustrator CC Help (2014, [PDF](https://help.adobe.com/archive/en/illustrator/cc/2014/illustrator_reference.pdf)), page 285 (PDF page 291). +- **Optical kerning:** Character and Properties offer Optical beside Auto for automatic pair spacing. The side-profile spacing method is VectorCraft's own. Optical keeps its mode across cosmetic style runs, and leaves manual pair values and additive tracking intact. Native documents retain the mode and pair overrides; old documents use Auto. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/engine/src/tests/textedit.rs`. - **Kerning across style runs:** characters that differ only in fill, stroke, underline, strikethrough, overprint, character style name, leading, baseline shift, rotation, Character Alignment, kerning, or tracking that keeps or drops ligatures alike are shaped together, so restyling one character keeps the font's kerning pairs with its neighbors. A character with manual kerning that follows one with automatic kerning keeps the font's kerning with it (unless All Caps or Small Caps sets it as two letters, as ß becomes SS), and its value replaces the font's kerning after it. A ligature does not form across a change of style, and a change of font, size or OpenType features still shapes the characters apart. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/text/src/tests/bidi.rs`. - **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515). - **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `<use>` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). diff --git a/docs/typography-lettering.md b/docs/typography-lettering.md index 373f92b964..588a91e77d 100644 --- a/docs/typography-lettering.md +++ b/docs/typography-lettering.md @@ -24,7 +24,7 @@ can use installed system fonts, while the web app uses the fonts supplied by its 6. Adjust **Font Size** (the field beside **T**) and **Tracking** (beside **VA↔**) in the Character panel. Hover a field's label to see its name. For example, enter `72 pt` for a large heading and try tracking `50` to spread its letters slightly. Positive tracking adds space; negative tracking - tightens it. **Leading** controls the spacing between lines; **Kerning (0 = Auto)** adjusts pairs. + tightens it. **Leading** controls the spacing between lines; **Kerning** adjusts pairs. 7. To change only part of the text, select **Type Tool**, click into the text and drag across the characters before using the Character panel. Press **Escape** when finished. Keep the text editable until its wording, font and spacing are settled. From 14100bfab2847625eb1d7280f8e97925fbcdf719 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 1 Nov 2026 00:39:34 +0700 Subject: [PATCH 137/260] Character Styles: Style Options edits the name and Basic Character Formats Squashed from #4809 onto main. --- crates/engine/src/cmd/textstyles.rs | 157 ++++- crates/engine/src/cmd/textstyles/tests.rs | 239 +++++++- crates/ui-egui/src/dialogs.rs | 2 + .../ui-egui/src/dialogs/char_style_options.rs | 548 ++++++++++++++++++ crates/ui-egui/src/dialogs/new_text_style.rs | 53 +- crates/ui-egui/src/i18n/ca.tsv | 6 + crates/ui-egui/src/i18n/cs.tsv | 6 + crates/ui-egui/src/i18n/de.tsv | 6 + crates/ui-egui/src/i18n/el.tsv | 6 + crates/ui-egui/src/i18n/es.tsv | 6 + crates/ui-egui/src/i18n/fi.tsv | 6 + crates/ui-egui/src/i18n/fr.tsv | 6 + crates/ui-egui/src/i18n/hu.tsv | 6 + crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/ja.tsv | 6 + crates/ui-egui/src/i18n/ka.tsv | 6 + crates/ui-egui/src/i18n/ko.tsv | 6 + crates/ui-egui/src/i18n/pl.tsv | 6 + crates/ui-egui/src/i18n/pt-br.tsv | 6 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/sv.tsv | 6 + crates/ui-egui/src/i18n/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + crates/ui-egui/src/i18n/vi.tsv | 6 + crates/ui-egui/src/i18n/zh-hans.tsv | 6 + crates/ui-egui/src/i18n/zh-hant.tsv | 6 + crates/ui-egui/src/menus/run.rs | 5 + crates/ui-egui/src/menus/state.rs | 6 +- crates/ui-egui/src/menus/ui_commands.rs | 12 + crates/ui-egui/src/panels/text_styles.rs | 8 +- .../ui-egui/src/panels/text_styles/tests.rs | 50 ++ docs/mcp.md | 16 + docs/target-app-parity.md | 3 +- 33 files changed, 1188 insertions(+), 37 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/char_style_options.rs diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index c1312fa9ba..30ccbfc7b7 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -8,7 +8,7 @@ use serde::Serialize; use serde::de::DeserializeOwned; use serde_json::{Map, Value, json}; -use vectorcraft_doc::{CharStyle, Document, NodeId, NodeKind, ParaStyle, TextStyleDef}; +use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind, ParaStyle, TextStyleDef}; use super::typecmd::{refresh_bounds, text_targets}; use super::{CommandSpec, Result, Run, Session, bad, bool_or, has_doc, id_param, index, ok, str_param}; @@ -117,6 +117,14 @@ macro_rules! style_cmds { pub fn specs() -> Vec<CommandSpec> { let mut v = style_cmds!(Kind::Char, "charStyle", "Character Styles", "Character"); + v.push(spec( + "charStyle.edit", + "Edit Character Style", + &[], + "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides", + |s, p| edit_style(s, p, Kind::Char), + true, + )); v.extend(style_cmds!(Kind::Para, "paraStyle", "Paragraph Styles", "Paragraph")); v } @@ -245,14 +253,16 @@ fn with_attrs<T: Serialize + DeserializeOwned>(base: &T, attrs: &Map<String, Val } /// `cur` after its style changed from `old` to `new`: attributes still equal to the old style's -/// value (or not set by it) take the new value; overrides stay. `attrs` lists every attribute of -/// `cur` ([`char_attrs`], [`para_attrs`]), so one at its default matches a style that sets the -/// default. Unchanged if the style doesn't round-trip through JSON. +/// value (or not set by it) take the new value, and removed attributes return to `base`; +/// overrides stay. `attrs` lists every attribute of `cur` ([`char_attrs`], [`para_attrs`]), so +/// one at its default matches a style that sets the default. Unchanged if the style doesn't +/// round-trip through JSON. fn restyle<T: Serialize + DeserializeOwned + Clone>( cur: &T, attrs: fn(&T) -> Map<String, Value>, old: &Map<String, Value>, new: &Map<String, Value>, + base: &Map<String, Value>, ) -> T { let Some(full) = to_map(cur) else { return cur.clone() }; let mut m = attrs(cur); @@ -264,6 +274,14 @@ fn restyle<T: Serialize + DeserializeOwned + Clone>( m.insert(k.clone(), v.clone()); } } + for (k, v) in old { + if !new.contains_key(k) + && m.get(k) == Some(v) + && let Some(base_value) = base.get(k) + { + m.insert(k.clone(), base_value.clone()); + } + } serde_json::from_value(Value::Object(m)).unwrap_or_else(|_| cur.clone()) } @@ -282,15 +300,47 @@ fn font_change(before: &CharStyle, mut st: CharStyle, attrs: &Map<String, Value> st } -/// Every text object id in the document. -fn all_text(d: &Document) -> Vec<NodeId> { - let mut v = vec![]; - d.walk(|n| { - if matches!(n.kind, NodeKind::Text(_)) { - v.push(n.id) +/// Change text in layers, symbols, graph designs, pattern tiles, saved pattern tiles restored by +/// Cancel, and brush art, including opacity masks in those trees. +fn each_text_mut(d: &mut Document, f: &mut impl FnMut(&mut vectorcraft_doc::TextObject) -> Result<()>) -> Result<()> { + fn has_text(n: &Node) -> bool { + matches!(n.kind, NodeKind::Text(_)) + || n.extras().mask.as_ref().is_some_and(|mask| has_text(&mask.art)) + || n.children().is_some_and(|children| children.iter().any(|child| has_text(child))) + } + + fn visit(n: &mut Node, f: &mut impl FnMut(&mut vectorcraft_doc::TextObject) -> Result<()>) -> Result<()> { + if let NodeKind::Text(t) = &mut n.kind { + f(t)?; } - }); - v + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + && has_text(&mask.art) + { + visit(std::sync::Arc::make_mut(&mut mask.art), f)?; + } + for child in n.children_mut().into_iter().flatten() { + if has_text(child) { + visit(std::sync::Arc::make_mut(child), f)?; + } + } + Ok(()) + } + let trees = d.layers.iter_mut().chain(d.symbols.iter_mut().map(|s| &mut s.art)).chain(d.graph_designs.iter_mut().map(|g| &mut g.art)); + let patterns = d.patterns.iter_mut().chain(d.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut())); + for root in trees.chain(patterns.flat_map(|p| &mut p.art)) { + if has_text(root) { + visit(std::sync::Arc::make_mut(root), f)?; + } + } + let mut brushes = vectorcraft_brush::library(d); + let original_brushes = brushes.clone(); + for art in brushes.iter_mut().flat_map(|b| b.art_mut()) { + visit(art, f)?; + } + if brushes != original_brushes { + vectorcraft_brush::store(d, &brushes); + } + Ok(()) } fn text_mut(d: &mut Document, id: NodeId) -> Option<&mut vectorcraft_doc::TextObject> { @@ -328,16 +378,20 @@ fn uses_of(uses: &std::collections::HashMap<Option<String>, usize>, kind: Kind, } /// Update every user of `name` from `old` to `new` attributes (overrides kept). -fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Value>, new: &Map<String, Value>) { +fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Value>, new: &Map<String, Value>) -> Result<()> { let target = (name != kind.normal()).then_some(name.to_string()); - for id in all_text(d) { - let Some(t) = text_mut(d, id) else { continue }; + let normal = kind.attrs(d, kind.normal()).unwrap_or_default(); + let base = match kind { + Kind::Char => char_attrs(&with_attrs(&CharStyle::default(), &normal, &kind.cmd("edit"))?), + Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), &normal, &kind.cmd("edit"))?), + }; + each_text_mut(d, &mut |t| { let mut changed = false; match kind { Kind::Char => { for r in &mut t.runs { if r.style.style_name == target { - r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new), new); + r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new, &base), new); changed = true; } } @@ -345,7 +399,7 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Valu Kind::Para => { for pa in t.para_styles_mut() { if pa.style_name == target { - *pa = restyle(pa, para_attrs, old, new); + *pa = restyle(pa, para_attrs, old, new, &base); changed = true; } } @@ -354,7 +408,8 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Valu if changed { refresh_bounds(t); } - } + Ok(()) + }) } /// The selected text's attributes: the first selected character for a nonempty range, @@ -394,6 +449,11 @@ pub fn target_style_attrs(s: &Session, target: &Value, para: bool) -> Option<Map selection_attrs(s, target, if para { Kind::Para } else { Kind::Char }).ok().flatten() } +/// The attributes a new character or paragraph style receives when no text is selected. +pub fn default_new_style_attrs(s: &Session, para: bool) -> Map<String, Value> { + new_style_attrs(s, if para { Kind::Para } else { Kind::Char }) +} + /// Whether the document has a character (`para`: paragraph) style `name`, and its attributes. pub(crate) fn style_attrs(d: &Document, para: bool, name: &str) -> Option<Map<String, Value>> { if para { Kind::Para } else { Kind::Char }.attrs(d, name) @@ -567,13 +627,16 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> { fn redefine_to(s: &mut Session, kind: Kind, name: &str, new_attrs: Map<String, Value>, verb: &str) -> Result<Value> { let d = &s.doc()?.doc; let old = kind.attrs(d, name).ok_or_else(|| bad(&kind.cmd(verb), format!("no style `{name}`")))?; + if new_attrs == old { + return ok(); + } let name = name.to_string(); s.edit_named("Redefine {name}", &name, name == kind.normal(), |d, _| { match kind.defs_mut(d).iter_mut().find(|s| s.name == name) { Some(def) => def.attrs = new_attrs.clone(), None => kind.defs_mut(d).push(TextStyleDef { name: name.clone(), attrs: new_attrs.clone() }), } - update_users(d, kind, &name, &old, &new_attrs); + update_users(d, kind, &name, &old, &new_attrs)?; Ok(()) })?; ok() @@ -591,6 +654,50 @@ fn set_attrs(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> { redefine_to(s, kind, &name, attrs, "setAttrs") } +fn edit_style(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> { + let c = kind.cmd("edit"); + let name = name_param(p, kind, "edit")?.to_string(); + let to = str_param(p, "to").ok_or_else(|| bad(&c, "missing `to`"))?.trim().to_string(); + let attrs = attrs_param(p, kind, "edit")?.ok_or_else(|| bad(&c, "missing `attrs`"))?; + let d = &s.doc()?.doc; + let old = kind.attrs(d, &name).ok_or_else(|| bad(&c, format!("no style `{name}`")))?; + if name == kind.normal() { + return Err(bad(&c, format!("`{name}` can't be edited this way"))); + } + if to.is_empty() { + return Err(bad(&c, "give the style a name")); + } + if to != name && kind.attrs(d, &to).is_some() { + return Err(bad(&c, format!("a style named `{to}` already exists"))); + } + if to == name && attrs == old { + return ok(); + } + s.edit(if kind == Kind::Char { "Character Style Options" } else { "Paragraph Style Options" }, |d, _| { + if let Some(def) = kind.defs_mut(d).iter_mut().find(|def| def.name == name) { + def.name = to.clone(); + def.attrs = attrs.clone(); + } + update_users(d, kind, &name, &old, &attrs)?; + if to != name { + each_text_mut(d, &mut |t| { + let fix = |style_name: &mut Option<String>| { + if style_name.as_deref() == Some(name.as_str()) { + *style_name = Some(to.clone()); + } + }; + match kind { + Kind::Char => t.runs.iter_mut().for_each(|r| fix(&mut r.style.style_name)), + Kind::Para => t.para_styles_mut().for_each(|pa| fix(&mut pa.style_name)), + } + Ok(()) + })?; + } + Ok(()) + })?; + ok() +} + fn duplicate(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> { let name = name_param(p, kind, "duplicate")?.to_string(); let d = &s.doc()?.doc; @@ -619,8 +726,7 @@ fn rename(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> { if let Some(def) = kind.defs_mut(d).iter_mut().find(|s| s.name == name) { def.name = to.clone(); } - for id in all_text(d) { - let Some(t) = text_mut(d, id) else { continue }; + each_text_mut(d, &mut |t| { let fix = |n: &mut Option<String>| { if n.as_deref() == Some(name.as_str()) { *n = Some(to.clone()); @@ -630,7 +736,8 @@ fn rename(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> { Kind::Char => t.runs.iter_mut().for_each(|r| fix(&mut r.style.style_name)), Kind::Para => t.para_styles_mut().for_each(|pa| fix(&mut pa.style_name)), } - } + Ok(()) + })?; Ok(()) })?; ok() @@ -654,8 +761,7 @@ fn delete(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> { } s.edit(if names.len() > 1 { "Delete Styles" } else { "Delete Style" }, |d, _| { kind.defs_mut(d).retain(|s| !names.contains(&s.name)); - for id in all_text(d) { - let Some(t) = text_mut(d, id) else { continue }; + each_text_mut(d, &mut |t| { let fix = |n: &mut Option<String>| { if n.as_ref().is_some_and(|n| names.contains(n)) { *n = None; @@ -665,7 +771,8 @@ fn delete(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> { Kind::Char => t.runs.iter_mut().for_each(|r| fix(&mut r.style.style_name)), Kind::Para => t.para_styles_mut().for_each(|pa| fix(&mut pa.style_name)), } - } + Ok(()) + })?; Ok(()) })?; ok() diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index 670e3bbb7a..46b52346de 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -15,6 +15,233 @@ fn runs(s: &Session, id: u64) -> Vec<vectorcraft_doc::TextRun> { } } +fn embedded_style(s: &Session, container: &str) -> (Option<String>, f64, Option<String>) { + let d = &s.doc().unwrap().doc; + let brushes = vectorcraft_brush::library(d); + let roots: Vec<&Node> = match container { + "symbol" => d.symbols.iter().map(|s| &*s.art).collect(), + "pattern" => d.patterns.iter().flat_map(|p| p.art.iter().map(|a| &**a)).collect(), + "graph" => d.graph_designs.iter().map(|g| &*g.art).collect(), + "brush" => brushes.iter().flat_map(|b| b.art()).collect(), + _ => panic!("unknown container"), + }; + let mut found = None; + for root in roots { + vectorcraft_doc::swatches::walk_with_masks(root, &mut |n| { + if let NodeKind::Text(t) = &n.kind { + found = Some((t.runs[0].style.style_name.clone(), t.runs[0].style.size, t.para.style_name.clone())); + } + }); + } + found.unwrap() +} + +fn embedded_style_session(kind: &str, container: &str) -> Session { + let (mut s, id) = session_with_text("Styled"); + s.execute(&format!("{kind}Style.new"), &json!({"name": "Body", "attrs": if kind == "char" { json!({"size": 24}) } else { json!({}) }})).unwrap(); + s.execute(&format!("{kind}Style.apply"), &json!({"name": "Body", "id": id})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + match container { + "symbol" => { + let symbol = s.execute("symbol.new", &json!({"name": "Mark"})).unwrap(); + s.execute("edit.clear", &json!({"ids": [symbol["id"]]})).unwrap(); + } + "pattern" => { + s.execute("object.pattern.make", &json!({"edit": false})).unwrap(); + if s.doc().unwrap().doc.node(NodeId(id)).is_some() { + s.execute("edit.clear", &json!({"ids": [id]})).unwrap(); + } + } + "graph" => { + s.execute("graph.design", &json!({"new": "Bar"})).unwrap(); + s.execute("edit.clear", &json!({"ids": [id]})).unwrap(); + } + "brush" => { + s.execute("brush.new", &json!({"type": "art", "name": "Lettering"})).unwrap(); + s.execute("edit.clear", &json!({"ids": [id]})).unwrap(); + } + _ => panic!("unknown container"), + } + s +} + +#[test] +fn character_style_options_update_embedded_art() { + for container in ["symbol", "pattern", "graph", "brush"] { + let mut s = embedded_style_session("char", container); + assert_eq!(embedded_style(&s, container).0.as_deref(), Some("Body"), "{container}"); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("charStyle.edit", &json!({"name": "Body", "to": "Heading", "attrs": {"size": 18}})).unwrap(); + assert_eq!(embedded_style(&s, container).0.as_deref(), Some("Heading"), "{container}"); + assert_eq!(embedded_style(&s, container).1, 18.0, "{container}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{container}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before, "{container}"); + s.execute("edit.redo", &json!({})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("charStyle.delete", &json!({"name": "Heading"})).unwrap(); + assert_eq!(embedded_style(&s, container).0, None, "{container}"); + assert_eq!(embedded_style(&s, container).1, 18.0, "{container}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{container}"); + } +} + +#[test] +fn character_style_edit_survives_canceling_pattern_edit() { + let mut s = embedded_style_session("char", "pattern"); + let name = s.doc().unwrap().doc.patterns[0].name.clone(); + s.execute("object.pattern.edit", &json!({"name": name})).unwrap(); + s.execute("charStyle.edit", &json!({"name": "Body", "to": "Heading", "attrs": {"size": 18}})).unwrap(); + s.execute("object.pattern.cancel", &json!({})).unwrap(); + + assert_eq!(embedded_style(&s, "pattern").0.as_deref(), Some("Heading")); + assert_eq!(embedded_style(&s, "pattern").1, 18.0); +} + +#[test] +fn paragraph_style_rename_updates_symbol_art() { + let mut s = embedded_style_session("para", "symbol"); + assert_eq!(embedded_style(&s, "symbol").2.as_deref(), Some("Body")); + s.execute("paraStyle.rename", &json!({"name": "Body", "to": "Heading"})).unwrap(); + assert_eq!(embedded_style(&s, "symbol").2.as_deref(), Some("Heading")); +} + +#[test] +fn character_style_options_keep_text_free_layer_shared() { + let (mut s, id) = session_with_text("Styled"); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + let empty_id = s.execute("layer.new", &json!({"name": "Empty"})).unwrap()["id"].as_u64().unwrap(); + let before = s.doc().unwrap().doc.layers.iter().find(|layer| layer.id == NodeId(empty_id)).unwrap().clone(); + + s.execute("charStyle.edit", &json!({"name": "Body", "to": "Heading", "attrs": {"size": 18}})).unwrap(); + + let d = &s.doc().unwrap().doc; + let after = d.layers.iter().find(|layer| layer.id == NodeId(empty_id)).unwrap(); + assert!(std::sync::Arc::ptr_eq(&before, after)); + assert_eq!(runs(&s, id)[0].style.style_name.as_deref(), Some("Heading")); + assert_eq!(runs(&s, id)[0].style.size, 18.0); +} + +#[test] +fn unchanged_style_options_keep_undo_and_redo_with_and_without_preview() { + for preview in [false, true] { + let (mut s, _) = session_with_text("Text"); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 18, "leading": null}})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Other", "attrs": {}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let redo = s.doc().unwrap().history.redo.len(); + assert!(redo > 0); + let params = json!({"name": "Body", "to": " Body ", "attrs": {"size": 18.0, "leading": null}}); + if preview { + s.begin_interaction("Character Style Options").unwrap(); + s.preview("charStyle.edit", ¶ms).unwrap(); + s.commit_interaction().unwrap(); + } else { + s.execute("charStyle.edit", ¶ms).unwrap(); + } + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "preview={preview}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "preview={preview}"); + assert_eq!(s.doc().unwrap().history.redo.len(), redo, "preview={preview}"); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.char_styles.iter().any(|style| style.name == "Other")); + } +} + +#[test] +fn unchanged_style_attributes_keep_undo_and_redo_for_both_kinds() { + for (command, para) in [("charStyle", false), ("paraStyle", true)] { + let (mut s, _) = session_with_text("Text"); + let attrs = if para { json!({"space_before": 18}) } else { json!({"size": 18}) }; + s.execute(&format!("{command}.new"), &json!({"name": "Body", "attrs": attrs})).unwrap(); + s.execute(&format!("{command}.new"), &json!({"name": "Other", "attrs": {}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let redo = s.doc().unwrap().history.redo.len(); + assert!(redo > 0); + let attrs = if para { json!({"space_before": 18.0}) } else { json!({"size": 18.0}) }; + s.execute(&format!("{command}.setAttrs"), &json!({"name": "Body", "attrs": attrs})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{command}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{command}"); + assert_eq!(s.doc().unwrap().history.redo.len(), redo, "{command}"); + } +} + +#[test] +fn character_style_options_edit_applies_to_users_and_is_one_saved_undo_step() { + let (mut s, id) = session_with_text("First second"); + s.execute("charStyle.new", &json!({"name":"Body", "attrs":{"size":24.0,"tracking":20.0,"baseline_shift":3.0}})).unwrap(); + s.execute("charStyle.apply", &json!({"name":"Body", "id":id, "start":0, "end":5})).unwrap(); + s.execute("charStyle.apply", &json!({"name":"Body", "id":id, "start":6, "end":12})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id":id,"start":6,"end":12,"size":31.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("charStyle.edit", &json!({"name":"Body","to":"Text","attrs":{"size":18.0,"tracking":40.0,"baseline_shift":3.0}})).unwrap(); + let changed = s.doc().unwrap().doc.clone(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!( + runs(&s, id).iter().map(|r| (r.style.style_name.as_deref(), r.style.size, r.style.tracking)).collect::<Vec<_>>(), + [(Some("Text"), 18.0, 40.0), (None, 12.0, 0.0), (Some("Text"), 31.0, 40.0)] + ); + let future = s.execute("text.create", &json!({"x":20,"y":90,"text":""})).unwrap()["id"].as_u64().unwrap(); + s.execute("charStyle.apply", &json!({"name":"Text","id":future})).unwrap(); + s.execute("text.editRange", &json!({"id":future,"start":0,"end":0,"insert":"Later"})).unwrap(); + assert_eq!((runs(&s, future)[0].style.size, runs(&s, future)[0].style.tracking), (18.0, 40.0)); + let saved = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert_eq!( + saved.char_styles.iter().find(|d| d.name == "Text").unwrap().attrs, + s.doc().unwrap().doc.char_styles.iter().find(|d| d.name == "Text").unwrap().attrs + ); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, changed); +} + +#[test] +fn editing_character_style_clears_removed_size_without_losing_local_override() { + let (mut s, id) = session_with_text("One two"); + s.execute("charStyle.setAttrs", &json!({"name": NORMAL_CHAR, "attrs": {"size": 15.0}})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 7, "size": 31.0})).unwrap(); + s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {}})).unwrap(); + let r = runs(&s, id); + assert_eq!((r[0].style.size, r[1].style.size), (15.0, 31.0)); +} + +#[test] +fn replacing_character_style_attrs_clears_removed_size() { + let (mut s, id) = session_with_text("Text"); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {}})).unwrap(); + assert_eq!(runs(&s, id)[0].style.size, 12.0); +} + +#[test] +fn character_style_options_edit_validates_names_and_allows_case_changes() { + let (mut s, _) = session_with_text("Text"); + s.execute("charStyle.new", &json!({"name":"Body","attrs":{"size":24.0}})).unwrap(); + s.execute("charStyle.new", &json!({"name":"Other","attrs":{}})).unwrap(); + for (name, to, message) in + [(super::NORMAL_CHAR, "New", "can't be edited this way"), ("Body", " ", "give the style a name"), ("Body", "Other", "already exists")] + { + let error = s.execute("charStyle.edit", &json!({"name":name,"to":to,"attrs":{}})).unwrap_err().to_string(); + assert!(error.contains(message), "{error}"); + } + s.execute("charStyle.edit", &json!({"name":"Body","to":"body","attrs":{"size":18.0}})).unwrap(); + s.execute("charStyle.edit", &json!({"name":"body","to":" body ","attrs":{"size":20.0}})).unwrap(); + assert_eq!(s.doc().unwrap().doc.char_styles.iter().find(|style| style.name == "body").unwrap().attrs["size"], json!(20.0)); +} + #[test] fn char_style_new_apply_range_redefine_keeps_overrides() { let (mut s, id) = session_with_text("Hello world"); @@ -293,10 +520,10 @@ fn auto_leading_redefine_keeps_overrides_and_history() { s.execute("text.setStyle", &json!({"ids": [linked], "leading": "auto"})).unwrap(); s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"leading": 28}})).unwrap(); assert_eq!(ids.map(|id| runs(&s, id)[0].style.leading), [Some(28.0), None, Some(42.0)]); - // Omitting leading replaces the definition without resetting the text's leading. + // Omitting leading returns linked text to Auto and keeps local overrides. s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"tracking": 20}})).unwrap(); assert!(!s.doc().unwrap().doc.char_styles[0].attrs.contains_key("leading")); - assert_eq!(ids.map(|id| runs(&s, id)[0].style.leading), [Some(28.0), None, Some(42.0)]); + assert_eq!(ids.map(|id| runs(&s, id)[0].style.leading), [None, None, Some(42.0)]); } } @@ -308,7 +535,7 @@ fn settable<T: DeserializeOwned>() -> std::collections::BTreeSet<String> { /// New and Redefine capture every paragraph attribute. A paragraph style redefined from a /// paragraph at the defaults gives its paragraphs the defaults back where they had the old /// definition's values, and `setAttrs` with a default value does too; local overrides, and -/// attributes `setAttrs` leaves out, stay. +/// attributes `setAttrs` leaves out return to the base value. #[test] fn para_style_redefined_to_the_defaults_updates_its_paragraphs() { use vectorcraft_doc::{Composer, HyphenationOptions}; @@ -335,11 +562,11 @@ fn para_style_redefined_to_the_defaults_updates_its_paragraphs() { assert_eq!(defined(&s, 0), settable::<ParaStyle>(), "Redefine captures every attribute"); s.execute("paraStyle.new", &json!({"name": "Copy", "id": local})).unwrap(); assert_eq!(defined(&s, 1), settable::<ParaStyle>(), "New captures every attribute"); - // Style options: a default value reaches the users too; an attribute left out stays as it is. + // Style options: a default value reaches users, and an attribute left out returns to base. s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"hyphenation": {"hyphen_limit": 3}, "composer": "singleLine"}})).unwrap(); assert_eq!((limits(&s), composers(&s)), ([3, 3, 4], [Composer::SingleLine; 3])); s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"composer": "everyLine"}})).unwrap(); - assert_eq!((limits(&s), composers(&s)), ([3, 3, 4], [Composer::EveryLine; 3])); + assert_eq!((limits(&s), composers(&s)), ([0, 0, 4], [Composer::EveryLine; 3])); assert_eq!(Value::Object(s.doc().unwrap().doc.para_styles[0].attrs.clone()), json!({"composer": "everyLine"})); } @@ -368,7 +595,7 @@ fn char_style_redefined_to_the_defaults_updates_its_text() { s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"kerning": 10, "charAlign": "emBoxTop"}})).unwrap(); assert_eq!((kerning(&s), aligns(&s)), ([Some(10.0), Some(10.0), Some(60.0)], [CharAlign::EmBoxTop; 3])); s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"charAlign": "romanBaseline"}})).unwrap(); - assert_eq!((kerning(&s), aligns(&s)), ([Some(10.0), Some(10.0), Some(60.0)], [CharAlign::RomanBaseline; 3])); + assert_eq!((kerning(&s), aligns(&s)), ([None, None, Some(60.0)], [CharAlign::RomanBaseline; 3])); assert_eq!(Value::Object(s.doc().unwrap().doc.char_styles[0].attrs.clone()), json!({"charAlign": "romanBaseline"})); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index b2a42af49b..a4eac70418 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -14,6 +14,7 @@ pub mod blend_options; mod brush_art_options; pub mod brush_delete; pub mod brush_options; +pub mod char_style_options; pub mod color_balance; pub mod color_guide_options; mod color_picker; @@ -306,6 +307,7 @@ registry! { GradientStop: ["gradientStop"] => gradient_stop::SPEC, ColorPicker: [color_picker::KIND] => color_picker::SPEC, GraphicStyleOptions: [graphic_style_options::KIND] => graphic_style_options::SPEC, + CharStyleOptions: [char_style_options::KIND] => char_style_options::SPEC, NewTextStyle: [new_text_style::KIND] => new_text_style::SPEC, EffectExists: [effect::EXISTS] => effect::EXISTS_SPEC, ColorGuideOptions: [color_guide_options::KIND] => color_guide_options::SPEC, diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs new file mode 100644 index 0000000000..848151ac54 --- /dev/null +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -0,0 +1,548 @@ +//! Character Style Options fields shared by editing and creating a character style. + +use serde_json::{Map, Value, json}; + +use super::{DialogSpec, form}; +use crate::VectorcraftApp; +use crate::state::Dialog; + +pub const KIND: &str = "charStyleOptions"; +const BASIC: &[&str] = &[ + "font_family", + "font_style", + "size", + "leading", + "kerning", + "tracking", + "all_caps", + "small_caps", + "position", + "underline", + "strikethrough", + "charAlign", +]; +const NUMBERS: &[&str] = &["size", "leading", "kerning", "tracking"]; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Character Style Options").into(), + body, + confirm, + preview: true, + inputs: |_| { + &[ + "name", + "font_family", + "font_style", + "size", + "leading", + "kerning", + "tracking", + "case", + "position", + "underline", + "strikethrough", + "charAlign", + "section", + ] + }, + min_width: 650.0, + ..DialogSpec::FORM +}; + +pub fn open(app: &mut VectorcraftApp, name: &str) -> Result<Value, String> { + crate::panels::character::end_typing(app); + let doc = &app.session.active().ok_or("no document open")?.doc; + let def = doc.char_styles.iter().find(|s| s.name == name).ok_or_else(|| format!("no character style `{name}`"))?; + let mut fields = fields_from_attrs(&def.attrs); + fields.insert("name".into(), json!(name)); + fields.insert("__style".into(), json!(name)); + fields.insert("__attrs".into(), json!(def.attrs)); + fields.insert("__smallCapsSize".into(), json!(doc.setup.small_caps_size)); + fields.insert("__superscript".into(), json!(doc.setup.superscript)); + fields.insert("__subscript".into(), json!(doc.setup.subscript)); + fields.insert("section".into(), json!("general")); + fields.insert("preview".into(), json!(true)); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + Ok(json!({"dialog": KIND})) +} + +pub(crate) fn fields_from_attrs(attrs: &Map<String, Value>) -> Map<String, Value> { + let mut fields = Map::new(); + for key in ["font_family", "font_style", "size", "leading", "kerning", "tracking", "underline", "strikethrough", "charAlign"] { + let value = attrs.get(key).cloned().unwrap_or(Value::Null); + let shown = if ["underline", "strikethrough"].contains(&key) { + value + } else if value.is_null() { + if attrs.contains_key(key) && ["leading", "kerning"].contains(&key) { json!("Auto") } else { json!("") } + } else { + value + }; + fields.insert(key.into(), shown); + } + fields.insert("case".into(), case_from_attrs(attrs).map_or(Value::Null, Value::from)); + fields.insert("position".into(), attrs.get("position").and_then(|v| v.get("kind")).cloned().unwrap_or(Value::Null)); + fields +} + +fn case_from_attrs(attrs: &Map<String, Value>) -> Option<&'static str> { + if attrs.get("all_caps") == Some(&json!(true)) { + Some("allCaps") + } else if attrs.get("small_caps").is_some_and(|v| !v.is_null()) { + Some("smallCaps") + } else if attrs.contains_key("all_caps") || attrs.contains_key("small_caps") { + Some("normal") + } else { + None + } +} + +fn optional_number(d: &Dialog, key: &str) -> Result<Option<Value>, String> { + let label = match key { + "size" => tl!("Size"), + "leading" => tl!("Leading"), + "kerning" => tl!("Kerning"), + "tracking" => tl!("Tracking"), + _ => return Err("unknown character style number field".into()), + }; + match d.fields.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(s)) if s.trim().is_empty() => Ok(None), + Some(Value::String(s)) if s.trim().eq_ignore_ascii_case("auto") && ["leading", "kerning"].contains(&key) => Ok(Some(Value::Null)), + Some(v) => { + let n = v + .as_f64() + .or_else(|| v.as_str().and_then(|s| s.trim().parse::<f64>().ok())) + .filter(|n| n.is_finite()) + .ok_or_else(|| format!("{label} must be a number"))?; + if ["size", "leading"].contains(&key) && n < 0.1 { + return Err(format!("{label} must be a number of at least 0.1")); + } + Ok(Some(json!(n))) + } + } +} + +pub(crate) fn edited_attrs(d: &Dialog) -> Result<Map<String, Value>, String> { + let original = d.fields.get("__attrs").and_then(Value::as_object).cloned().unwrap_or_default(); + let original_fields = fields_from_attrs(&original); + let reset = d.bool("__resetBasic"); + let mut attrs = original.clone(); + for key in BASIC { + attrs.remove(*key); + } + for key in ["font_family", "font_style"] { + if let Some(v) = d.fields.get(key).and_then(Value::as_str).filter(|v| !v.trim().is_empty()) { + attrs.insert(key.into(), json!(v.trim())); + } + } + if reset || ["font_family", "font_style"].iter().any(|key| d.fields.get(*key) != original_fields.get(*key)) { + attrs.remove("font_version"); + attrs.remove("fontAxes"); + } + for key in NUMBERS { + if let Some(v) = optional_number(d, key)? { + attrs.insert((*key).into(), v); + } + } + for key in ["underline", "strikethrough"] { + if let Some(v) = d.fields.get(key).and_then(Value::as_bool) { + attrs.insert(key.into(), json!(v)); + } + } + if reset || d.fields.get("case").and_then(Value::as_str) != case_from_attrs(&original) { + match d.fields.get("case").and_then(Value::as_str) { + Some("allCaps") => { + attrs.insert("all_caps".into(), json!(true)); + attrs.insert("small_caps".into(), Value::Null); + } + Some("smallCaps") => { + attrs.insert("all_caps".into(), json!(false)); + attrs.insert( + "small_caps".into(), + original + .get("small_caps") + .filter(|v| v.is_number()) + .cloned() + .unwrap_or_else(|| d.fields.get("__smallCapsSize").cloned().unwrap_or_else(|| json!(70.0))), + ); + } + Some("normal") => { + attrs.insert("all_caps".into(), json!(false)); + attrs.insert("small_caps".into(), Value::Null); + } + _ => {} + } + } + if let Some(position) = d.fields.get("position").and_then(Value::as_str).filter(|v| !v.is_empty()) { + let value = if position == "normal" { + json!({"kind": "normal"}) + } else { + original.get("position").filter(|v| v.get("kind").and_then(Value::as_str) == Some(position)).cloned().unwrap_or_else(|| { + let metrics = d.fields.get(if position == "superscript" { "__superscript" } else { "__subscript" }); + json!({"kind": position, "size": metrics.and_then(|m| m.get("size")).cloned().unwrap_or(json!(58.3)), + "position": metrics.and_then(|m| m.get("position")).cloned().unwrap_or(json!(33.3))}) + }) + }; + attrs.insert("position".into(), value); + } + if let Some(align) = d.fields.get("charAlign").and_then(Value::as_str).filter(|v| !v.is_empty()) { + attrs.insert("charAlign".into(), json!(align)); + } + if !reset { + for key in BASIC { + let field = if ["all_caps", "small_caps"].contains(key) { "case" } else { key }; + if d.fields.get(field) == original_fields.get(field) { + attrs.remove(*key); + if let Some(value) = original.get(*key) { + attrs.insert((*key).into(), value.clone()); + } + } + } + } + Ok(attrs) +} + +pub(crate) fn reset_basic(d: &mut Dialog) { + d.fields.insert("__resetBasic".into(), json!(true)); + for key in ["font_family", "font_style", "size", "leading", "kerning", "tracking", "case", "position", "underline", "strikethrough", "charAlign"] + { + d.fields.insert( + key.into(), + if ["font_family", "font_style", "size", "leading", "kerning", "tracking"].contains(&key) { json!("") } else { Value::Null }, + ); + } +} + +pub fn reset_panel(app: &mut VectorcraftApp) -> Result<Value, String> { + let d = app.ui.dialog.as_mut().ok_or("no dialog open")?; + let character_new = d.kind == super::new_text_style::KIND && !d.bool("__para"); + if (d.kind != KIND && !character_new) || d.str("section") != "basic" { + return Err("the open dialog has no Reset".into()); + } + reset_basic(d); + Ok(json!({"dialog": d.kind})) +} + +fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, options: &[(&str, &str)]) { + let selected = d.fields.get(key).and_then(Value::as_str).unwrap_or("").to_string(); + let shown = options.iter().find(|(value, _)| *value == selected).map_or("", |(_, label)| *label); + let labels: Vec<&str> = std::iter::once(" ").chain(options.iter().map(|(_, label)| *label)).collect(); + if let Some(i) = crate::widgets::dropdown(ui, (KIND, key), shown, &labels, 190.0) { + d.fields.insert(key.into(), if i == 0 { Value::Null } else { options.get(i - 1).map_or(Value::Null, |(value, _)| json!(value)) }); + } +} + +pub(crate) fn basic_body(ui: &mut egui::Ui, d: &mut Dialog) { + egui::Grid::new("character-style-basic").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { + for (key, caption) in [ + ("font_family", tl!("Font Family:")), + ("font_style", tl!("Font Style:")), + ("size", tl!("Size")), + ("leading", tl!("Leading")), + ("kerning", tl!("Kerning")), + ("tracking", tl!("Tracking")), + ] { + ui.label(caption); + if d.fields.get(key).is_some_and(Value::is_null) { + d.fields.insert(key.into(), json!("")); + } + form::text(ui, d, key, 190.0); + ui.end_row(); + } + ui.label(tl!("Case")); + choice(ui, d, "case", &[("normal", tl!("Normal")), ("allCaps", tl!("All Caps")), ("smallCaps", tl!("Small Caps"))]); + ui.end_row(); + ui.label(tl!("Position")); + choice(ui, d, "position", &[("normal", tl!("Normal")), ("superscript", tl!("Superscript")), ("subscript", tl!("Subscript"))]); + ui.end_row(); + for (key, caption) in [("underline", tl!("Underline")), ("strikethrough", tl!("Strikethrough"))] { + ui.label(""); + let value = d.fields.get(key).and_then(Value::as_bool); + if crate::widgets::check3(ui, caption, value, true) { + d.fields.insert( + key.into(), + match value { + None => json!(true), + Some(true) => json!(false), + Some(false) => Value::Null, + }, + ); + } + ui.end_row(); + } + ui.label(tl!("Standard Vertical Roman Alignment")); + choice( + ui, + d, + "charAlign", + &[ + ("romanBaseline", tl!("Roman Baseline")), + ("emBoxTop", tl!("Em Box Top/Right")), + ("emBoxCenter", tl!("Em Box Center")), + ("emBoxBottom", tl!("Em Box Bottom/Left")), + ("icfTop", tl!("ICF Top/Right")), + ("icfBottom", tl!("ICF Bottom/Left")), + ], + ); + ui.end_row(); + }); +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + ui.horizontal(|ui| { + ui.vertical(|ui| { + for (id, label) in [("general", tl!("General")), ("basic", tl!("Basic Character Formats"))] { + if ui.selectable_label(d.str("section") == id, label).clicked() { + d.fields.insert("section".into(), json!(id)); + } + } + }); + ui.separator(); + ui.vertical(|ui| { + if d.str("section") == "basic" { + basic_body(ui, d); + } else { + ui.horizontal(|ui| { + ui.label(tl!("Style Name:")); + form::text(ui, d, "name", 190.0); + }); + ui.separator(); + if let Ok(attrs) = edited_attrs(d) { + for (key, value) in attrs { + ui.label(format!("{}: {}", super::humanize(&key), value)); + } + } + } + }); + }); + ui.add_enabled_ui(d.str("section") == "basic", |ui| { + if ui.button(tl!("Reset Panel")).clicked() { + reset_basic(d); + } + }); + match edited_attrs(d) { + Ok(attrs) => { + let params = json!({"name": d.str("__style"), "to": d.str("name"), "attrs": attrs}); + form::preview(app, ui, d, tl!("Character Style Options"), "charStyle.edit", params); + } + Err(why) => { + ui.add_space(6.0); + ui.colored_label(crate::theme::Tokens::get(ui.ctx()).error, crate::i18n::message(crate::i18n::current(), &why)); + } + } + false +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { + let attrs = edited_attrs(d)?; + form::commit_preview(app, "charStyle.edit", json!({"name": d.str("__style"), "to": d.str("name"), "attrs": attrs})) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app + } + + fn frame(app: &mut VectorcraftApp) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + } + + #[test] + fn unchanged_basic_fields_preserve_original_keys() { + for attrs in [ + json!({"all_caps": false}), + json!({"all_caps": true}), + json!({"small_caps": 70.0}), + json!({"font_family": "Example", "font_style": "Regular", "font_version": "1", "size": 24, + "leading": null, "kerning": null, "tracking": 3, "underline": null, + "strikethrough": false, "position": {"kind": "normal", "size": 80}, "charAlign": null}), + ] { + let original = attrs.as_object().unwrap().clone(); + let mut fields = fields_from_attrs(&original); + fields.insert("__attrs".into(), attrs); + let d = Dialog { kind: KIND.into(), fields }; + assert_eq!(edited_attrs(&d).unwrap(), original); + } + let original = json!({"all_caps": false}).as_object().unwrap().clone(); + let mut fields = fields_from_attrs(&original); + fields.insert("__attrs".into(), json!(original)); + fields.insert("case".into(), json!("allCaps")); + let d = Dialog { kind: KIND.into(), fields }; + assert_eq!(edited_attrs(&d).unwrap(), json!({"all_caps": true, "small_caps": null}).as_object().unwrap().clone()); + } + + #[test] + fn unchanged_options_keep_local_small_caps_and_history() { + for preview in [false, true] { + let mut app = app(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {"all_caps": false}})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "Text"})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name": "Body", "id": id})).unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 4, "smallCaps": true})).unwrap(); + let state = app.session.doc().unwrap(); + let before = state.doc.clone(); + let history = (state.history.undo.len(), state.history.redo.len()); + open(&mut app, "Body").unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(preview)); + if preview { + frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before); + } + super::super::confirm(&mut app).unwrap(); + let state = app.session.doc().unwrap(); + assert_eq!(state.doc, before); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + assert_eq!( + state.doc.node(vectorcraft_doc::NodeId(id)).and_then(|node| match &node.kind { + vectorcraft_doc::NodeKind::Text(text) => text.runs.first().map(|run| run.style.small_caps), + _ => None, + }), + Some(Some(state.doc.setup.small_caps_size)) + ); + } + } + + #[test] + fn options_preview_cancel_reset_and_commit_keep_sparse_definition() { + let mut app = app(); + app.run("charStyle.new", json!({"name":"Body","attrs":{"size":24.0,"baseline_shift":3.0}})).unwrap(); + let id = app.run("text.create", json!({"x":10,"y":40,"text":"Text"})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name":"Body","id":id})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + open(&mut app, "Body").unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().bool("preview")); + assert!(app.run("ui.charStyleOptions.resetPanel", json!({})).is_err()); + assert!(app.ui.dialog.as_ref().unwrap().fields["underline"].is_null()); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("kerning"), ""); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("name".into(), json!("Revised")); + d.fields.insert("size".into(), json!(18)); + } + frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc.char_styles[0].name, "Revised"); + super::super::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + open(&mut app, "Body").unwrap(); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("section".into(), json!("basic")); + } + app.run("ui.charStyleOptions.resetPanel", json!({})).unwrap(); + { + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(edited_attrs(d).unwrap(), serde_json::from_value(json!({"baseline_shift":3.0})).unwrap()); + d.fields.insert("name".into(), json!("Revised")); + } + super::super::confirm(&mut app).unwrap(); + let state = app.session.doc().unwrap(); + assert_eq!(state.history.undo.len(), undo + 1); + assert_eq!(state.doc.char_styles[0].name, "Revised"); + assert_eq!(state.doc.char_styles[0].attrs, serde_json::from_value(json!({"baseline_shift":3.0})).unwrap()); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.char_styles[0].name, "Revised"); + app.run("select.set", json!({"ids":[id]})).unwrap(); + app.run("ui.newCharStyle", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("size"), "12.0"); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("size".into(), json!(36.0)); + d.fields.insert("name".into(), json!("Future")); + } + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.char_styles.iter().find(|def| def.name == "Future").unwrap().attrs["size"], json!(36.0)); + } + + #[test] + fn invalid_numbers_name_the_visible_field() { + let mut d = Dialog::new(KIND, json!({})); + for (key, label) in [("size", "Size"), ("leading", "Leading"), ("kerning", "Kerning"), ("tracking", "Tracking")] { + d.fields.insert(key.into(), json!("not a number")); + assert_eq!(optional_number(&d, key).unwrap_err(), format!("{label} must be a number")); + } + } + + #[test] + fn size_and_leading_below_minimum_do_not_preview_or_commit() { + for (key, value) in [("size", json!(0)), ("size", json!(-2)), ("leading", json!(0.09)), ("leading", json!(-1))] { + let mut app = app(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {"size": 24.0, "leading": 28.0}})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "Text"})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name": "Body", "id": id})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + open(&mut app, "Body").unwrap(); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("name".into(), json!("Revised")); + d.fields.insert(key.into(), value); + assert!(edited_attrs(d).unwrap_err().contains("at least 0.1")); + } + frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before, "{key} preview"); + assert!(super::super::confirm(&mut app).is_err(), "{key} confirm"); + assert_eq!(app.session.doc().unwrap().doc, before, "{key} confirm"); + } + } + + #[test] + fn invalid_number_keeps_last_valid_preview() { + let mut app = app(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "Text"})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name": "Body", "id": id})).unwrap(); + open(&mut app, "Body").unwrap(); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("name".into(), json!("Revised")); + d.fields.insert("size".into(), json!(18)); + } + frame(&mut app); + let valid = app.session.doc().unwrap().doc.clone(); + assert_eq!(valid.char_styles[0].name, "Revised"); + assert_eq!(valid.char_styles[0].attrs["size"], json!(18.0)); + app.ui.dialog.as_mut().unwrap().fields.insert("size".into(), json!("invalid")); + frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc, valid); + } + + #[test] + fn script_positions_use_document_setup_in_existing_and_new_style_dialogs() { + let mut app = app(); + app.run( + "document.setup", + json!({"superscript": {"size": 67.0, "position": 22.0}, + "subscript": {"size": 72.0, "position": 18.0}}), + ) + .unwrap(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {}})).unwrap(); + open(&mut app, "Body").unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("position".into(), json!("superscript")); + assert_eq!( + edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap()["position"], + json!({"kind": "superscript", "size": 67.0, "position": 22.0}) + ); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.char_styles[0].attrs["position"], json!({"kind": "superscript", "size": 67.0, "position": 22.0})); + app.run("ui.newCharStyle", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("position".into(), json!("subscript")); + assert_eq!(edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap()["position"], json!({"kind": "subscript", "size": 72.0, "position": 18.0})); + super::super::confirm(&mut app).unwrap(); + assert_eq!( + app.session.doc().unwrap().doc.char_styles.last().unwrap().attrs["position"], + json!({"kind": "subscript", "size": 72.0, "position": 18.0}) + ); + } +} diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index f945332e64..16ec9568d5 100644 --- a/crates/ui-egui/src/dialogs/new_text_style.rs +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -31,14 +31,60 @@ pub fn open(app: &mut VectorcraftApp, para: bool, target: Value) -> Result<Value let d = &app.session.active().ok_or("no document open")?.doc; let name = vectorcraft_engine::cmd::textstyles::new_style_name(d, para); let mut target = target; - if let Some(attrs) = vectorcraft_engine::cmd::textstyles::target_style_attrs(&app.session, &target, para) { + let selected_attrs = vectorcraft_engine::cmd::textstyles::target_style_attrs(&app.session, &target, para); + if let Some(attrs) = selected_attrs.or_else(|| (!para).then(|| vectorcraft_engine::cmd::textstyles::default_new_style_attrs(&app.session, false))) + { target["attrs"] = Value::Object(attrs); } - app.ui.dialog = Some(Dialog::new(KIND, json!({ "name": name, "__para": para, "__target": target }))); + let mut fields = Dialog::new(KIND, json!({ "name": name, "__para": para, "__target": target })).fields; + if !para { + fields.insert("section".into(), json!("general")); + fields.insert("__smallCapsSize".into(), json!(d.setup.small_caps_size)); + fields.insert("__superscript".into(), json!(d.setup.superscript)); + fields.insert("__subscript".into(), json!(d.setup.subscript)); + let attrs = target.get("attrs").and_then(Value::as_object).cloned().unwrap_or_default(); + fields.extend(super::char_style_options::fields_from_attrs(&attrs)); + fields.insert("__attrs".into(), Value::Object(attrs)); + } + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); Ok(json!({ "dialog": KIND })) } fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + if !para(d) { + ui.horizontal(|ui| { + ui.vertical(|ui| { + for (id, title) in [("general", tl!("General")), ("basic", tl!("Basic Character Formats"))] { + if ui.selectable_label(d.str("section") == id, title).clicked() { + d.fields.insert("section".into(), json!(id)); + } + } + }); + ui.separator(); + if d.str("section") == "basic" { + super::char_style_options::basic_body(ui, d); + } else { + ui.vertical(|ui| { + grid(ui, |ui| { + label(ui, tl!("Style Name:")); + form::text(ui, d, "name", 190.0); + ui.end_row(); + }); + if let Ok(attrs) = super::char_style_options::edited_attrs(d) { + for (key, value) in attrs { + ui.label(format!("{}: {}", super::humanize(&key), value)); + } + } + }); + } + }); + ui.add_enabled_ui(d.str("section") == "basic", |ui| { + if ui.button(tl!("Reset Panel")).clicked() { + super::char_style_options::reset_basic(d); + } + }); + return false; + } grid(ui, |ui| { label(ui, tl!("Style Name:")); form::text(ui, d, "name", 190.0); @@ -52,6 +98,9 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { let mut params = d.fields.get("__target").filter(|t| t.is_object()).cloned().unwrap_or_else(|| json!({})); params["name"] = json!(d.str("name")); + if !para(d) { + params["attrs"] = Value::Object(super::char_style_options::edited_attrs(d)?); + } let r = app.run(if para(d) { "paraStyle.new" } else { "charStyle.new" }, params); if let Ok(v) = &r { app.ui.dialog = None; diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 442e051c03..87c2edac46 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5869,6 +5869,12 @@ anchor Points: Punts: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Color dels punts de la il·lustració + Basic Character Formats Formats bàsics de caràcters + Case Majúscules i minúscules + Kerning Interlletratge +@msg {label} must be a number {label} ha de ser un nombre +@msg {label} must be a number of at least 0.1 {label} ha de ser un nombre de com a mínim 0,1 +@msg no character style `{name}` No s'ha trobat l'estil de caràcter `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Bitò… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index aa88620f4d..3f9c07acd5 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5878,6 +5878,12 @@ anchor Points: Body: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Barva bodů podle kresby + Basic Character Formats Základní formáty znaků + Case Velikost písmen + Kerning Vyrovnání párů +@msg {label} must be a number {label} musí být číslo +@msg {label} must be a number of at least 0.1 {label} musí být číslo alespoň 0,1 +@msg no character style `{name}` styl znaků `{name}` neexistuje # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Dvoutón… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2d1e728453..f248421755 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5463,6 +5463,12 @@ anchor Points: Punkte: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Punktfarbe aus Grafik + Basic Character Formats Grundlegende Zeichenformate + Case Großschreibung + Kerning Unterschneidung +@msg {label} must be a number {label} muss eine Zahl sein +@msg {label} must be a number of at least 0.1 {label} muss eine Zahl von mindestens 0,1 sein +@msg no character style `{name}` Zeichenformat `{name}` nicht gefunden # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Duplex… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 16fe9435e1..eab0f70fa3 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5830,6 +5830,12 @@ anchor Points: Σημεία: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Χρώμα κουκκίδων από το γραφικό + Basic Character Formats Βασικές μορφές χαρακτήρων + Case Πεζά και κεφαλαία + Kerning Διαγραμμάτωση +@msg {label} must be a number Το {label} πρέπει να είναι αριθμός +@msg {label} must be a number of at least 0.1 Το {label} πρέπει να είναι αριθμός τουλάχιστον 0,1 +@msg no character style `{name}` Δεν βρέθηκε το στυλ χαρακτήρων `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Δίτονο… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index d4d2d20eb3..5b7d317406 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5821,6 +5821,12 @@ anchor Points: Puntos: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Color de puntos de la ilustración + Basic Character Formats Formatos básicos de caracteres + Case Mayúsculas y minúsculas + Kerning Interletraje +@msg {label} must be a number {label} debe ser un número +@msg {label} must be a number of at least 0.1 {label} debe ser un número de al menos 0,1 +@msg no character style `{name}` No existe el estilo de carácter `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Duotono… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index e080c8f98d..4f6a802ccd 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5909,6 +5909,12 @@ anchor Points: Pisteet: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Pisteiden väri kuvituksesta + Basic Character Formats Merkkien perusmuotoilut + Case Kirjainkoko + Kerning Merkkipariväli +@msg {label} must be a number {label} on oltava luku +@msg {label} must be a number of at least 0.1 {label} on oltava vähintään 0,1 +@msg no character style `{name}` Merkkityyliä `{name}` ei löytynyt # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Duotone… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index dd9cc259a2..57196f94ee 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5876,6 +5876,12 @@ anchor Points: Points : # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Couleur des points d’après l’illustration + Basic Character Formats Formats de caractère de base + Case Casse + Kerning Crénage +@msg {label} must be a number {label} doit être un nombre +@msg {label} must be a number of at least 0.1 {label} doit être un nombre d’au moins 0,1 +@msg no character style `{name}` Style de caractère `{name}` introuvable # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Bichromie… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 671a569caa..5e9b7a386b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5865,6 +5865,12 @@ anchor Points: Pontok: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Pontszín a grafikából + Basic Character Formats Alapvető karakterformátumok + Case Kis- és nagybetűk + Kerning Betűpárköz +@msg {label} must be a number {label}: szám kell +@msg {label} must be a number of at least 0.1 {label} legalább 0,1 értékű szám kell legyen +@msg no character style `{name}` A(z) `{name}` karakterstílus nem található # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Duplex… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 708378ba43..9c41f8daf0 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5497,6 +5497,12 @@ anchor Points: Punti: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Colore punti dalla grafica + Basic Character Formats Formati carattere di base + Case Maiuscole e minuscole + Kerning Crenatura +@msg {label} must be a number {label} deve essere un numero +@msg {label} must be a number of at least 0.1 {label} deve essere un numero di almeno 0,1 +@msg no character style `{name}` Stile di carattere `{name}` non trovato # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Bicromia… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 628f0ec033..6978094eee 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5563,6 +5563,12 @@ anchor Points: ポイント: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art ドットの色をアートから取得 + Basic Character Formats 基本文字形式 + Case 大文字と小文字 + Kerning カーニング +@msg {label} must be a number {label} には数値を指定してください +@msg {label} must be a number of at least 0.1 {label} には 0.1 以上の数値を指定してください +@msg no character style `{name}` 文字スタイル `{name}` が見つかりません # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… ダブルトーン… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 4d44093f71..545c5fc1e0 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5868,6 +5868,12 @@ anchor Points: წერტილები: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art წერტილების ფერი ნახატიდან + Basic Character Formats სიმბოლოს ძირითადი ფორმატები + Case ასოების რეგისტრი + Kerning კერნინგი +@msg {label} must be a number {label} უნდა იყოს რიცხვი +@msg {label} must be a number of at least 0.1 {label} უნდა იყოს მინიმუმ 0,1 +@msg no character style `{name}` სიმბოლოს სტილი `{name}` ვერ მოიძებნა # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… დუოტონი… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dea1f8f503..07b703658d 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5460,6 +5460,12 @@ anchor Points: 포인트: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art 아트워크에서 점 색상 가져오기 + Basic Character Formats 기본 문자 형식 + Case 대소문자 + Kerning 커닝 +@msg {label} must be a number {label}은(는) 숫자여야 합니다 +@msg {label} must be a number of at least 0.1 {label}은(는) 0.1 이상의 숫자여야 합니다 +@msg no character style `{name}` 문자 스타일 `{name}`을 찾을 수 없습니다 # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… 이중톤… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 9debbef17a..8104acb32e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5733,6 +5733,12 @@ anchor Points: Punkty: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Kolor kropek z kompozycji + Basic Character Formats Podstawowe formaty znaków + Case Wielkość liter + Kerning Kerning +@msg {label} must be a number {label} musi być liczbą +@msg {label} must be a number of at least 0.1 {label} musi być liczbą co najmniej 0,1 +@msg no character style `{name}` Nie znaleziono stylu znakowego `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Dwutonowy… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e40d32fb13..dbccb87c74 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5796,6 +5796,12 @@ anchor Points: Pontos: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Cor dos Pontos da Arte + Basic Character Formats Formatos básicos de caracteres + Case Maiúsculas e minúsculas + Kerning Kerning +@msg {label} must be a number {label} deve ser um número +@msg {label} must be a number of at least 0.1 {label} deve ser um número de pelo menos 0,1 +@msg no character style `{name}` Estilo de caractere `{name}` não encontrado # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Duotom… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 7bfca518c4..9419aeb42d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5856,6 +5856,12 @@ anchor Points: Точки: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Цвет точек из рисунка + Basic Character Formats Основные форматы символов + Case Регистр + Kerning Кернинг +@msg {label} must be a number {label} должно быть числом +@msg {label} must be a number of at least 0.1 {label} должно быть числом не меньше 0,1 +@msg no character style `{name}` Стиль символов `{name}` не найден # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Дуплекс… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd22f672d..616c5f319a 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5931,6 +5931,12 @@ shape Open Öppen # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Punktfärg från objekt + Basic Character Formats Grundläggande teckenformat + Case Skiftläge + Kerning Kerning +@msg {label} must be a number {label} måste vara ett tal +@msg {label} must be a number of at least 0.1 {label} måste vara ett tal på minst 0,1 +@msg no character style `{name}` Teckenformatet `{name}` hittades inte # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Duoton… diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index deb3e95d78..7d84df263f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5836,6 +5836,12 @@ anchor Points: Noktalar: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Nokta Rengini Sanattan Al + Basic Character Formats Temel karakter biçimleri + Case Büyük küçük harf + Kerning Karakter aralığı +@msg {label} must be a number {label} bir sayı olmalıdır +@msg {label} must be a number of at least 0.1 {label} en az 0,1 olan bir sayı olmalıdır +@msg no character style `{name}` `{name}` karakter stili bulunamadı # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Çift Ton… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d78f48b331..aeaffaaac5 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5477,6 +5477,12 @@ anchor Points: Точки: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Колір точок із малюнка + Basic Character Formats Основні формати символів + Case Регістр + Kerning Кернінг +@msg {label} must be a number {label} має бути числом +@msg {label} must be a number of at least 0.1 {label} має бути числом не менше 0,1 +@msg no character style `{name}` Стиль символів `{name}` не знайдено # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Дуплекс… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index ade0a07aae..3f3292be39 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5479,6 +5479,12 @@ anchor Points: Điểm: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Màu chấm theo tác phẩm + Basic Character Formats Định dạng ký tự cơ bản + Case Chữ hoa và chữ thường + Kerning Điều chỉnh khoảng cách cặp chữ +@msg {label} must be a number {label} phải là một số +@msg {label} must be a number of at least 0.1 {label} phải là một số ít nhất bằng 0,1 +@msg no character style `{name}` Không tìm thấy kiểu ký tự `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Hai tông… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index acffa1e4e9..cf2ae14bff 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5720,6 +5720,12 @@ anchor Points: 点: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art 网点颜色取自图稿 + Basic Character Formats 基本字符格式 + Case 大小写 + Kerning 字偶间距 +@msg {label} must be a number {label} 必须是数字 +@msg {label} must be a number of at least 0.1 {label} 必须是至少 0.1 的数字 +@msg no character style `{name}` 找不到字符样式 `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… 双色调… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 3b560be95b..f8c302079b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5516,6 +5516,12 @@ anchor Points: 點: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art 網點顏色取自圖稿 + Basic Character Formats 基本字元格式 + Case 大小寫 + Kerning 字偶間距 +@msg {label} must be a number {label} 必須是數字 +@msg {label} must be a number of at least 0.1 {label} 必須是至少 0.1 的數字 +@msg no character style `{name}` 找不到字元樣式 `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… 雙色調… diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index bb20fbbca5..5b83dc25b8 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -594,6 +594,11 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result< "ui.colorPicker" => crate::dialogs::open_color_picker(app, p), "ui.sampleScreenColor" => crate::screen_color::start(app, p), "ui.graphicStyleOptions" => crate::dialogs::graphic_style_options::open(app, s("name").as_deref()), + "ui.charStyleOptions" => match s("name") { + Some(name) => crate::dialogs::char_style_options::open(app, &name), + None => Err("missing `name`".into()), + }, + "ui.charStyleOptions.resetPanel" => crate::dialogs::char_style_options::reset_panel(app), "ui.newCharStyle" => crate::panels::text_styles::open_new(app, crate::panels::text_styles::Kind::Char), "ui.newParaStyle" => crate::panels::text_styles::open_new(app, crate::panels::text_styles::Kind::Para), "ui.symbolOptions" => { diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index c1cdf4f59d..ad7f88c5c6 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -225,7 +225,11 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { "ui.missingFontsDialog" => !cfg!(target_arch = "wasm32") && app.session.active().is_some(), "ui.findFontsInFolder" => crate::picks::can(app, &crate::picks::PickRequest::Folder) && app.session.active().is_some(), "ui.swatchOptions" | "ui.newSwatch" | "ui.newColorGroup" => app.session.active().is_some(), - "ui.graphicStyleOptions" | "ui.newCharStyle" | "ui.newParaStyle" => app.session.active().is_some(), + "ui.graphicStyleOptions" | "ui.charStyleOptions" | "ui.newCharStyle" | "ui.newParaStyle" => app.session.active().is_some(), + "ui.charStyleOptions.resetPanel" => app.ui.dialog.as_ref().is_some_and(|d| { + (d.kind == crate::dialogs::char_style_options::KIND || (d.kind == crate::dialogs::new_text_style::KIND && !d.bool("__para"))) + && d.str("section") == "basic" + }), "ui.newArtboard" => app.session.active().is_some(), "ui.sampleScreenColor" => crate::screen_color::available(app), "ui.newBrush" => app.session.active().is_some(), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index ba3e700c62..bd633da60e 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -657,6 +657,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{name?} open Graphic Style Options (dialog `graphicStyleOptions`, field `name`): for style `name` OK renames it (graphicStyle.rename); without, OK makes a new style of that name from the selection (graphicStyle.new)", ), + ( + "ui.charStyleOptions", + "Character Style Options", + "", + "{name} open Character Style Options (dialog `charStyleOptions`); OK runs charStyle.edit with name, to and sparse attrs in one undo step; Cancel restores a live preview", + ), + ( + "ui.charStyleOptions.resetPanel", + "Reset Panel", + "", + "{} clear the Basic Character Formats settings in the open Character Style Options or New Character Style dialog; available only on that section", + ), ( "ui.newCharStyle", "New Character Style…", diff --git a/crates/ui-egui/src/panels/text_styles.rs b/crates/ui-egui/src/panels/text_styles.rs index 8eebeae19f..1aca6039a1 100644 --- a/crates/ui-egui/src/panels/text_styles.rs +++ b/crates/ui-egui/src/panels/text_styles.rs @@ -375,8 +375,12 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui, kind: Kind) { if menu_item(ui, &crate::i18n::fmt(tl!("{kind} Style Options…"), &[("kind", kind.what_label())]), user, false) && let Some(n) = &sel { - let label = format!("{} Style Options", kind.what()); - app.run("ui.paramDialog", json!({ "command": format!("{p}.rename"), "label": label, "params": { "name": n, "to": n } })).ok(); + if kind == Kind::Char { + app.run("ui.charStyleOptions", json!({ "name": n })).ok(); + } else { + let label = format!("{} Style Options", kind.what()); + app.run("ui.paramDialog", json!({ "command": format!("{p}.rename"), "label": label, "params": { "name": n, "to": n } })).ok(); + } } } diff --git a/crates/ui-egui/src/panels/text_styles/tests.rs b/crates/ui-egui/src/panels/text_styles/tests.rs index d20962461a..144e2d525f 100644 --- a/crates/ui-egui/src/panels/text_styles/tests.rs +++ b/crates/ui-egui/src/panels/text_styles/tests.rs @@ -291,6 +291,22 @@ fn panel_menu_duplicate_and_delete_update_the_highlighted_style() { } } +#[test] +fn character_style_options_menu_opens_format_sections() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + click_label(&ctx, &mut app, "Body", |app, ui| show(app, ui, Kind::Char)); + assert_eq!(click_label(&ctx, &mut app, " Character Style Options…", |app, ui| menu(app, ui, Kind::Char)), 1); + let dialog = app.ui.dialog.as_ref().unwrap(); + assert_eq!(dialog.kind, crate::dialogs::char_style_options::KIND); + assert_eq!(dialog.str("section"), "general"); + assert_eq!(dialog.str("size"), "24.0"); + assert!(dialog.bool("preview")); +} + /// In a panel scrolled to the top of a long list, the menu's Duplicate scrolls the copy's row into /// view, and so does the New button's `highlight_made` for the new style. #[test] @@ -866,6 +882,40 @@ fn alt_clicking_new_character_style_asks_for_its_name() { assert_eq!(text_editing(&app), Some((id, 3, 5)), "the Type selection stays"); } +#[test] +fn new_character_style_without_selection_uses_japanese_defaults() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.prefs.interface_language = "ja".into(); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + assert!(app.session.japanese_interface()); + + for (name, size) in [("Default", None), ("Edited", Some(18))] { + crate::dialogs::new_text_style::open(&mut app, false, json!({})).unwrap(); + let dialog = app.ui.dialog.as_mut().unwrap(); + assert_eq!(dialog.fields["__attrs"]["charAlign"], "emBoxCenter"); + dialog.fields.insert("name".into(), json!(name)); + if let Some(size) = size { + dialog.fields.insert("size".into(), json!(size)); + } + crate::dialogs::confirm(&mut app).unwrap(); + let style = app.session.doc().unwrap().doc.char_styles.iter().find(|style| style.name == name).unwrap(); + assert_eq!(style.attrs.get("charAlign"), Some(&json!("emBoxCenter"))); + assert_eq!(style.attrs.get("size").cloned(), size.map(|value| json!(f64::from(value)))); + } + crate::dialogs::new_text_style::open(&mut app, false, json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!("basic")); + app.run("ui.charStyleOptions.resetPanel", json!({})).unwrap(); + let dialog = app.ui.dialog.as_ref().unwrap(); + assert!(!crate::dialogs::char_style_options::edited_attrs(dialog).unwrap().contains_key("charAlign")); + crate::dialogs::cancel(&mut app); + + crate::dialogs::new_text_style::open(&mut app, true, json!({})).unwrap(); + let dialog = app.ui.dialog.as_ref().unwrap(); + assert!(dialog.fields["__target"].get("attrs").is_none()); + assert!(dialog.fields.get("__attrs").is_none()); + crate::dialogs::cancel(&mut app); +} + /// The dialog highlights its new style and scrolls the matching panel to its row. #[test] fn a_style_made_in_the_new_style_dialog_is_highlighted() { diff --git a/docs/mcp.md b/docs/mcp.md index 129d7346c3..1557555237 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5109,6 +5109,22 @@ name and the Type tool's selection as it was when the dialog opened (else the se has, or an empty one, keeps the dialog open, and Cancel adds no style. A plain click on New still makes the style at once. +`ui.charStyleOptions {name}` opens Character Style Options for an existing named style. +Character Style Options uses `charStyle.edit {name, to, attrs}` to replace the name and complete sparse +attribute map in one undo step. `to` is trimmed and must be unique. The command updates text using the style +while preserving local overrides; Undo/Redo restores the definition and its users. The `charStyleOptions` +dialog exposes `name`, `font_family`, `font_style`, `size`, `leading`, `kerning`, `tracking`, `case`, +`position`, `underline`, `strikethrough`, `charAlign`, `section`, and `preview`. An empty field leaves its +attribute unset. `leading` and `kerning` also accept `Auto` to store an explicit automatic value. +The New Character Style dialog accepts the same character fields and starts with the selected text's +captured attributes. Without selected text, it starts with the character defaults for the interface language +(including `charAlign: "emBoxCenter"` in Japanese); changing a Basic field keeps other seeded attributes. +Without selected text, the New Paragraph Style dialog sends no `attrs`, and the engine gives the new style the +paragraph defaults for the interface language. Reset Panel in Basic Character +Formats removes those fields from the definition. +`ui.charStyleOptions.resetPanel {}` performs that reset when Basic Character Formats is selected in +either character-style dialog; it is disabled on General. + In the native file a text object's `para` holds the first paragraph's attributes and `paras` (left out when every paragraph is alike) one entry per paragraph, so older readers keep the first paragraph's. SVG export anchors each centred or right-aligned line on its own (`<tspan text-anchor>`), and SVG import gives each line's paragraph its diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e6645bbbce..caa6dbfb3c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -500,7 +500,8 @@ since 2026-10-01. - **COLR colour fonts:** v0 and v1 glyphs draw as vector layers (solid colours, linear and radial gradients, clips, blend modes, the foreground colour from the run's fill) on the canvas, as paths in SVG, EPS, legacy `.ai` and PDF with outlined text, as Type 3 text in PDF, and as editable groups with Create Outlines; sweep gradients and Porter-Duff compositing draw the glyph as an image. Measured by `tests_colr`, `render::tests_colrglyphs`, `pdf::tests::colr_glyphs_export_as_vector_art`, `svg/tests/it/colour_glyphs.rs`, `eps` `colr_glyphs_*`, `tests_pathops::create_outlines_turns_colr_glyphs_into_layer_groups`. Scores unchanged (estimated). - **OpenType SVG colour fonts:** each glyph's SVG document is read by the SVG importer (registered by the engine) into vector art in the run's colours, then drawn, exported and outlined as COLR glyphs are; PDF real text writes them as text that draws nothing and draws their art where they sit. Measured by `tests_svg_glyphs`, `svg/tests/it/svg_glyphs.rs`, `tests_colourfonts::create_outlines_turns_svg_glyphs_into_groups`, `tests_colourfonts::pdf_real_text_draws_svg_glyphs_as_art_and_keeps_their_characters`. Scores unchanged (estimated). - **Character-style Auto leading:** capture and explicit style attributes retain Auto as a reset, distinct from omitted leading. Redefine and later numeric updates preserve local leading overrides; the Character Styles marker recognizes Auto correctly. Regression assertions cover partial definitions, Undo/Redo and native save/load serialization. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Leading](https://helpx.adobe.com/illustrator/using/line-character-spacing.html). -- **Text styles redefined to the defaults:** New and Redefine Character Style and Paragraph Style capture every attribute of the selected text, including those at their defaults (Auto kerning, Roman baseline alignment, the default Hyphenation options, the Every-line Composer, no tab stops), and `charStyle.setAttrs` and `paraStyle.setAttrs` keep an attribute set to its default value. After a redefinition, text whose value still equals the old definition's takes the new value, a default included; local overrides and attributes the new definition leaves out stay. The style panels show "+" only where the text differs from its style, including type with Auto alignment. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). +- **Character Style Options, General and Basic Character Formats:** the dialog edits a style's name and stored character formats together. Empty fields remain unset, checkboxes show an indeterminate unset state, Basic's Reset Panel clears its explicit settings, and Preview can be canceled without changing history. OK saves one undo step; New Character Style offers the same fields from captured text or the interface language's defaults without a selection. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). +- **Text styles redefined to the defaults:** New and Redefine Character Style and Paragraph Style capture every attribute of the selected text, including those at their defaults (Auto kerning, Roman baseline alignment, the default Hyphenation options, the Every-line Composer, no tab stops), and `charStyle.setAttrs` and `paraStyle.setAttrs` keep an attribute set to its default value. After a redefinition, text whose value still equals the old definition's takes the new value, a default included; local overrides stay, and text that still has the old value of an attribute the new definition leaves out goes back to the Normal style's value. The style panels show "+" only where the text differs from its style, including type with Auto alignment. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Text styles dragged onto the panel's buttons:** a style dragged from the Character Styles or Paragraph Styles panel onto Create New Style is copied (`charStyle.duplicate`, `paraStyle.duplicate`, which name the copy `<name> copy`) and the copy is highlighted; dragged onto Delete it is deleted (`charStyle.delete`, `paraStyle.delete`); the Normal style is not deleted. Each drop is one undo step. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Auto Leading outside the layout:** a paragraph's Justification… › Auto Leading (<https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/adjust-word-and-letterspacing-in-justified-text.html>) also sets the Leading the Character panel shows for Auto type (blank where the selected paragraphs differ), the leading the Alt+↑/↓ nudge (`type.step`) steps from, each paragraph's own, and the lines Fill with Placeholder Text counts in area type. Evidence: `ParaStyle::effective_leading` (`crates/doc/src/text.rs` test `paragraph_effective_leading_follows_auto_leading`), `tests_prefs::auto_leading_steps_and_fills_from_the_paragraph_auto_leading`, `panels::character` test `leading_field_shows_the_paragraph_auto_leading`. - **The text style panel menus' Duplicate and Delete:** in the Character Styles and Paragraph Styles panel menus, Duplicate highlights the copy, as Create New Style highlights the new style, and Delete leaves no style highlighted, as the Delete button does, so Duplicate, Clear Overrides, Redefine and Style Options are disabled until another style is clicked. A highlighted style that is renamed in Style Options or deleted by a command is no longer highlighted either. The tests `panels::text_styles::tests::panel_menu_duplicate_and_delete_update_the_highlighted_style` and `a_highlighted_style_that_is_no_longer_listed_is_not_highlighted` cover this. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). From 2f1404af228c7eba86d5c97a7123c6657144233f Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 00:39:09 +0700 Subject: [PATCH 138/260] Optical kerning: shaped advances are read with get() --- crates/text/src/shape.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 5c69a6a935..ab547ef837 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -580,7 +580,7 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range< continue; } let mut start = i; - while start > 0 && glyphs[start - 1].byte == a.byte { + while start > 0 && glyphs.get(start - 1).is_some_and(|g| g.byte == a.byte) { start -= 1; } let mut end = i + 1; @@ -588,15 +588,16 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range< end += 1; } // A mark may precede its base inside either direction's shaped cluster. + let advance = |k: usize| shaped_advances.get(k).copied().unwrap_or(0.0); let first_base = glyphs[start..=i] .iter() .enumerate() - .max_by(|(a, _), (b, _)| shaped_advances[start + *a].total_cmp(&shaped_advances[start + *b])) + .max_by(|(a, _), (b, _)| advance(start + *a).total_cmp(&advance(start + *b))) .map_or(start, |(offset, _)| start + offset); let second_base = glyphs[i + 1..=end] .iter() .enumerate() - .max_by(|(a, _), (b, _)| shaped_advances[i + 1 + *a].total_cmp(&shaped_advances[i + 1 + *b])) + .max_by(|(a, _), (b, _)| advance(i + 1 + *a).total_cmp(&advance(i + 1 + *b))) .map_or(i + 1, |(offset, _)| i + 1 + offset); let (left_index, right_index, target, cluster_start, cluster_end) = if a.level.is_rtl() { (second_base, first_base, end, i + 1, end) } else { (first_base, second_base, i, start, i) }; From 939af8e255fb9f025e14bd4c4289bd81cdcac5e9 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 00:53:30 +0700 Subject: [PATCH 139/260] i18n: one Kerning row per catalog after the Character Styles and Kerning changes --- crates/ui-egui/src/i18n/ca.tsv | 1 - crates/ui-egui/src/i18n/cs.tsv | 1 - crates/ui-egui/src/i18n/de.tsv | 1 - crates/ui-egui/src/i18n/el.tsv | 1 - crates/ui-egui/src/i18n/es.tsv | 1 - crates/ui-egui/src/i18n/fi.tsv | 1 - crates/ui-egui/src/i18n/fr.tsv | 1 - crates/ui-egui/src/i18n/hu.tsv | 1 - crates/ui-egui/src/i18n/it.tsv | 1 - crates/ui-egui/src/i18n/ja.tsv | 1 - crates/ui-egui/src/i18n/ka.tsv | 1 - crates/ui-egui/src/i18n/ko.tsv | 1 - crates/ui-egui/src/i18n/pl.tsv | 1 - crates/ui-egui/src/i18n/pt-br.tsv | 1 - crates/ui-egui/src/i18n/ru.tsv | 1 - crates/ui-egui/src/i18n/sv.tsv | 1 - crates/ui-egui/src/i18n/tr.tsv | 1 - crates/ui-egui/src/i18n/uk.tsv | 1 - crates/ui-egui/src/i18n/vi.tsv | 1 - crates/ui-egui/src/i18n/zh-hans.tsv | 1 - crates/ui-egui/src/i18n/zh-hant.tsv | 1 - 21 files changed, 21 deletions(-) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 87c2edac46..9f8b0a55e4 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5871,7 +5871,6 @@ anchor Points: Punts: Dot Color from Art Color dels punts de la il·lustració Basic Character Formats Formats bàsics de caràcters Case Majúscules i minúscules - Kerning Interlletratge @msg {label} must be a number {label} ha de ser un nombre @msg {label} must be a number of at least 0.1 {label} ha de ser un nombre de com a mínim 0,1 @msg no character style `{name}` No s'ha trobat l'estil de caràcter `{name}` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 3f9c07acd5..2a9aeaf99b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5880,7 +5880,6 @@ anchor Points: Body: Dot Color from Art Barva bodů podle kresby Basic Character Formats Základní formáty znaků Case Velikost písmen - Kerning Vyrovnání párů @msg {label} must be a number {label} musí být číslo @msg {label} must be a number of at least 0.1 {label} musí být číslo alespoň 0,1 @msg no character style `{name}` styl znaků `{name}` neexistuje diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index f248421755..240bb8684d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5465,7 +5465,6 @@ anchor Points: Punkte: Dot Color from Art Punktfarbe aus Grafik Basic Character Formats Grundlegende Zeichenformate Case Großschreibung - Kerning Unterschneidung @msg {label} must be a number {label} muss eine Zahl sein @msg {label} must be a number of at least 0.1 {label} muss eine Zahl von mindestens 0,1 sein @msg no character style `{name}` Zeichenformat `{name}` nicht gefunden diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index eab0f70fa3..a4057ea1dc 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5832,7 +5832,6 @@ anchor Points: Σημεία: Dot Color from Art Χρώμα κουκκίδων από το γραφικό Basic Character Formats Βασικές μορφές χαρακτήρων Case Πεζά και κεφαλαία - Kerning Διαγραμμάτωση @msg {label} must be a number Το {label} πρέπει να είναι αριθμός @msg {label} must be a number of at least 0.1 Το {label} πρέπει να είναι αριθμός τουλάχιστον 0,1 @msg no character style `{name}` Δεν βρέθηκε το στυλ χαρακτήρων `{name}` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5b7d317406..2a77b567a4 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5823,7 +5823,6 @@ anchor Points: Puntos: Dot Color from Art Color de puntos de la ilustración Basic Character Formats Formatos básicos de caracteres Case Mayúsculas y minúsculas - Kerning Interletraje @msg {label} must be a number {label} debe ser un número @msg {label} must be a number of at least 0.1 {label} debe ser un número de al menos 0,1 @msg no character style `{name}` No existe el estilo de carácter `{name}` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 4f6a802ccd..44af5c9fb7 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5911,7 +5911,6 @@ anchor Points: Pisteet: Dot Color from Art Pisteiden väri kuvituksesta Basic Character Formats Merkkien perusmuotoilut Case Kirjainkoko - Kerning Merkkipariväli @msg {label} must be a number {label} on oltava luku @msg {label} must be a number of at least 0.1 {label} on oltava vähintään 0,1 @msg no character style `{name}` Merkkityyliä `{name}` ei löytynyt diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 57196f94ee..abc63175f4 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5878,7 +5878,6 @@ anchor Points: Points : Dot Color from Art Couleur des points d’après l’illustration Basic Character Formats Formats de caractère de base Case Casse - Kerning Crénage @msg {label} must be a number {label} doit être un nombre @msg {label} must be a number of at least 0.1 {label} doit être un nombre d’au moins 0,1 @msg no character style `{name}` Style de caractère `{name}` introuvable diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 5e9b7a386b..db6960188e 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5867,7 +5867,6 @@ anchor Points: Pontok: Dot Color from Art Pontszín a grafikából Basic Character Formats Alapvető karakterformátumok Case Kis- és nagybetűk - Kerning Betűpárköz @msg {label} must be a number {label}: szám kell @msg {label} must be a number of at least 0.1 {label} legalább 0,1 értékű szám kell legyen @msg no character style `{name}` A(z) `{name}` karakterstílus nem található diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 9c41f8daf0..618fce870f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5499,7 +5499,6 @@ anchor Points: Punti: Dot Color from Art Colore punti dalla grafica Basic Character Formats Formati carattere di base Case Maiuscole e minuscole - Kerning Crenatura @msg {label} must be a number {label} deve essere un numero @msg {label} must be a number of at least 0.1 {label} deve essere un numero di almeno 0,1 @msg no character style `{name}` Stile di carattere `{name}` non trovato diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 6978094eee..30005d3c3a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5565,7 +5565,6 @@ anchor Points: ポイント: Dot Color from Art ドットの色をアートから取得 Basic Character Formats 基本文字形式 Case 大文字と小文字 - Kerning カーニング @msg {label} must be a number {label} には数値を指定してください @msg {label} must be a number of at least 0.1 {label} には 0.1 以上の数値を指定してください @msg no character style `{name}` 文字スタイル `{name}` が見つかりません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 545c5fc1e0..ff40a494d5 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5870,7 +5870,6 @@ anchor Points: წერტილები: Dot Color from Art წერტილების ფერი ნახატიდან Basic Character Formats სიმბოლოს ძირითადი ფორმატები Case ასოების რეგისტრი - Kerning კერნინგი @msg {label} must be a number {label} უნდა იყოს რიცხვი @msg {label} must be a number of at least 0.1 {label} უნდა იყოს მინიმუმ 0,1 @msg no character style `{name}` სიმბოლოს სტილი `{name}` ვერ მოიძებნა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 07b703658d..d2f381afcb 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5462,7 +5462,6 @@ anchor Points: 포인트: Dot Color from Art 아트워크에서 점 색상 가져오기 Basic Character Formats 기본 문자 형식 Case 대소문자 - Kerning 커닝 @msg {label} must be a number {label}은(는) 숫자여야 합니다 @msg {label} must be a number of at least 0.1 {label}은(는) 0.1 이상의 숫자여야 합니다 @msg no character style `{name}` 문자 스타일 `{name}`을 찾을 수 없습니다 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8104acb32e..092e5e9447 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5735,7 +5735,6 @@ anchor Points: Punkty: Dot Color from Art Kolor kropek z kompozycji Basic Character Formats Podstawowe formaty znaków Case Wielkość liter - Kerning Kerning @msg {label} must be a number {label} musi być liczbą @msg {label} must be a number of at least 0.1 {label} musi być liczbą co najmniej 0,1 @msg no character style `{name}` Nie znaleziono stylu znakowego `{name}` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index dbccb87c74..d9a1a94f1e 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5798,7 +5798,6 @@ anchor Points: Pontos: Dot Color from Art Cor dos Pontos da Arte Basic Character Formats Formatos básicos de caracteres Case Maiúsculas e minúsculas - Kerning Kerning @msg {label} must be a number {label} deve ser um número @msg {label} must be a number of at least 0.1 {label} deve ser um número de pelo menos 0,1 @msg no character style `{name}` Estilo de caractere `{name}` não encontrado diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 9419aeb42d..d364faf0a0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5858,7 +5858,6 @@ anchor Points: Точки: Dot Color from Art Цвет точек из рисунка Basic Character Formats Основные форматы символов Case Регистр - Kerning Кернинг @msg {label} must be a number {label} должно быть числом @msg {label} must be a number of at least 0.1 {label} должно быть числом не меньше 0,1 @msg no character style `{name}` Стиль символов `{name}` не найден diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 616c5f319a..e01793d233 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5933,7 +5933,6 @@ shape Open Öppen Dot Color from Art Punktfärg från objekt Basic Character Formats Grundläggande teckenformat Case Skiftläge - Kerning Kerning @msg {label} must be a number {label} måste vara ett tal @msg {label} must be a number of at least 0.1 {label} måste vara ett tal på minst 0,1 @msg no character style `{name}` Teckenformatet `{name}` hittades inte diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7d84df263f..32bb794bca 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5838,7 +5838,6 @@ anchor Points: Noktalar: Dot Color from Art Nokta Rengini Sanattan Al Basic Character Formats Temel karakter biçimleri Case Büyük küçük harf - Kerning Karakter aralığı @msg {label} must be a number {label} bir sayı olmalıdır @msg {label} must be a number of at least 0.1 {label} en az 0,1 olan bir sayı olmalıdır @msg no character style `{name}` `{name}` karakter stili bulunamadı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index aeaffaaac5..835a75efcf 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5479,7 +5479,6 @@ anchor Points: Точки: Dot Color from Art Колір точок із малюнка Basic Character Formats Основні формати символів Case Регістр - Kerning Кернінг @msg {label} must be a number {label} має бути числом @msg {label} must be a number of at least 0.1 {label} має бути числом не менше 0,1 @msg no character style `{name}` Стиль символів `{name}` не знайдено diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 3f3292be39..6da79b33ea 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5481,7 +5481,6 @@ anchor Points: Điểm: Dot Color from Art Màu chấm theo tác phẩm Basic Character Formats Định dạng ký tự cơ bản Case Chữ hoa và chữ thường - Kerning Điều chỉnh khoảng cách cặp chữ @msg {label} must be a number {label} phải là một số @msg {label} must be a number of at least 0.1 {label} phải là một số ít nhất bằng 0,1 @msg no character style `{name}` Không tìm thấy kiểu ký tự `{name}` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index cf2ae14bff..2912cf6d2a 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5722,7 +5722,6 @@ anchor Points: 点: Dot Color from Art 网点颜色取自图稿 Basic Character Formats 基本字符格式 Case 大小写 - Kerning 字偶间距 @msg {label} must be a number {label} 必须是数字 @msg {label} must be a number of at least 0.1 {label} 必须是至少 0.1 的数字 @msg no character style `{name}` 找不到字符样式 `{name}` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index f8c302079b..b814e29917 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5518,7 +5518,6 @@ anchor Points: 點: Dot Color from Art 網點顏色取自圖稿 Basic Character Formats 基本字元格式 Case 大小寫 - Kerning 字偶間距 @msg {label} must be a number {label} 必須是數字 @msg {label} must be a number of at least 0.1 {label} 必須是至少 0.1 的數字 @msg no character style `{name}` 找不到字元樣式 `{name}` From 777ad6765c772fa4c2b298a438c47b34ac858357 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 21:31:38 -0700 Subject: [PATCH 140/260] File formats: JPEG 2000 images open and place MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File › Open and File › Place read JP2 files and raw JPEG 2000 codestreams (.jpf, .jpx, .jp2, .j2k, .j2c, .jpc) through hayro-jpeg2000, and store the pixels as PNG. Gray, RGB, CMYK and ICC-tagged images, with or without alpha, are converted to RGBA. Several codestreams, JPX composition or layers, other color spaces, inconsistent or oversize palettes, inconsistent channel definitions, oversize tile grids and images past the pixel allowance are refused with a message before the pixels are decoded. The capture and display resolution boxes size the image: the box that comes last sets each axis, and an axis without a usable value uses 72 ppi. IccProfile::to_srgb_into converts a pixel with the cached transform and no heap allocation. --- ASSETS.md | 3 + Cargo.lock | 1 + crates/color/src/cms/icc.rs | 15 +- crates/engine/Cargo.toml | 1 + crates/engine/src/cmd/fileio.rs | 3 + crates/engine/src/cmd/fileio/formats.rs | 18 +- crates/engine/src/cmd/fileio/jp2read.rs | 279 +++++++++++++++++ crates/engine/src/cmd/fileio/load.rs | 6 + crates/engine/src/cmd/fileio/ppi.rs | 37 ++- crates/engine/src/cmd/fileio/tests_jp2read.rs | 293 ++++++++++++++++++ .../fixtures/jpeg2000/checker-300ppi.jp2 | Bin 0 -> 265 bytes .../tests/fixtures/jpeg2000/checker-raw.j2k | Bin 0 -> 154 bytes .../tests/fixtures/jpeg2000/checker.jp2 | Bin 0 -> 239 bytes crates/engine/tests/import_fuzz.rs | 25 ++ crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + docs/file-format-parity.md | 4 +- docs/mcp.md | 4 +- docs/releasing.md | 2 +- docs/target-app-parity.md | 7 +- 40 files changed, 728 insertions(+), 14 deletions(-) create mode 100644 crates/engine/src/cmd/fileio/jp2read.rs create mode 100644 crates/engine/src/cmd/fileio/tests_jp2read.rs create mode 100644 crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2 create mode 100644 crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k create mode 100644 crates/engine/tests/fixtures/jpeg2000/checker.jp2 diff --git a/ASSETS.md b/ASSETS.md index 5bebefae63..3233c99d0e 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -345,6 +345,9 @@ Generated-in-code art is original and has no file to list. This covers the defau | `examples/ribbons.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | | | `examples/feature-sheet.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | | | `examples/perspective-city.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | | +| `crates/engine/tests/fixtures/jpeg2000/checker.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `3de9c2bb5b8aaec241d939b795002a68eb3d50e41d51c43368000804ad3de057` | +| `crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `76fa51ab8ccbc2534098b26b8e7fe16dd886e2b6298ba52d06a6b1bde9b61d9e` | +| `crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `1b1aeed8975d3cdc832da6ecf5855852d07d0c490105121e61a8aefb31af009b` | ## Assets embedded by the PDF backend diff --git a/Cargo.lock b/Cargo.lock index 9362671b07..934be1b120 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6208,6 +6208,7 @@ dependencies = [ "craft-docpath", "crc32fast", "flate2", + "hayro-jpeg2000", "image", "kurbo 0.13.1", "log", diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index 8201b8b97f..64f42f25b9 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -149,11 +149,20 @@ impl IccProfile { /// Device values (RGB / CMYK / Gray, 0..1) → sRGB. pub fn to_srgb(&self, v: &[f32], intent: Intent) -> Option<[f32; 3]> { + let mut src = [0.0f32; 4]; + let channels = self.channels(); + src.get_mut(..channels)?.iter_mut().zip(v.iter()).for_each(|(dst, value)| *dst = *value); + self.to_srgb_into(src.get(..channels)?, intent) + } + + /// Convert an exact-width device pixel using the cached transform and stack storage. + pub fn to_srgb_into(&self, v: &[f32], intent: Intent) -> Option<[f32; 3]> { + if v.len() != self.channels() { + return None; + } let xf = self.to_xf(intent)?; - let mut src = v.to_vec(); - src.resize(self.channels(), 0.0); let mut dst = [0.0f32; 3]; - xf.transform(&src, &mut dst).ok()?; + xf.transform(v, &mut dst).ok()?; Some(dst.map(|x| x.clamp(0.0, 1.0))) } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index f495697ceb..7b1199277b 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -36,6 +36,7 @@ vectorcraft-plugins = { workspace = true } vectorcraft-affinity = { workspace = true } vectorcraft-scriptcheck = { workspace = true } image = { workspace = true } +hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] } flate2 = { workspace = true } # The XML parts of Word documents placed as type (place/docx.rs). roxmltree = "0.21" diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index c8cb7218a7..7471ffb56a 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -33,6 +33,7 @@ pub(crate) mod imagemap; mod legacy_ai; mod load; pub(crate) use load::{MAX_RASTER_ALLOC, size_note}; +mod jp2read; mod metafile; mod naming; mod native; @@ -193,6 +194,8 @@ mod tests_psd; #[cfg(test)] mod tests_psdread; +#[cfg(test)] +mod tests_jp2read; #[cfg(test)] mod tests_pcxread; diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index f727215341..a1687e214f 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -491,6 +491,8 @@ pub const FORMATS: &[Format] = &[ reader("ps", "PostScript", &["ps"], "application/postscript", false), // ZSoft PCX images, read by `pcxread` and stored as PNG; exports don't write them. reader("pcx", "PCX", &["pcx"], "image/x-pcx", true), + // JP2 and raw codestreams are decoded to PNG; JPX composition is not supported. + reader("jpeg2000", "JPEG 2000", &["jpf", "jpx", "jp2", "j2k", "j2c", "jpc"], "image/jp2", true), ]; /// Every extension `document.open` reads (the "All readable files" filter of open dialogs). @@ -515,6 +517,12 @@ pub const OPEN_EXTS: &[&str] = &[ "icb", "vst", "pcx", + "jpf", + "jpx", + "jp2", + "j2k", + "j2c", + "jpc", "psd", "psb", "vctemplate", @@ -531,10 +539,10 @@ pub const OPEN_EXTS: &[&str] = &[ /// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to /// raster editors, so Finder and file managers don't offer a vector app for them, and there is no -/// `.epsf`, `.ps`, Targa or PCX type (File › Open and Place still read them all). On Linux the +/// `.epsf`, `.ps`, Targa, PCX or JPEG 2000 type (File › Open and Place still read them all). On Linux the /// desktop entry's EPS type (shared-mime-info's) also covers `.epsf`, so file managers offer /// VectorCraft for it. -pub const UNASSOCIATED_EXTS: &[&str] = &["psd", "psb", "epsf", "ps", "tga", "vda", "icb", "vst", "pcx"]; +pub const UNASSOCIATED_EXTS: &[&str] = &["psd", "psb", "epsf", "ps", "tga", "vda", "icb", "vst", "pcx", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc"]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares /// `.png` with PNG, so `.png` comes once), in [`FORMATS`] order. @@ -581,6 +589,12 @@ pub const PLACE_EXTS: &[&str] = &[ "icb", "vst", "pcx", + "jpf", + "jpx", + "jp2", + "j2k", + "j2c", + "jpc", "psd", "psb", "vctemplate", diff --git a/crates/engine/src/cmd/fileio/jp2read.rs b/crates/engine/src/cmd/fileio/jp2read.rs new file mode 100644 index 0000000000..9e0752c2c5 --- /dev/null +++ b/crates/engine/src/cmd/fileio/jp2read.rs @@ -0,0 +1,279 @@ +//! JPEG 2000 JP2 and codestream images for File › Open and File › Place. The decoded image is +//! bounded before allocation and converted to RGBA for the common PNG storage path. + +use hayro_jpeg2000::{ColorSpace, DecodeSettings, DecoderContext, Image}; +use vectorcraft_color::cms::{IccProfile, Intent}; + +/// Recognize a JP2 signature box or the start of a raw codestream. The decoder checks the rest. +pub(super) fn is_jpeg2000(bytes: &[u8]) -> bool { + bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") || bytes.starts_with(b"\xff\x4f") +} + +/// Boxes at one JP2 nesting level. Invalid lengths stop the walk at that level. +pub(super) fn boxes(b: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> { + let mut at = 0usize; + std::iter::from_fn(move || { + let header = b.get(at..at.checked_add(8)?)?; + let size = u32::from_be_bytes(header.get(..4)?.try_into().ok()?); + let (length, head) = match size { + 0 => (b.len().checked_sub(at)?, 8usize), + 1 => (usize::try_from(u64::from_be_bytes(b.get(at.checked_add(8)?..at.checked_add(16)?)?.try_into().ok()?)).ok()?, 16usize), + n => (n as usize, 8usize), + }; + if length < head { + return None; + } + let end = at.checked_add(length)?; + let data = b.get(at.checked_add(head)?..end)?; + let ty = header.get(4..8)?; + at = end; + Some((ty, data)) + }) +} + +/// The decoder ignores JPX layers and composition and silently uses the last top-level jp2c. +fn unsupported_jpx_content(bytes: &[u8]) -> bool { + fn association_has_content(data: &[u8], depth: usize) -> bool { + if depth >= 16 { + return true; + } + boxes(data).any(|(ty, child)| { + matches!(ty, b"jp2c" | b"jpch" | b"jplh" | b"comp" | b"ftbl") || (ty == b"asoc" && association_has_content(child, depth + 1)) + }) + } + let mut codestreams = 0u8; + for (ty, data) in boxes(bytes) { + match ty { + b"jp2c" => { + codestreams = codestreams.saturating_add(1); + if codestreams > 1 { + return true; + } + } + b"jpch" | b"jplh" | b"comp" | b"ftbl" => return true, + b"asoc" if association_has_content(data, 0) => return true, + _ => {} + } + } + false +} + +/// The largest embedded ICC profile read. +const MAX_PROFILE: usize = 4 * 1024 * 1024; +/// A codestream numbers its tiles 0 to 65,534 (Isot in SOT, ITU-T T.800 A.4.2). +const MAX_TILES: u64 = 65_535; +/// Bytes the decoder keeps for each component of each tile before decoding any of them. +const TILE_COMPONENT_BYTES: u64 = 256; + +/// SIZ follows SOC in the codestream; Lsiz includes its two length bytes. Returns the component +/// count, the image size and the tile count. +fn codestream_size(bytes: &[u8]) -> Option<(u64, u32, u32, u64)> { + let stream = if bytes.starts_with(b"\xff\x4f") { bytes } else { boxes(bytes).find_map(|(ty, data)| (ty == b"jp2c").then_some(data))? }; + if stream.get(..4)? != b"\xff\x4f\xff\x51" { + return None; + } + let length = u16::from_be_bytes(stream.get(4..6)?.try_into().ok()?) as usize; + let count = u16::from_be_bytes(stream.get(40..42)?.try_into().ok()?) as usize; + if count == 0 || length != 38usize.checked_add(count.checked_mul(3)?)? || stream.get(4..4usize.checked_add(length)?)?.len() != length { + return None; + } + let be32 = |range: std::ops::Range<usize>| stream.get(range).and_then(|v| v.try_into().ok()).map(u32::from_be_bytes); + let width = be32(8..12)?.checked_sub(be32(16..20)?)?; + let height = be32(12..16)?.checked_sub(be32(20..24)?)?; + // Tiles across and down (T.800 B-5): the grid from the tile offset, in whole tiles. + let tiles = |grid: u32, offset: u32, tile: u32| match (grid.checked_sub(offset), tile) { + (Some(span), 1..) => Some(u64::from(span).div_ceil(u64::from(tile))), + _ => None, + }; + let across = tiles(be32(8..12)?, be32(32..36)?, be32(24..28)?)?; + let down = tiles(be32(12..16)?, be32(36..40)?, be32(28..32)?)?; + Some((count as u64, width, height, across.checked_mul(down)?)) +} + +/// One `jp2h` header with at most one palette, component mapping and channel definition box, so +/// the checks below read the boxes the decoder uses. +fn single_header_boxes(bytes: &[u8]) -> bool { + let mut headers = boxes(bytes).filter(|(ty, _)| *ty == b"jp2h"); + let (Some((_, header)), None) = (headers.next(), headers.next()) else { + return false; + }; + [b"pclr", b"cmap", b"cdef"].iter().all(|kind| boxes(header).filter(|(ty, _)| ty == kind).count() <= 1) +} + +/// The number of channel definitions in a JP2 `cdef` box, `None` without one. Only color channels +/// 1 to n, in any order, followed by at most one opacity channel for the whole image are read; +/// any other layout (premultiplied opacity, opacity before a color, an unassociated channel) gives +/// `Some(0)`, which no image matches. +fn channel_definitions(bytes: &[u8]) -> Option<u64> { + if bytes.starts_with(b"\xff\x4f") { + return None; + } + let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data))?; + let cdef = boxes(header).find_map(|(ty, data)| (ty == b"cdef").then_some(data))?; + let count = cdef.get(..2).and_then(|n| n.try_into().ok()).map_or(0, |n: [u8; 2]| usize::from(u16::from_be_bytes(n))); + let Some(entries) = cdef.get(2..).filter(|rest| count > 0 && rest.len() == count * 6) else { + return Some(0); + }; + // (channel, type, association) by channel. + let mut defs: Vec<[u16; 3]> = + entries.as_chunks::<6>().0.iter().map(|&[a, b, c, d, e, f]| [[a, b], [c, d], [e, f]].map(u16::from_be_bytes)).collect(); + defs.sort_unstable(); + let opacity = defs.last().is_some_and(|&[_, kind, association]| kind == 1 && association == 0); + let colors = defs.len() - usize::from(opacity); + let mut seen = vec![false; colors]; + let layout_ok = defs.iter().enumerate().all(|(i, &[channel, kind, association])| { + usize::from(channel) == i + && (i >= colors + || (kind == 0 + && usize::from(association).checked_sub(1).and_then(|slot| seen.get_mut(slot)).is_some_and(|s| !std::mem::replace(s, true)))) + }); + Some(if layout_ok { defs.len() as u64 } else { 0 }) +} + +/// The column count of a JP2 palette (`pclr`), `Ok(None)` without one. A component mapping (`cmap`) +/// beside it needs one entry per column, each naming a codestream component and, when it maps +/// through the palette, a palette column; anything else is `Err`. +fn palette_columns(bytes: &[u8], components: u64) -> Result<Option<u64>, ()> { + if bytes.starts_with(b"\xff\x4f") { + return Ok(None); + } + let Some(header) = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)) else { + return Ok(None); + }; + let Some(palette) = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then_some(data)) else { + return Ok(None); + }; + let columns = palette.get(2).copied().ok_or(())?; + // Each column's descriptor: unsigned, 1 to 31 bits, as codestream samples are. + let depths = palette.get(3..3 + usize::from(columns)).ok_or(())?; + if columns == 0 || depths.iter().any(|&d| d & 0x80 != 0 || (d & 0x7f) + 1 > 31) { + return Err(()); + } + // Without a mapping the decoder maps every column from the first component. + let Some(mapping) = boxes(header).find_map(|(ty, data)| (ty == b"cmap").then_some(data)) else { + return Ok(Some(u64::from(columns))); + }; + if mapping.len() != usize::from(columns) * 4 { + return Err(()); + } + for &[c0, c1, kind, column] in mapping.as_chunks::<4>().0 { + let valid = u64::from(u16::from_be_bytes([c0, c1])) < components + && match kind { + 0 => true, + 1 => column < columns, + _ => false, + }; + if !valid { + return Err(()); + } + } + Ok(Some(u64::from(columns))) +} + +/// Decode within the raster allocation allowance, counting source samples, RGBA output, and +/// decoder intermediates. The decoder may need multiple full-sized component planes. +pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result<image::RgbaImage, String> { + if bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") && unsupported_jpx_content(bytes) { + return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()); + } + if bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") && !single_header_boxes(bytes) { + return Err("the JPEG 2000 file can't be read".into()); + } + let (codestream_channels, declared_w, declared_h, tile_count) = codestream_size(bytes).ok_or("the JPEG 2000 file can't be read")?; + if tile_count == 0 || tile_count > MAX_TILES { + return Err("the JPEG 2000 file can't be read".into()); + } + let declared_pixels = u64::from(declared_w).checked_mul(u64::from(declared_h)); + if declared_w == 0 + || declared_h == 0 + || declared_pixels.and_then(|n| n.checked_mul(codestream_channels)).and_then(|n| n.checked_mul(4)).is_none_or(|n| n > max_alloc) + || tile_count.checked_mul(codestream_channels).and_then(|n| n.checked_mul(TILE_COMPONENT_BYTES)).is_none_or(|n| n > max_alloc) + { + return Err(format!("an image of {declared_w} × {declared_h} pixels is too large to draw")); + } + // The decoder copies an embedded profile (after a 3-byte `colr` header) when it reads the file. + let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap_or_default(); + if boxes(header).any(|(ty, data)| ty == b"colr" && data.len() > MAX_PROFILE + 3) { + return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()); + } + let palette = palette_columns(bytes, codestream_channels).map_err(|()| "the JPEG 2000 file can't be read")?; + // The decoder keeps each palette value in 8 bytes and each row in its own list. + let palette_rows = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then(|| data.get(..2)).flatten()); + if let (Some(columns), Some(&[r0, r1])) = (palette, palette_rows) + && u64::from(u16::from_be_bytes([r0, r1])) * (columns * 8 + 24) > max_alloc + { + return Err(format!("an image of {declared_w} × {declared_h} pixels is too large to draw")); + } + let image = Image::new(bytes, &DecodeSettings::default()).map_err(|_| "the JPEG 2000 file can't be read")?; + let (w, h) = (image.width(), image.height()); + let color = image.color_space(); + let channels = match color { + ColorSpace::Gray => 1, + ColorSpace::RGB => 3, + ColorSpace::CMYK => 4, + ColorSpace::Icc { num_channels: 1 | 3 | 4, profile } if profile.len() <= MAX_PROFILE => color.num_channels(), + _ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()), + }; + let stride = u64::from(channels) + u64::from(image.has_alpha()); + // The decoder sizes its output by the palette's columns and writes one channel per mapping + // entry, so the columns, the entries and the output channels must all match. + if palette.is_some_and(|columns| columns != stride) { + return Err("the JPEG 2000 file can't be read".into()); + } + // The decoder reorders the channels by their definitions (`cdef`) and drops any channel without + // one, so a definition is needed for every channel it writes. + if channel_definitions(bytes).is_some_and(|count| count != stride || count != palette.unwrap_or(codestream_channels)) { + return Err("the JPEG 2000 file can't be read".into()); + } + let plane_channels = codestream_channels.max(stride).max(palette.unwrap_or(0)); + let too_large = || format!("an image of {w} × {h} pixels is too large to draw"); + let pixels = u64::from(w).checked_mul(u64::from(h)).ok_or_else(too_large)?; + let size = pixels.checked_mul(stride).ok_or_else(too_large)?; + let rgba_size = pixels.checked_mul(4).ok_or_else(too_large)?; + // hayro 0.3.5 keeps a f32 plane per component, including alpha, and a second + // f32 coefficient plane per component. Palette mapping or channel definitions + // can temporarily clone the component planes. Reserve another 8 bytes per + // pixel for IDWT and code-block scratch while samples and RGBA coexist. + let plane_bytes = pixels.checked_mul(plane_channels).and_then(|n| n.checked_mul(4)).ok_or_else(too_large)?; + let scratch_bytes = plane_bytes.checked_mul(2).and_then(|n| n.checked_add(pixels.checked_mul(8)?)).ok_or_else(too_large)?; + let working = + size.checked_add(rgba_size).and_then(|n| n.checked_add(plane_bytes)).and_then(|n| n.checked_add(scratch_bytes)).ok_or_else(too_large)?; + if w == 0 || h == 0 || working > max_alloc { + return Err(too_large()); + } + let len = usize::try_from(size).map_err(|_| too_large())?; + let mut samples = vec![0; len]; + image.decode_into(&mut samples, &mut DecoderContext::default()).map_err(|_| "the JPEG 2000 file can't be read")?; + let profile = match color { + ColorSpace::Icc { profile, .. } => { + Some(IccProfile::from_bytes(None, profile).map_err(|_| "the JPEG 2000 file has an unsupported color space or JPX content")?) + } + _ => None, + }; + let cms = vectorcraft_color::cms::active(); + let mut rgba = Vec::with_capacity(usize::try_from(rgba_size).map_err(|_| too_large())?); + for sample in samples.chunks_exact(stride as usize) { + let at = |i: usize| sample.get(i).copied().unwrap_or(0); + let rgb = match (color, profile.as_ref()) { + (ColorSpace::Gray, _) => [at(0); 3], + (ColorSpace::RGB, _) => [at(0), at(1), at(2)], + (ColorSpace::CMYK, _) => { + cms.cmyk_to_srgb([at(0), at(1), at(2), at(3)].map(|v| f32::from(v) / 255.0), false).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8) + } + (ColorSpace::Icc { .. }, Some(profile)) => { + let mut values = [0.0f32; 4]; + for (dst, src) in values.iter_mut().zip(sample.iter().take(usize::from(channels))) { + *dst = f32::from(*src) / 255.0; + } + profile + .to_srgb_into(&values[..usize::from(channels)], Intent::RelativeColorimetric) + .ok_or("the JPEG 2000 file has an unsupported color space or JPX content")? + .map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8) + } + _ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()), + }; + let [r, g, b] = rgb; + rgba.extend_from_slice(&[r, g, b, if image.has_alpha() { at(usize::from(channels)) } else { 255 }]); + } + image::RgbaImage::from_raw(w, h, rgba).ok_or_else(|| "the JPEG 2000 file can't be read".into()) +} diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index c2e58e39e7..0083130695 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -97,6 +97,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { if psdread::is_psd(bytes) { return format(if psdread::is_psb(bytes) { "psb" } else { "psd" }); } + if super::jp2read::is_jpeg2000(bytes) { + return format("jpeg2000"); + } if let Some(f) = image::guess_format(bytes).ok().and_then(image_format) { return Some(f); } @@ -631,6 +634,9 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> { let cms = vectorcraft_color::cms::active(); return as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, ppi); } + if super::jp2read::is_jpeg2000(bytes) { + return as_png(super::jp2read::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi); + } let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(err)?; if reader.format().is_none() && super::tgaread::is_targa(bytes) { reader.set_format(image::ImageFormat::Tga); diff --git a/crates/engine/src/cmd/fileio/ppi.rs b/crates/engine/src/cmd/fileio/ppi.rs index 61b7417567..fd2ffbf8c2 100644 --- a/crates/engine/src/cmd/fileio/ppi.rs +++ b/crates/engine/src/cmd/fileio/ppi.rs @@ -1,6 +1,6 @@ //! Image resolution metadata (pixels per inch): PNG `pHYs`, JPEG JFIF density or EXIF, TIFF and //! WebP EXIF resolution tags, BMP pixels per metre, a Photoshop document's ResolutionInfo, a PCX -//! header's HDpi and VDpi. Place +//! header's HDpi and VDpi, or JP2 capture and display resolution boxes. Place //! sizes an image by it (72 ppi when the file has none); images converted to PNG on import keep it //! as a `pHYs` chunk. @@ -24,12 +24,47 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { super::psdread::resolution(bytes) } else if super::pcxread::is_pcx(bytes) { super::pcxread::resolution(bytes) + } else if super::jp2read::is_jpeg2000(bytes) { + jp2(bytes) } else { None }; r.filter(|(x, y)| [*x, *y].iter().all(|v| v.is_finite() && (1.0..=100_000.0).contains(v))) } +fn jp2_axis(n: u16, d: u16, e: i8) -> Option<f64> { + if d == 0 { + return None; + } + let ppi = f64::from(n) / f64::from(d) * 10f64.powi(i32::from(e)) * INCH_M; + (ppi.is_finite() && (1.0..=100_000.0).contains(&ppi)).then_some(ppi) +} + +/// JP2 resolution is independent on each axis. Later capture or display boxes replace earlier +/// valid values for that axis; an invalid later axis leaves the earlier value intact. +fn jp2(b: &[u8]) -> Option<(f64, f64)> { + if !b.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") { + return Some((72.0, 72.0)); + } + let (mut x, mut y) = (None, None); + for (_, header) in super::jp2read::boxes(b).filter(|(ty, _)| *ty == b"jp2h") { + for (_, res) in super::jp2read::boxes(header).filter(|(ty, _)| *ty == b"res ") { + for (_, data) in super::jp2read::boxes(res).filter(|(ty, _)| *ty == b"resc" || *ty == b"resd") { + let Some([vn0, vn1, vd0, vd1, hn0, hn1, hd0, hd1, ve, he]): Option<[u8; 10]> = data.get(..10).and_then(|v| v.try_into().ok()) else { + continue; + }; + if let Some(value) = jp2_axis(u16::from_be_bytes([hn0, hn1]), u16::from_be_bytes([hd0, hd1]), he as i8) { + x = Some(value); + } + if let Some(value) = jp2_axis(u16::from_be_bytes([vn0, vn1]), u16::from_be_bytes([vd0, vd1]), ve as i8) { + y = Some(value); + } + } + } + } + Some((x.unwrap_or(72.0), y.unwrap_or(72.0))) +} + /// `n` bytes at `at` (`None` past the end; offsets come from the file, so no overflow either). fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> { b.get(at..at.checked_add(n)?) diff --git a/crates/engine/src/cmd/fileio/tests_jp2read.rs b/crates/engine/src/cmd/fileio/tests_jp2read.rs new file mode 100644 index 0000000000..54481c4038 --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_jp2read.rs @@ -0,0 +1,293 @@ +//! JPEG 2000 Open, Place, pixel and resolution regressions using original synthetic fixtures. + +use serde_json::json; + +use super::jp2read::is_jpeg2000; +use super::*; + +const JP2: &[u8] = include_bytes!("../../../tests/fixtures/jpeg2000/checker.jp2"); +const RAW: &[u8] = include_bytes!("../../../tests/fixtures/jpeg2000/checker-raw.j2k"); +const PPI300: &[u8] = include_bytes!("../../../tests/fixtures/jpeg2000/checker-300ppi.jp2"); +const COLORS: [[u8; 4]; 4] = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255; 4]]; + +fn pixels(bytes: &[u8]) -> Vec<[u8; 4]> { + let raster = load::raster_image(bytes).unwrap(); + image::load_from_memory(&raster.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect() +} + +fn boxed(ty: &[u8; 4], data: &[u8]) -> Vec<u8> { + let mut out = ((data.len() + 8) as u32).to_be_bytes().to_vec(); + out.extend(ty); + out.extend(data); + out +} + +fn with_resolution(children: &[Vec<u8>]) -> Vec<u8> { + let mut file = JP2.to_vec(); + let at = file.windows(4).position(|w| w == b"jp2h").unwrap() - 4; + let old_len = u32::from_be_bytes(file[at..at + 4].try_into().unwrap()) as usize; + let mut header = file[at + 8..at + old_len].to_vec(); + if !children.is_empty() { + header.extend(boxed(b"res ", &children.concat())); + } + file.splice(at..at + old_len, boxed(b"jp2h", &header)); + file +} + +fn res(ty: &[u8; 4], vr: u16, hr: u16) -> Vec<u8> { + let mut data = Vec::new(); + for n in [vr, hr] { + data.extend(n.to_be_bytes()); + data.extend(254u16.to_be_bytes()); + } + data.extend([2, 2]); + boxed(ty, &data) +} + +#[test] +fn checker_opens_and_places_with_exact_pixels() { + for (name, bytes) in [("checker.jp2", JP2), ("checker-raw.j2k", RAW)] { + assert_eq!(pixels(bytes), COLORS, "{name}"); + let mut s = Session::new(); + let encoded = vectorcraft_format::base64_encode(bytes); + let opened = s.execute("document.open", &json!({"name": name, "dataBase64": encoded})).unwrap(); + assert_eq!(opened["format"], "jpeg2000"); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(2.0, 2.0)); + let blob = s.doc().unwrap().doc.images.values().next().unwrap(); + assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::<Vec<_>>(), COLORS); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let placed = s.execute("file.place", &json!({"name": name, "dataBase64": encoded})).unwrap(); + assert_eq!(placed["format"], "jpeg2000"); + let blob = s.doc().unwrap().doc.images.values().next().unwrap(); + assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::<Vec<_>>(), COLORS); + assert!(load::texture_image(bytes).is_ok()); + } +} + +#[test] +fn signatures_and_every_extension() { + assert!(is_jpeg2000(JP2) && is_jpeg2000(RAW)); + for ext in ["jpf", "jpx", "jp2", "j2k", "j2c", "jpc"] { + assert_eq!(load::detect(&format!("a.{ext}"), b"invalid").map(|f| f.id), Some("jpeg2000")); + assert!(OPEN_EXTS.contains(&ext) && PLACE_EXTS.contains(&ext) && UNASSOCIATED_EXTS.contains(&ext)); + } + assert_eq!(load::detect("unknown.bin", JP2).map(|f| f.id), Some("jpeg2000")); + assert_eq!(load::detect("unknown.bin", RAW).map(|f| f.id), Some("jpeg2000")); +} + +#[test] +fn resolution_boxes_use_last_valid_axis_and_72_fallback() { + let check = |children: &[Vec<u8>], want: (f64, f64)| { + let file = with_resolution(children); + let got = ppi::resolution(&file).unwrap(); + assert!((got.0 - want.0).abs() < 0.01 && (got.1 - want.1).abs() < 0.01, "{got:?} != {want:?}"); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "a.jp2", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap(); + let size = s.doc().unwrap().doc.artboards[0].rect.size(); + assert!((size.width - 144.0 / want.0).abs() < 0.01 && (size.height - 144.0 / want.1).abs() < 0.01); + }; + check(&[], (72.0, 72.0)); + check(&[res(b"resc", 30000, 30000)], (300.0, 300.0)); + check(&[res(b"resd", 15000, 15000)], (150.0, 150.0)); + check(&[res(b"resc", 30000, 30000), res(b"resd", 15000, 15000)], (150.0, 150.0)); + check(&[res(b"resd", 15000, 15000), res(b"resc", 30000, 30000)], (300.0, 300.0)); + check(&[res(b"resc", 30000, 15000)], (150.0, 300.0)); + assert_eq!(ppi::resolution(RAW), Some((72.0, 72.0))); + assert!((ppi::resolution(PPI300).unwrap().0 - 300.0).abs() < 0.01); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "a.jp2", "dataBase64": vectorcraft_format::base64_encode(PPI300)})).unwrap(); + let size = s.doc().unwrap().doc.artboards[0].rect.size(); + assert!((size.width - 0.48).abs() < 0.001 && (size.height - 0.48).abs() < 0.001); + let blob = s.doc().unwrap().doc.images.values().next().unwrap(); + let stored = ppi::resolution(&blob.bytes).unwrap(); + assert!((stored.0 - 300.0).abs() < 0.01 && (stored.1 - 300.0).abs() < 0.01); +} + +#[test] +fn malformed_resolution_and_image_data_are_bounded() { + let good = res(b"resc", 30000, 15000); + let mut zero = res(b"resd", 15000, 15000); + zero[10..12].copy_from_slice(&0u16.to_be_bytes()); + let got = ppi::resolution(&with_resolution(&[good.clone(), zero])).unwrap(); + assert!((got.0 - 150.0).abs() < 0.01 && (got.1 - 300.0).abs() < 0.01); + let short = boxed(b"resd", &[0; 9]); + assert!(ppi::resolution(&with_resolution(&[good.clone(), short])).unwrap().0 > 149.0); + assert_eq!(ppi::resolution(&with_resolution(&[boxed(b"resc", &[0; 9])])), Some((72.0, 72.0))); + let mut over = good.clone(); + over[..4].copy_from_slice(&u32::MAX.to_be_bytes()); + assert_eq!(ppi::resolution(&with_resolution(&[over])), Some((72.0, 72.0))); + let mut outer_over = JP2.to_vec(); + let jp2h = outer_over.windows(4).position(|w| w == b"jp2h").unwrap() - 4; + outer_over[jp2h..jp2h + 4].copy_from_slice(&u32::MAX.to_be_bytes()); + assert_eq!(ppi::resolution(&outer_over), Some((72.0, 72.0))); + let mut extended = Vec::from(1u32.to_be_bytes()); + extended.extend(b"resd"); + extended.extend(26u64.to_be_bytes()); + extended.extend(&res(b"resd", 15000, 30000)[8..]); + assert!(ppi::resolution(&with_resolution(&[extended])).unwrap().0 > 299.0); + let mut to_end = res(b"resd", 15000, 30000); + to_end[..4].copy_from_slice(&0u32.to_be_bytes()); + assert!(ppi::resolution(&with_resolution(&[to_end])).unwrap().0 > 299.0); + for bytes in [&JP2[..12], &RAW[..4], &JP2[..JP2.len() - 5]] { + assert!(load::raster_image(bytes).is_err()); + } + assert!(super::jp2read::decode(JP2, 8).is_err()); + // RGBA (16 bytes) and the float component planes (48 bytes) each fit; + // their concurrent allocation with samples and scratch does not. + assert!(super::jp2read::decode(JP2, 80).unwrap_err().contains("too large to draw")); + let mut huge = RAW.to_vec(); + huge[8..12].copy_from_slice(&100_000u32.to_be_bytes()); + huge[12..16].copy_from_slice(&100_000u32.to_be_bytes()); + assert!(load::raster_image(&huge).is_err()); + let mut jpx = JP2.to_vec(); + jpx.extend(boxed(b"jp2c", RAW)); + assert!(load::raster_image(&jpx).err().unwrap().to_string().contains("unsupported color space or JPX content")); + let mut layered = JP2.to_vec(); + layered.extend(boxed(b"jpch", &[])); + assert!(load::raster_image(&layered).err().unwrap().to_string().contains("unsupported color space or JPX content")); + let mut wrapped = JP2.to_vec(); + wrapped.extend(boxed(b"asoc", &boxed(b"jp2c", RAW))); + assert!(load::raster_image(&wrapped).err().unwrap().to_string().contains("unsupported color space or JPX content")); +} + +#[test] +fn compatible_jpx_brand_alone_keeps_checker_pixels() { + let mut branded = JP2.to_vec(); + branded[12..16].copy_from_slice(&24u32.to_be_bytes()); + branded.splice(32..32, b"jpx ".iter().copied()); + assert_eq!(pixels(&branded), COLORS); +} + +#[test] +fn codestream_component_count_bounds_decode_planes() { + assert_eq!(super::jp2read::decode(RAW, 1000).unwrap().pixels().map(|p| p.0).collect::<Vec<_>>(), COLORS); + let mut many = RAW.to_vec(); + let component = many[42..45].to_vec(); + many.splice(42..42, component.repeat(17)); + many[4..6].copy_from_slice(&98u16.to_be_bytes()); // 38 + 3 * 20 + many[40..42].copy_from_slice(&20u16.to_be_bytes()); + assert!(super::jp2read::decode(&many, 1000).unwrap_err().contains("too large to draw")); + many[0..4].copy_from_slice(&[0, 0, 0, 0]); + assert!(super::jp2read::decode(&many, 1000).unwrap_err().contains("can't be read")); +} + +fn with_header_boxes(extra: &[Vec<u8>]) -> Vec<u8> { + let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap(); + let mut children = header.to_vec(); + children.extend(extra.concat()); + super::jp2read::boxes(JP2) + .map(|(ty, data)| if ty == b"jp2h" { boxed(b"jp2h", &children) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::<Vec<_>>() + .concat() +} + +#[test] +fn channel_definitions_must_cover_every_channel() { + // (channel, type, association): color channels 1 to 3, an opacity channel (type 1). + let cdef = |defs: &[[u16; 3]]| { + let mut data = (defs.len() as u16).to_be_bytes().to_vec(); + data.extend(defs.iter().flatten().flat_map(|v| v.to_be_bytes())); + boxed(b"cdef", &data) + }; + assert_eq!(pixels(&with_header_boxes(&[cdef(&[[0, 0, 1], [1, 0, 2], [2, 0, 3]])])), COLORS); + // Channel 0 as green and channel 1 as red swap the two. + let swapped = [[0, 255, 0, 255], [255, 0, 0, 255], [0, 0, 255, 255], [255; 4]]; + assert_eq!(pixels(&with_header_boxes(&[cdef(&[[0, 0, 2], [1, 0, 1], [2, 0, 3]])])), swapped); + for defs in [ + vec![[0, 0, 1]], + vec![[0, 0, 1], [1, 0, 2], [2, 1, 0]], + vec![[0, 0, 1], [1, 0, 2], [2, 0, 3], [3, 1, 0]], + // Opacity first, a premultiplied opacity, a repeated color, an unassociated color. + vec![[0, 1, 0], [1, 0, 1], [2, 0, 2]], + vec![[0, 0, 1], [1, 0, 2], [2, 2, 0]], + vec![[0, 0, 1], [1, 0, 1], [2, 0, 3]], + vec![[0, 0, 1], [1, 0, 2], [2, 0, 0]], + ] { + assert!(load::raster_image(&with_header_boxes(&[cdef(&defs)])).err().unwrap().to_string().contains("can't be read"), "{defs:?}"); + } + // A second definition box, and a second header, are refused. + let full = cdef(&[[0, 0, 1], [1, 0, 2], [2, 0, 3]]); + assert!(load::raster_image(&with_header_boxes(&[full.clone(), cdef(&[[0, 0, 1]])])).err().unwrap().to_string().contains("can't be read")); + let mut two_headers = JP2.to_vec(); + let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap(); + two_headers.extend(boxed(b"jp2h", header)); + assert!(load::raster_image(&two_headers).err().unwrap().to_string().contains("can't be read")); +} + +#[test] +fn palette_needs_one_mapping_per_column() { + // 256 entries of three 8-bit columns, entry i being (i, i, i). + let mut palette = vec![1, 0, 3, 7, 7, 7]; + palette.extend((0..=255u8).flat_map(|i| [i; 3])); + let pclr = boxed(b"pclr", &palette); + let mut deep = vec![1, 0, 3, 7, 7, 31]; + deep.extend((0..=255u8).flat_map(|i| [i, i, 0, 0, 0, i])); + let deep = boxed(b"pclr", &deep); + let cmap = |entries: &[[u8; 4]]| boxed(b"cmap", &entries.concat()); + // Each component through its own column gives the same pixels. + let mapped = with_header_boxes(&[pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 0, 0]])]); + assert_eq!(pixels(&mapped), COLORS); + // 256 rows of three 8-byte values and a 24-byte list each (12,288 bytes) pass a 12,000-byte allowance. + assert!(super::jp2read::decode(&mapped, 12_000).unwrap_err().contains("too large to draw")); + for extra in [ + vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 1, 2], [0, 0, 1, 0]])], + vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 9, 1, 2]])], + vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 1, 3]])], + vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1]])], + // A 32-bit column. + vec![deep.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 1, 2]])], + ] { + assert!(load::raster_image(&with_header_boxes(&extra)).err().unwrap().to_string().contains("can't be read")); + } +} + +#[test] +fn tile_grid_is_bounded_before_decoding() { + let tiled = |size: u32, tile: u32| { + let mut file = RAW.to_vec(); + file[8..12].copy_from_slice(&size.to_be_bytes()); + file[12..16].copy_from_slice(&size.to_be_bytes()); + file[24..28].copy_from_slice(&tile.to_be_bytes()); + file[28..32].copy_from_slice(&tile.to_be_bytes()); + file + }; + // 1,000 × 1,000 one-pixel tiles are more than a codestream can number. + assert!(super::jp2read::decode(&tiled(1000, 1), MAX_RASTER_ALLOC).unwrap_err().contains("can't be read")); + assert!(super::jp2read::decode(&tiled(2, 0), MAX_RASTER_ALLOC).unwrap_err().contains("can't be read")); + // 255 × 255 one-pixel tiles of three components need more than this allowance before decoding. + assert!(super::jp2read::decode(&tiled(255, 1), 1 << 20).unwrap_err().contains("too large to draw")); +} + +#[test] +fn cielab_images_are_refused() { + let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap(); + // Enumerated color space 14, CIELab, with its default range and offset. + let children = super::jp2read::boxes(header) + .map(|(ty, data)| if ty == b"colr" { boxed(b"colr", &[1, 0, 0, 0, 0, 0, 14]) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::<Vec<_>>(); + let file = super::jp2read::boxes(JP2) + .map(|(ty, data)| if ty == b"jp2h" { boxed(b"jp2h", &children.concat()) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::<Vec<_>>() + .concat(); + assert!(load::raster_image(&file).err().unwrap().to_string().contains("unsupported color space")); +} + +#[test] +fn embedded_srgb_profile_keeps_checker_pixels() { + let icc = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::SRGB).unwrap(); + let mut colr_data = vec![2, 0, 0]; + colr_data.extend_from_slice(&icc); + let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap(); + let children = super::jp2read::boxes(header) + .map(|(ty, data)| if ty == b"colr" { boxed(b"colr", &colr_data) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::<Vec<_>>(); + let file = super::jp2read::boxes(JP2) + .map(|(ty, data)| if ty == b"jp2h" { boxed(b"jp2h", &children.concat()) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::<Vec<_>>() + .concat(); + assert_eq!(pixels(&file), COLORS); + // A profile past 4 MiB is refused before the decoder reads the file. + let mut big = vec![2, 0, 0]; + big.resize(3 + 4 * 1024 * 1024 + 1, 0); + assert!(super::jp2read::decode(&with_header_boxes(&[boxed(b"colr", &big)]), MAX_RASTER_ALLOC).unwrap_err().contains("unsupported color space")); +} diff --git a/crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2 b/crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2 new file mode 100644 index 0000000000000000000000000000000000000000..60f2c24239522c67e548ace2a185ab3a0597eda1 GIT binary patch literal 265 zcmZQzVBpCLP*C9IYUg5LU=T?wsVvAUFj4@r8KAT~kj?;d#WFKeihwi|7&CLQ18D{Z z{^b0eB1SM%07yy|r4}myX(1q;tf$Pt2*P05ML=Vc|NH+BWY7omA;y52AOfTaq7W>^ z%+AONLH~moc))UOOiT=n|6>@$6dXJ}0?^R^6b1nXMxVs8WHVzuLp?(SqyG~aKt5t% c&;{z63}&Ga)1R?0+`r$z!La@S3&a1L09t`7jQ{`u literal 0 HcmV?d00001 diff --git a/crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k b/crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k new file mode 100644 index 0000000000000000000000000000000000000000..0e2196656bb1737c0ffcb707260f718b20c62299 GIT binary patch literal 154 zcmezG|38pHp8*7zpcu?yU|<B&APfb}?2L>M^goD!2PnwMz{bSH!1zCgK}^BH!y^C< z{ZC;KU|{q~EK4>s)-%*IG%)%<fq@Hbm@ZJ)WSF@KdipaKhWqy$I2hI+U}5-w696_C B8d?AV literal 0 HcmV?d00001 diff --git a/crates/engine/tests/fixtures/jpeg2000/checker.jp2 b/crates/engine/tests/fixtures/jpeg2000/checker.jp2 new file mode 100644 index 0000000000000000000000000000000000000000..787ca865d86c842b8e8bf0b28db51dce03503eef GIT binary patch literal 239 zcmZQzVBpCLP*C9IYUg5LU=T?wsVvAUFj4@r8KAT-kj?;d#WFKeihwi|7&CLQ18D{Z z{^b0eB1SM%07xzZDo+0I|38pHA1nq@3}%7|kV1%Jun;plBO?U;4`Sc}%ds&rF);p* zVGvVr@bCygL;q741Q-~763dd!jP(rl3=NF_PhbGKn}I<WsB1Eqg+fe!#=>y_egg-? L`U5Ns|8D{SZk#8K literal 0 HcmV?d00001 diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 12eaf13d64..10109e1ec3 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -1781,6 +1781,31 @@ proptest! { // ---------- SVG saved with hidden layers and editing data ---------- +proptest! { + #![proptest_config(config())] + + /// Mutated JP2 boxes and raw codestream markers must return errors rather than unwind. + #[test] + fn mutated_jpeg2000_files_do_not_panic(raw in any::<bool>(), cut in 0usize..300, edits in prop::collection::vec((0usize..300, any::<u8>()), 0..8)) { + let (name, mut bytes) = if raw { + ("a.j2k", include_bytes!("fixtures/jpeg2000/checker-raw.j2k").to_vec()) + } else { + ("a.jp2", include_bytes!("fixtures/jpeg2000/checker.jp2").to_vec()) + }; + for (at, byte) in edits { + if let Some(slot) = bytes.get_mut(at) { *slot = byte; } + } + bytes.truncate(cut); + let result = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + let params = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("document.open", ¶ms)); + let _ = no_panic(s.execute("file.place", ¶ms)); + }); + prop_assert!(result.is_ok(), "{name}: panicked: {:?}", result.err()); + } +} + /// The rich document with a hidden layer, saved as SVG with its editing data. fn saved_svg() -> String { let mut d = rich_doc(); diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 311580ce5e..d5f5e6dad5 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4862,6 +4862,8 @@ imageTrace Outline Obris @msg the PCX file is cut short PCX datoteka je skraćena @msg the PCX file's header is damaged zaglavlje PCX datoteke je oštećeno @msg PCX files with {bits}-bit pixels in {planes} planes can't be read PCX datoteke s {bits}-bitnim pikselima u {planes} ravni nije moguće pročitati +@msg the JPEG 2000 file can't be read datoteku JPEG 2000 nije moguće pročitati +@msg the JPEG 2000 file has an unsupported color space or JPX content datoteka JPEG 2000 ima nepodržan prostor boja ili JPX sadržaj @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD slika je prevelika za čitanje ({_1} × {_2} piksela) @msg zipped 32-bit PSD image data with prediction can't be read zipovani 32-bitni PSD podaci slike s predviđanjem ne mogu se pročitati @msg {depth}-bit PSD files in this colour mode can't be read {depth}-bitne PSD datoteke u ovom načinu boja ne mogu se pročitati diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 9f8b0a55e4..4f2d7c6164 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6006,6 +6006,8 @@ breakText Glyphs Glifs Gap 4 Separació 4 Dash 5 Guió 5 Gap 5 Separació 5 +@msg the JPEG 2000 file can't be read no es pot llegir el fitxer JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content el fitxer JPEG 2000 té un espai de color o contingut JPX no compatible @msg You must choose a side pattern. Heu de triar un patró lateral. @msg invalid pattern tile choice opció de mosaic de patró no vàlida @msg no pattern named `{choice}` no hi ha cap patró anomenat `{choice}` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 2a9aeaf99b..ab09e818aa 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4900,6 +4900,8 @@ imageTrace Outline Obrys @msg the PCX file is cut short soubor PCX je useknutý @msg the PCX file's header is damaged hlavička souboru PCX je poškozená @msg PCX files with {bits}-bit pixels in {planes} planes can't be read soubory PCX s {bits}bitovými obrazovými body v {planes} rovinách nelze přečíst +@msg the JPEG 2000 file can't be read soubor JPEG 2000 nelze přečíst +@msg the JPEG 2000 file has an unsupported color space or JPX content soubor JPEG 2000 obsahuje nepodporovaný barevný prostor nebo obsah JPX @msg the PSD image is too large to read ({_1} × {_2} pixels) obraz PSD je příliš velký na přečtení ({_1} × {_2} obrazových bodů) @msg zipped 32-bit PSD image data with prediction can't be read zazipovaná 32bitová obrazová data PSD s predikcí nelze přečíst @msg {depth}-bit PSD files in this colour mode can't be read {depth}bitové soubory PSD v tomto barevném režimu nelze přečíst diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 240bb8684d..80bd277fd3 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4640,6 +4640,8 @@ theme Appearance Erscheinungsbild @msg the PCX file is cut short die PCX-Datei ist unvollständig @msg the PCX file's header is damaged der Dateikopf der PCX-Datei ist beschädigt @msg PCX files with {bits}-bit pixels in {planes} planes can't be read PCX-Dateien mit {bits}-Bit-Pixeln in {planes} Ebenen können nicht gelesen werden +@msg the JPEG 2000 file can't be read die JPEG-2000-Datei kann nicht gelesen werden +@msg the JPEG 2000 file has an unsupported color space or JPX content die JPEG-2000-Datei enthält einen nicht unterstützten Farbraum oder JPX-Inhalt @msg the PSD image is too large to read ({_1} × {_2} pixels) das PSD-Bild ist zu groß zum Lesen ({_1} × {_2} Pixel) @msg zipped 32-bit PSD image data with prediction can't be read ZIP-komprimierte 32-Bit-PSD-Bilddaten mit Vorhersage können nicht gelesen werden @msg {depth}-bit PSD files in this colour mode can't be read {depth}-Bit-PSD-Dateien in diesem Farbmodus können nicht gelesen werden diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a4057ea1dc..bcea580dda 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4581,6 +4581,8 @@ theme Appearance Εμφάνιση @msg the PCX file is cut short το αρχείο PCX είναι περικομμένο @msg the PCX file's header is damaged η κεφαλίδα του αρχείου PCX είναι κατεστραμμένη @msg PCX files with {bits}-bit pixels in {planes} planes can't be read τα αρχεία PCX με εικονοστοιχεία {bits} bit σε {planes} επίπεδα δεν διαβάζονται +@msg the JPEG 2000 file can't be read δεν είναι δυνατή η ανάγνωση του αρχείου JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content το αρχείο JPEG 2000 έχει μη υποστηριζόμενο χρωματικό χώρο ή περιεχόμενο JPX @msg the PSD image is too large to read ({_1} × {_2} pixels) η εικόνα PSD είναι πολύ μεγάλη για ανάγνωση ({_1} × {_2} εικονοστοιχεία) @msg zipped 32-bit PSD image data with prediction can't be read τα συμπιεσμένα δεδομένα εικόνας PSD 32 bit με πρόβλεψη δεν διαβάζονται @msg {depth}-bit PSD files in this colour mode can't be read τα αρχεία PSD {depth} bit δεν διαβάζονται σε αυτήν τη λειτουργία χρώματος diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 2a77b567a4..e9555f3241 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4621,6 +4621,8 @@ axis Both Ambos @msg the PCX file is cut short el archivo PCX está incompleto @msg the PCX file's header is damaged el encabezado del archivo PCX está dañado @msg PCX files with {bits}-bit pixels in {planes} planes can't be read los archivos PCX con píxeles de {bits} bits en {planes} planos no se pueden leer +@msg the JPEG 2000 file can't be read no se puede leer el archivo JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content el archivo JPEG 2000 tiene un espacio de color o contenido JPX no compatible @msg the PSD image is too large to read ({_1} × {_2} pixels) la imagen PSD es demasiado grande para leerla ({_1} × {_2} píxeles) @msg zipped 32-bit PSD image data with prediction can't be read no se pueden leer datos de imagen PSD de 32 bits comprimidos en ZIP con predicción @msg {depth}-bit PSD files in this colour mode can't be read los archivos PSD de {depth} bits en este modo de color no se pueden leer diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 44af5c9fb7..58f8157bad 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4803,6 +4803,8 @@ imageTrace Outline Ääriviiva @msg the PCX file is cut short tämä PCX-tiedosto on katkennut @msg the PCX file's header is damaged PCX-tiedoston otsake on vahingoittunut @msg PCX files with {bits}-bit pixels in {planes} planes can't be read PCX-tiedostoja, joissa on {bits}-bittisiä pikseleitä {planes} tasossa, ei voi lukea +@msg the JPEG 2000 file can't be read tätä JPEG 2000 -tiedostoa ei voi lukea +@msg the JPEG 2000 file has an unsupported color space or JPX content tässä JPEG 2000 -tiedostossa on tukematon väriavaruus tai JPX-sisältö @msg the PSD image is too large to read ({_1} × {_2} pixels) tämä PSD-kuva on liian suuri luettavaksi ({_1} × {_2} pikseliä) @msg zipped 32-bit PSD image data with prediction can't be read ennustusta käyttävää zip-pakattua 32-bittistä PSD-kuvadataa ei voi lukea @msg {depth}-bit PSD files in this colour mode can't be read tässä väritilassa olevia {depth}-bittisiä PSD-tiedostoja ei voi lukea diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index abc63175f4..818a363e6a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4631,6 +4631,8 @@ axis Both Les deux @msg the PCX file is cut short le fichier PCX est tronqué @msg the PCX file's header is damaged l'en-tête du fichier PCX est endommagé @msg PCX files with {bits}-bit pixels in {planes} planes can't be read les fichiers PCX à pixels de {bits} bits sur {planes} plans ne peuvent pas être lus +@msg the JPEG 2000 file can't be read le fichier JPEG 2000 ne peut pas être lu +@msg the JPEG 2000 file has an unsupported color space or JPX content le fichier JPEG 2000 contient un espace colorimétrique ou un contenu JPX non pris en charge @msg the PSD image is too large to read ({_1} × {_2} pixels) l'image PSD est trop grande pour être lue ({_1} × {_2} pixels) @msg zipped 32-bit PSD image data with prediction can't be read les données d'image PSD 32 bits compressées en ZIP avec prédiction ne peuvent pas être lues @msg {depth}-bit PSD files in this colour mode can't be read les fichiers PSD {depth} bits dans ce mode colorimétrique ne peuvent pas être lus diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index db6960188e..6bb3bf986f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5144,6 +5144,8 @@ imageTrace Outline Körvonal @msg the PCX file is cut short a PCX-fájl csonka @msg the PCX file's header is damaged a PCX-fájl fejléce sérült @msg PCX files with {bits}-bit pixels in {planes} planes can't be read a {bits} bites pixeleket {planes} síkban tároló PCX-fájlok nem olvashatók +@msg the JPEG 2000 file can't be read a JPEG 2000 fájl nem olvasható +@msg the JPEG 2000 file has an unsupported color space or JPX content a JPEG 2000 fájl nem támogatott színteret vagy JPX-tartalmat tartalmaz @msg the PSD image is too large to read ({_1} × {_2} pixels) a PSD-kép túl nagy a beolvasáshoz ({_1} × {_2} pixel) @msg the Save PDF dialog didn't open a PDF mentése párbeszédablak nem nyílt meg @msg the scale is not a usable number a méretarány nem használható szám diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 618fce870f..ce6b0d70a1 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4661,6 +4661,8 @@ axis Both Entrambi @msg the PCX file is cut short il file PCX è troncato @msg the PCX file's header is damaged l'intestazione del file PCX è danneggiata @msg PCX files with {bits}-bit pixels in {planes} planes can't be read i file PCX con pixel a {bits} bit in {planes} piani non possono essere letti +@msg the JPEG 2000 file can't be read impossibile leggere il file JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content il file JPEG 2000 contiene uno spazio colore o un contenuto JPX non supportato @msg the PSD image is too large to read ({_1} × {_2} pixels) l'immagine PSD è troppo grande per essere letta ({_1} × {_2} pixel) @msg zipped 32-bit PSD image data with prediction can't be read i dati immagine PSD a 32 bit compressi ZIP con previsione non possono essere letti @msg {depth}-bit PSD files in this colour mode can't be read i file PSD a {depth} bit in questo metodo colore non possono essere letti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 30005d3c3a..69caf7f3a0 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4703,6 +4703,8 @@ swatch Bright Violet ビビッドバイオレット @msg the PCX file is cut short PCX ファイルが途中で切れています @msg the PCX file's header is damaged PCX ファイルのヘッダーが壊れています @msg PCX files with {bits}-bit pixels in {planes} planes can't be read {planes} プレーンに {bits} bit のピクセルを持つ PCX ファイルは読み込めません +@msg the JPEG 2000 file can't be read JPEG 2000 ファイルを読み込めません +@msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000 ファイルには未対応の色空間または JPX コンテンツがあります @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 画像が大きすぎて読み込めません({_1} × {_2} ピクセル) @msg zipped 32-bit PSD image data with prediction can't be read 予測付き ZIP 圧縮の 32 bit PSD 画像データは読み込めません @msg {depth}-bit PSD files in this colour mode can't be read このカラーモードの {depth} bit PSD ファイルは読み込めません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index ff40a494d5..134cc18084 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4340,6 +4340,8 @@ font-technology Variable ცვლადი @msg the PCX file is cut short PCX ფაილი შეკვეცილია @msg the PCX file's header is damaged PCX ფაილის სათაური დაზიანებულია @msg PCX files with {bits}-bit pixels in {planes} planes can't be read {planes} სიბრტყეში {bits}-ბიტიანი პიქსელების მქონე PCX ფაილების წაკითხვა ვერ ხერხდება +@msg the JPEG 2000 file can't be read JPEG 2000 ფაილის წაკითხვა შეუძლებელია +@msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000 ფაილს აქვს მხარდაუჭერელი ფერთა სივრცე ან JPX შიგთავსი @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD გამოსახულება ზედმეტად დიდია წასაკითხად ({_1} × {_2} პიქსელი) @msg zipped 32-bit PSD image data with prediction can't be read zip-ით შეკუმშული 32-ბიტიანი PSD გამოსახულების მონაცემების წაკითხვა პროგნოზირებით ვერ ხერხდება @msg {depth}-bit PSD files in this colour mode can't be read ამ ფერის რეჟიმში {depth}-ბიტიანი PSD ფაილების წაკითხვა ვერ ხერხდება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index d2f381afcb..6a12ca3638 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4631,6 +4631,8 @@ theme Appearance 외관 @msg the PCX file is cut short PCX 파일이 잘려 있습니다 @msg the PCX file's header is damaged PCX 파일의 헤더가 손상되었습니다 @msg PCX files with {bits}-bit pixels in {planes} planes can't be read {planes}개 평면에 {bits}비트 픽셀이 있는 PCX 파일은 읽을 수 없습니다 +@msg the JPEG 2000 file can't be read JPEG 2000 파일을 읽을 수 없습니다 +@msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000 파일에 지원되지 않는 색 공간 또는 JPX 콘텐츠가 있습니다 @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 이미지가 너무 커서 읽을 수 없습니다({_1} × {_2}픽셀) @msg zipped 32-bit PSD image data with prediction can't be read 예측이 적용된 ZIP 압축 32비트 PSD 이미지 데이터는 읽을 수 없습니다 @msg {depth}-bit PSD files in this colour mode can't be read 이 색상 모드의 {depth}비트 PSD 파일은 읽을 수 없습니다 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 092e5e9447..c153223376 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4727,6 +4727,8 @@ imageTrace Outline Kontur @msg the PCX file is cut short plik PCX jest ucięty @msg the PCX file's header is damaged nagłówek pliku PCX jest uszkodzony @msg PCX files with {bits}-bit pixels in {planes} planes can't be read nie można odczytać plików PCX z {bits}-bitowymi pikselami w {planes} płaszczyznach +@msg the JPEG 2000 file can't be read nie można odczytać pliku JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content plik JPEG 2000 zawiera nieobsługiwaną przestrzeń barw lub zawartość JPX @msg the PSD image is too large to read ({_1} × {_2} pixels) obraz PSD jest zbyt duży, aby go odczytać ({_1} × {_2} pikseli) @msg zipped 32-bit PSD image data with prediction can't be read nie można odczytać spakowanych 32-bitowych danych obrazu PSD z predykcją @msg {depth}-bit PSD files in this colour mode can't be read nie można odczytać {depth}-bitowych plików PSD w tym trybie koloru diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index d9a1a94f1e..4fd8e2bc5c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4164,6 +4164,8 @@ axis Both Ambos @msg the PCX file is cut short o arquivo PCX está incompleto @msg the PCX file's header is damaged o cabeçalho do arquivo PCX está danificado @msg PCX files with {bits}-bit pixels in {planes} planes can't be read arquivos PCX com pixels de {bits} bits em {planes} planos não podem ser lidos +@msg the JPEG 2000 file can't be read não é possível ler o arquivo JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content o arquivo JPEG 2000 contém um espaço de cores ou conteúdo JPX sem suporte @msg the PSD image is too large to read ({_1} × {_2} pixels) a imagem PSD é grande demais para ser lida ({_1} × {_2} pixels) @msg zipped 32-bit PSD image data with prediction can't be read dados de imagem PSD de 32 bits compactados em zip com previsão não podem ser lidos @msg {depth}-bit PSD files in this colour mode can't be read arquivos PSD de {depth} bits neste modo de cor não podem ser lidos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d364faf0a0..122bf5939b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4659,6 +4659,8 @@ axis Both Оба @msg the PCX file is cut short файл PCX обрезан @msg the PCX file's header is damaged заголовок файла PCX повреждён @msg PCX files with {bits}-bit pixels in {planes} planes can't be read файлы PCX с {bits}-битными пикселями в {planes} плоскостях не читаются +@msg the JPEG 2000 file can't be read не удается прочитать файл JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content файл JPEG 2000 содержит неподдерживаемое цветовое пространство или содержимое JPX @msg the PSD image is too large to read ({_1} × {_2} pixels) изображение PSD слишком велико для чтения ({_1} × {_2} пикс.) @msg zipped 32-bit PSD image data with prediction can't be read 32-битные данные изображения PSD со сжатием ZIP с предсказанием не читаются @msg {depth}-bit PSD files in this colour mode can't be read {depth}-битные файлы PSD в этом цветовом режиме не читаются diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e01793d233..711f1eab46 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4538,6 +4538,8 @@ axis Both Båda @msg the PCX file is cut short PCX-filen är avkortad @msg the PCX file's header is damaged PCX-filens huvud är skadat @msg PCX files with {bits}-bit pixels in {planes} planes can't be read PCX-filer med {bits}-bitars pixlar i {planes} plan kan inte läsas +@msg the JPEG 2000 file can't be read JPEG 2000-filen kan inte läsas +@msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000-filen har en färgrymd eller ett JPX-innehåll som inte stöds @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD-bilden är för stor för att läsas ({_1} × {_2} pixlar) @msg zipped 32-bit PSD image data with prediction can't be read zippad 32-bitars PSD-bilddata med prediktion kan inte läsas @msg {depth}-bit PSD files in this colour mode can't be read {depth}-bitars PSD-filer i det här färgläget kan inte läsas diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 32bb794bca..5f69d1acb6 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4381,6 +4381,8 @@ axis Both Her İkisi @msg the PCX file is cut short PCX dosyası kısa kesildi @msg the PCX file's header is damaged PCX dosyasının başlığı bozuk @msg PCX files with {bits}-bit pixels in {planes} planes can't be read {planes} düzlemde {bits}-bit pikseller içeren PCX dosyaları okunamaz +@msg the JPEG 2000 file can't be read JPEG 2000 dosyası okunamıyor +@msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000 dosyasında desteklenmeyen bir renk alanı veya JPX içeriği var @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD görüntüsü okunamayacak kadar büyük ({_1} × {_2} piksel) @msg zipped 32-bit PSD image data with prediction can't be read Tahmin içeren sıkıştırılmış 32 bit PSD görüntü verileri okunamıyor @msg {depth}-bit PSD files in this colour mode can't be read Bu renk modunda {depth}-bit PSD dosyaları okunamaz diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 835a75efcf..eb9d140161 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4645,6 +4645,8 @@ axis Both Обидві @msg the PCX file is cut short файл PCX обрізаний @msg the PCX file's header is damaged заголовок файлу PCX пошкоджений @msg PCX files with {bits}-bit pixels in {planes} planes can't be read файли PCX з {bits}-бітними пікселями в {planes} площинах не читаються +@msg the JPEG 2000 file can't be read не вдається прочитати файл JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content файл JPEG 2000 містить непідтримуваний колірний простір або вміст JPX @msg the PSD image is too large to read ({_1} × {_2} pixels) зображення PSD завелике для читання ({_1} × {_2} пікс.) @msg zipped 32-bit PSD image data with prediction can't be read 32-бітні дані зображення PSD зі стисненням ZIP із передбаченням не читаються @msg {depth}-bit PSD files in this colour mode can't be read {depth}-бітні файли PSD у цьому колірному режимі не читаються diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 6da79b33ea..f6b926e07f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4801,6 +4801,8 @@ theme Appearance Giao diện @msg the PCX file is cut short tệp PCX bị cắt ngắn @msg the PCX file's header is damaged phần đầu của tệp PCX bị hỏng @msg PCX files with {bits}-bit pixels in {planes} planes can't be read tệp PCX có điểm ảnh {bits}-bit trong {planes} mặt phẳng không thể đọc được +@msg the JPEG 2000 file can't be read không thể đọc tệp JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content tệp JPEG 2000 có không gian màu hoặc nội dung JPX không được hỗ trợ @msg the PSD image is too large to read ({_1} × {_2} pixels) ảnh PSD quá lớn để đọc ({_1} × {_2} pixel) @msg the Save PDF dialog didn't open hộp thoại Lưu PDF không mở @msg the scale is not a usable number tỷ lệ không phải là số dùng được diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 2912cf6d2a..96b5fbe0df 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4417,6 +4417,8 @@ imageTrace Outline 轮廓 @msg the PCX file is cut short PCX 文件不完整 @msg the PCX file's header is damaged PCX 文件头已损坏 @msg PCX files with {bits}-bit pixels in {planes} planes can't be read 无法读取 {planes} 个平面中含 {bits} 位像素的 PCX 文件 +@msg the JPEG 2000 file can't be read 无法读取 JPEG 2000 文件 +@msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000 文件包含不受支持的色彩空间或 JPX 内容 @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 图像过大,无法读取 ({_1} × {_2} 像素) @msg zipped 32-bit PSD image data with prediction can't be read 无法读取带预测的 ZIP 压缩 32 位 PSD 图像数据 @msg {depth}-bit PSD files in this colour mode can't be read 无法读取此颜色模式下的 {depth} 位 PSD 文件 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b814e29917..147c3b0432 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2349,6 +2349,8 @@ file-filter Templates 範本 @msg the PCX file is cut short PCX 檔案不完整 @msg the PCX file's header is damaged PCX 檔案標頭已損毀 @msg PCX files with {bits}-bit pixels in {planes} planes can't be read 無法讀取 {planes} 個平面中含 {bits} 位元像素的 PCX 檔案 +@msg the JPEG 2000 file can't be read 無法讀取 JPEG 2000 檔案 +@msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000 檔案包含不支援的色彩空間或 JPX 內容 @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 影像過大,無法讀取 ({_1} × {_2} 像素) @msg zipped 32-bit PSD image data with prediction can't be read 無法讀取使用預測的 ZIP 壓縮 32 位元 PSD 影像資料 @msg {depth}-bit PSD files in this colour mode can't be read 無法讀取此色彩模式的 {depth} 位元 PSD 檔案 diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index c01f0005e5..2d687384cb 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -17,7 +17,7 @@ from the public specifications, and users' own `.ai` files are used locally only | | Illustrator | VectorCraft | Notes | |---|---:|---:|---| -| Formats opened or placed | ~30 | 26 | missing: FreeHand, CorelDRAW, DWG, HEIC/HEIF, JPEG 2000, PICT, Pixar, Word `.doc`, PS | +| Formats opened or placed | ~30 | 27 | missing: FreeHand, CorelDRAW, DWG, HEIC/HEIF, PICT, Pixar, Word `.doc`, PS | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (no Illustrator editing data) or as legacy version 7 (layers and groups, one artboard per file) | | Formats exported | ~16 | 17 | missing: DWG, 3D (OBJ/USDA/glTF); extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | | **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting | @@ -105,8 +105,8 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (Targa: `.tga`, `.vda`, `.icb` and `.vst`, raw or run-length encoded, with a 16-bit file's one-bit alpha) | yes; TIFF is also selectable in Export for Screens and Asset Export with its existing options | Targa: `tests_tiffbmp.rs`, `tests/links.rs`; TIFF: grayscale with an alpha channel or other extra channels reads (#1466 in part), and so do files that store each channel as its own plane (PlanarConfiguration 2), CMYK ones with their ink amounts, and 1-bit files compressed with CCITT Group 3 (Compression 2 and 3, one- and two-dimensional rows); the ICC profiles embedded in JPEG and TIFF have 4-byte aligned tags (#1584); PNG export marks its colours as sRGB (`embedIcc`, an `sRGB` chunk; no ICC profile is embedded, #2221) | | WebP | export (Export for Screens) | yes | yes (lossless only; lossy written lossless with a warning) | | | HEIC / HEIF | open, place | no | no | | -| JPEG 2000 | open, place | no | no | | | PCX | open, place | yes (1 bit in the header palette's first two colors, black and white without them; 1 bit in two to four planes and 4 bits with up to 16 colors; 2 bits in the CGA colors the header's CGA palette settings pick; 8 bits with the 256-color palette, gray without one; 24-bit color in three planes) | no | the header's HDpi and VDpi size the image; a file of another depth or plane count, cut short or past the pixel allowance is refused with a message; tests in `crates/engine/src/cmd/fileio/tests_pcxread.rs` and `crates/engine/tests/import_fuzz.rs` | +| JPEG 2000 | open, place | yes (JP2 and raw codestream images; multiple codestreams and JPX composition or layers are refused) | no | `.jpf`, `.jpx`, `.jp2`, `.j2k`, `.j2c`, `.jpc`; resolution uses the last valid `resc` or `resd` value on each axis, or 72 ppi; bounded decoding; `tests_jp2read.rs` | | PICT, Pixar PXR | open, place (legacy) | no | no | rarely used | | FreeHand `.fh*` | open (legacy) | no | no | | | CorelDRAW `.cdr` | open | no | no | | diff --git a/docs/mcp.md b/docs/mcp.md index 1557555237..719ac6d40c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -427,7 +427,7 @@ objects' fills or strokes differ (`fillMixed` / `strokeMixed`, drawn as a "?" pr | `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. Includes UI commands such as `view.*` and `window.*` in remote mode. | | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | | `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. | -| `open_file` | `{path}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PNG, JPEG, GIF, WebP, TIFF, BMP, Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, PSD/PSB (an image opens as a document of its pixel size; a Photoshop file as its merged image). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). `run_command document.formats` lists the formats. | +| `open_file` | `{path}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PNG, JPEG, GIF, WebP, TIFF, BMP, Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), PSD/PSB (an image opens as a document of its pixel size; a Photoshop file as its merged image). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). `run_command document.formats` lists the formats. | | `save_file` | `{path?, compress?, version?, preview?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), and `preview: true` embeds a PNG of the first artboard. `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version` or `preview` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a `.ai` file reads `compress` but not `version` or `preview`). `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warning for a top-level `compress`, `version` or `preview`. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. | | `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF and WMF write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`); `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | @@ -3685,7 +3685,7 @@ image `object.rasterize` makes with the same options. ## Glass textures Glass (`distort.glass`) takes an image file as its surface in `params.textureImage`, as `{path}` or -`{name?, dataBase64}`: a PNG, JPEG, GIF, WebP, TIFF, BMP, Targa, PSD, PSB or PCX file, decoded within the pixel allowance the +`{name?, dataBase64}`: a PNG, JPEG, GIF, WebP, TIFF, BMP, Targa, PSD, PSB, PCX or JPEG 2000 file, decoded within the pixel allowance the renderer draws images in, counted as RGBA. `effect.apply` and `effect.setParams` store the image's gray levels in the effect as a grayscale PNG in base64 and set `texture: "loaded"` unless the params give a `texture`. `effect.list` reports the stored string, and a command given that string stores it unchanged. Any other string, a file that is not an image, or an image past diff --git a/docs/releasing.md b/docs/releasing.md index 449729420c..1ec5c221c4 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -164,7 +164,7 @@ to the target triple, so host build scripts aren't affected. AppStream metainfo, the MIME type for VectorCraft documents, the icons and the licence files. **Document types.** The desktop entry's `MimeType` lists every format File › Open reads but PSD, -PSB, `.ps` PostScript, Targa and PCX, so file managers list VectorCraft under Open With for them. +PSB, `.ps` PostScript, Targa, PCX and JPEG 2000, so file managers list VectorCraft under Open With for them. `ai.storyteller.vectorcraft.mime.xml` declares the types that shared-mime-info lacks: VectorCraft documents and templates, `.ait` templates and Affinity files (`application/x-affinity`). An `.af` file gets the Affinity type by its content, and `.afdesign` and `.afpub` files by their extension. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index caa6dbfb3c..6f0a426b26 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -144,7 +144,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers panel row context menus and Collect for Export (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated; document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), guides lost (#779), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC/JPEG 2000 import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), guides lost (#779), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. | | View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated; document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | | View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score unchanged | @@ -536,7 +536,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Artboard deletion keys:** Delete/Backspace delete selected boards in one Undo step, retaining the original first board in the current order when all are selected, as in the public [Delete artboards guide](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html). The last board and active drags stay protected; neither key clears selected artwork. Headless shortcut regressions in `tests/distortkeys.rs` cover reordered boards, artwork, saved state and Undo/Redo. - **Locked artboards:** a click in the Artboards panel's lock column locks or unlocks an artboard in one undo step (`artboard.setProps {index, locked}`), and the native format saves the lock. The Artboard tool doesn't move, copy, resize or delete a locked artboard, Rearrange and Fit to Artwork Bounds leave it as it is, and its name isn't edited on the canvas. The art on it (each object whose bounds overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, `select.set`, `select.all` and the tools pass over it, and commands that act on the selection leave it; art drawn or pasted onto it stays selected and editable until the selection leaves it out. Tests in `crates/doc/src/lib.rs`, `tests/panelcmds.rs`, `xform/artboard.rs`, `panels/artboards.rs` and `canvas.rs` cover them. Public references: [Lock artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/lock-artboards.html) and [Managing Artboards in Illustrator](https://creativepro.com/managing-artboards-in-illustrator/). - **Linux RPM packaging:** 64-bit runtime capabilities replace Fedora-specific required package names (#1275); glibc 2.35, libm and libgcc_s are declared alongside dynamically loaded xkbcommon and Vulkan/EGL. Generated x86_64/aarch64 metadata and isolated synthetic-provider resolution checked; real-distro install/start-up QA remains pending. -- **Linux file associations:** the desktop entry lists the MIME type of every format File › Open reads but PSD, PSB, `.ps` PostScript, Targa and PCX, `.ai`, `.ait` and EPS included, and the MIME package declares the types shared-mime-info lacks (VectorCraft documents and templates, `.ait`, Affinity), so file managers list VectorCraft under Open With for them, as Finder does on macOS. `the_linux_desktop_entry_opens_every_readable_format` in `apps/vectorcraft/src/main.rs` checks both files against `OPEN_EXTS`. On Debian 13, Ubuntu 24.04 and Fedora 42, `desktop-file-validate` accepts the desktop entry, `update-mime-database` accepts the MIME package, and `gio` registers the app for every one of these types. +- **Linux file associations:** the desktop entry lists the MIME type of every format File › Open reads but PSD, PSB, `.ps` PostScript, Targa, PCX and JPEG 2000, `.ai`, `.ait` and EPS included, and the MIME package declares the types shared-mime-info lacks (VectorCraft documents and templates, `.ait`, Affinity), so file managers list VectorCraft under Open With for them, as Finder does on macOS. `the_linux_desktop_entry_opens_every_readable_format` in `apps/vectorcraft/src/tests.rs` checks both files against `OPEN_EXTS`. On Debian 13, Ubuntu 24.04 and Fedora 42, `desktop-file-validate` accepts the desktop entry, `update-mime-database` accepts the MIME package, and `gio` registers the app for every one of these types. - **Architecture:** 19+ crates with enforced layering (`cargo xtask layers`). Every action is a command (~400 engine + ~50 UI). Undo is unlimited via structural sharing. `command.batch` runs several commands as one transaction. - **Automation:** @@ -1059,6 +1059,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - EPS export with Use Artboards writes a central EPS file of the whole document, bounded by its visible art, beside the file of each artboard when it writes two or more artboards; a document with no visible art gets only the artboard files (`crates/engine/src/cmd/fileio/tests_eps.rs`). - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - PCX files (`.pcx`) open and place, from the ZSoft PCX Technical Reference Manual: 1 bit in the header palette's first two colors (black and white when the version has no palette or both colors are the same), 1 bit in two to four planes and 4 bits with up to 16 colors from the header's palette (the EGA colors for versions 0 and 3), 2 bits in the CGA colors that the header's CGA palette settings pick (background, color burst, palette and intensity), 8 bits with the 256-color palette after the image data (gray levels without one) and 24-bit color in three planes, run-length encoded. The header's HDpi and VDpi size the image. A file of another depth or plane count, one cut short, and one whose pixels as RGBA pass the pixel allowance are refused with a message before its pixels are decoded. Open and Place recognize a PCX file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a PCX file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_pcxread.rs`). + - JPEG 2000 JP2 and raw codestream images open and place from `.jpf`, `.jpx`, `.jp2`, `.j2k`, `.j2c` and `.jpc`. The last valid `resc` or `resd` resolution value wins on each axis; an axis with none uses 72 ppi. Multiple codestreams, JPX composition or layers, and unsupported color spaces are refused with a message. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_jp2read.rs`). - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). - TIFFs that store each channel as its own plane (PlanarConfiguration 2) place, relink and open as the same image stored pixel by pixel does, 8 and 16 bits: grayscale with an alpha channel or other extra channels, and CMYK with or without them. A planar CMYK TIFF keeps its ink amounts and is stored as a CMYK TIFF with each pixel's inks together, at the file's resolution. A TIFF whose header claims more strips or tiles than can be counted is refused as too large to draw (#1466 in part; `crates/engine/src/cmd/fileio/tests.rs`). - 1-bit TIFFs compressed with CCITT Group 3 (ITU-T T.4) place, relink and open: Compression 2 (modified Huffman) and Compression 3 with one-dimensional rows or, with T4Options bit 0, two-dimensional ones, with or without fill bits, in strips or tiles, with either FillOrder and either polarity. Rows in T.4's uncompressed mode are not read. A file whose pixels would take more than the decoding allowance as RGBA is refused as too large to draw (#1466 in part; `crates/engine/src/cmd/fileio/tests.rs`). @@ -1169,7 +1170,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Moving objects with raster effects (#1257):** during a drag or a dialog's preview, an object whose content only moved draws its cached drop shadows, outer glows and filtered content (Gaussian Blur, Feather and the Photoshop-style filters) from the rasters of an earlier frame at the nearest whole pixel, without running the effects again. The renderer first draws the moved content where the old content lies in its raster and compares the pixels. De-Interlace runs again. The frame after the drag runs the effects again and draws what a fresh renderer draws; on the desktop, the canvas renders that frame on the render worker. `texture_drag_perf` times a drag's frames and the frame after it. -- **Glass's Load Texture:** Effect › Distort › Glass… has a Load Texture… button that reads a PNG, JPEG, GIF, WebP, TIFF, BMP, Targa, PSD, PSB or PCX file and adds Loaded Texture to the Texture menu (`textureImage`: `{path}` or `{name?, dataBase64}`, stored in the effect and saved with the document as a grayscale PNG in base64). The texture lies one image pixel per point at Scaling 100%, centered on the object and repeated; each pixel's luma is the surface's height, from 0 for black to 1 pt for white, and a transparent pixel counts as middle gray. Scaling and Invert act on it as on the built-in textures. A Glass saved without `textureImage` draws and saves as before. +- **Glass's Load Texture:** Effect › Distort › Glass… has a Load Texture… button that reads a PNG, JPEG, GIF, WebP, TIFF, BMP, Targa, PSD, PSB, PCX or JPEG 2000 file and adds Loaded Texture to the Texture menu (`textureImage`: `{path}` or `{name?, dataBase64}`, stored in the effect and saved with the document as a grayscale PNG in base64). The texture lies one image pixel per point at Scaling 100%, centered on the object and repeated; each pixel's luma is the surface's height, from 0 for black to 1 pt for white, and a transparent pixel counts as middle gray. Scaling and Invert act on it as on the built-in textures. A Glass saved without `textureImage` draws and saves as before. - **Bounded effect length inputs (#4638):** Effect dialog fields with defined length ranges (such as Color Halftone Max Radius 4..127 pt) clamp immediately on commit and reject invalid inputs visibly with an accent highlight without reverting to sub-minimum values. - **Raster effects after document and view changes:** a cached drop shadow, outer glow or filtered content is made again when something its content reads from outside the object changes: a pattern's art or tiling, a symbol shown inside another symbol, a brush definition, an image's pixels, the raster resolution (De-Interlace), Page Knockout Group, the substitution highlights (Highlight Substituted Fonts and Highlight Alternate Glyphs in Preferences › Type, Highlight Substituted Glyphs in Document Setup), a layer's Dim Images, the color settings, the fonts, Pixel Preview, Anti-aliased Artwork, Overprint Preview and isolation mode. A thumbnail under Color Halftone or Mezzotint is made again when the document's color mode changes. Raster effects (blur, shadow, glow, grain) drawn after a pattern, radial or freeform gradient fill export at their place and size (#1541, fixes #1536). From f8bba3388e2fc546f24387eedc2087ca2acffeba Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 15:50:14 -0700 Subject: [PATCH 141/260] Batch: data set files name by File + Number, File + Data Set Name or Data Set Name The Batch dialog has a File Name choice for a Data Sets source, starting with File + Number (`source001`), as well as File + Data Set Name (`source_Alpha`) and Data Set Name (`Alpha`). `action.batch` takes it as `datasetFileNaming`; a call without it keeps File + Data Set Name, and a folder source ignores it. An unknown value is an error. A data set output whose name already exists in the destination folder now takes the next free `-2`, `-3` suffix instead of replacing the file, and a Windows device name under Data Set Name gets a trailing `-`. --- crates/engine/src/cmd/fileio/action_batch.rs | 212 ++++++++++++++++++- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/ui-egui/src/dialogs/action_batch.rs | 135 +++++++++--- crates/ui-egui/src/i18n/bg.tsv | 5 + crates/ui-egui/src/i18n/bs.tsv | 5 + crates/ui-egui/src/i18n/ca.tsv | 5 + crates/ui-egui/src/i18n/cs.tsv | 5 + crates/ui-egui/src/i18n/da.tsv | 5 + crates/ui-egui/src/i18n/de.tsv | 5 + crates/ui-egui/src/i18n/el.tsv | 5 + crates/ui-egui/src/i18n/es.tsv | 5 + crates/ui-egui/src/i18n/fi.tsv | 5 + crates/ui-egui/src/i18n/fr.tsv | 5 + crates/ui-egui/src/i18n/hu.tsv | 5 + crates/ui-egui/src/i18n/id.tsv | 5 + crates/ui-egui/src/i18n/it.tsv | 5 + crates/ui-egui/src/i18n/ja.tsv | 5 + crates/ui-egui/src/i18n/ka.tsv | 5 + crates/ui-egui/src/i18n/ko.tsv | 5 + crates/ui-egui/src/i18n/nl.tsv | 5 + crates/ui-egui/src/i18n/pl.tsv | 5 + crates/ui-egui/src/i18n/pt-br.tsv | 5 + crates/ui-egui/src/i18n/ru.tsv | 5 + crates/ui-egui/src/i18n/sv.tsv | 5 + crates/ui-egui/src/i18n/tr.tsv | 5 + crates/ui-egui/src/i18n/uk.tsv | 5 + crates/ui-egui/src/i18n/vi.tsv | 5 + crates/ui-egui/src/i18n/zh-hans.tsv | 5 + crates/ui-egui/src/i18n/zh-hant.tsv | 5 + docs/mcp.md | 25 ++- docs/target-app-parity.md | 2 + 31 files changed, 452 insertions(+), 54 deletions(-) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index d1db603025..f2310962ee 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -93,7 +93,7 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> { }; match source { "folder" => batch_folder(s, C, p, override_open, &run), - "datasets" => batch_datasets(s, C, &run), + "datasets" => batch_datasets(s, C, &run, p), _ => Err(bad(C, "`source` must be `folder` or `datasets`")), } } @@ -134,10 +134,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: } #[cfg(not(target_arch = "wasm32"))] -fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result<Value> { - use super::distinct_names; - use super::screens::file_part; - +fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>, p: &Value) -> Result<Value> { let st = s.doc()?; let names: Vec<String> = st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect(); if names.is_empty() { @@ -147,11 +144,8 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result<Value> { return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} data sets"))); } let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string(); - // Data set files are named File + Data Set Name (helpx, for Override Save/Export; the folder - // destination uses the same name). `file_part` writes the characters Windows does not allow in a - // file name (`/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters) in the data set's - // name as `-`, and `distinct_names` adds `-2`, `-3`… to a name an earlier data set used. - let stems = distinct_names(names.iter().map(|name| format!("{doc_stem}_{}", file_part(name)))); + let naming = p.get("datasetFileNaming").map_or("fileDataSetName", |v| v.as_str().unwrap_or("")); + let stems = dataset_stems(&names, &doc_stem, naming, run)?; let steps = filter_steps(run.steps, true, false); let run = Run { steps: &steps, ..*run }; let mut processed = Vec::new(); @@ -240,6 +234,68 @@ fn finish_destination(s: &mut Session, run: &Run<'_>, stem: &str, ext: &str, sou } } +/// Builds the three data set naming forms, replaces unsafe name characters, and adds `-2`, `-3` +/// suffixes when a stem was used earlier or its output already exists in the destination folder. +#[cfg(not(target_arch = "wasm32"))] +fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>) -> Result<Vec<String>> { + use super::screens::{file_part, safe_file_name}; + + if !matches!(naming, "fileNumber" | "fileDataSetName" | "dataSetName") { + return Err(bad("action.batch", "`datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName`")); + } + let bases = names.iter().enumerate().map(|(i, name)| { + let safe = file_part(name); + let safe_data_set = safe_file_name(&safe); + match naming { + "fileNumber" => format!("{doc_stem}{:03}", i + 1), + "dataSetName" if !safe_data_set.is_empty() => safe_data_set, + "dataSetName" => format!("{doc_stem}{:03}", i + 1), + _ => format!("{doc_stem}_{safe}"), + } + }); + let extensions = dataset_output_extensions(run); + let mut taken = std::collections::HashSet::new(); + let mut stems = Vec::with_capacity(bases.len()); + for base in bases { + let mut candidate = base.clone(); + let mut suffix = 2; + while taken.contains(&candidate.to_lowercase()) || dataset_output_exists(run.dest_folder, &candidate, &extensions) { + if suffix > 10_000 { + return Err(bad("action.batch", "no free data set file name in destination folder")); + } + candidate = format!("{base}-{suffix}"); + suffix += 1; + } + taken.insert(candidate.to_lowercase()); + stems.push(candidate); + } + Ok(stems) +} + +#[cfg(not(target_arch = "wasm32"))] +fn dataset_output_extensions(run: &Run<'_>) -> Vec<String> { + let mut extensions = Vec::new(); + if run.destination == "folder" { + extensions.push("vectorcraft".to_string()); + } + for step in run.steps { + let id = step.get("command").and_then(Value::as_str).unwrap_or(""); + let writes = (run.override_save && matches!(id, "document.save" | "file.save" | "file.saveAs")) + || (run.override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection")); + if writes { + let ext = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty()); + extensions.push(ext.map_or_else(|| "vectorcraft".to_string(), format_extension)); + } + } + extensions +} + +#[cfg(not(target_arch = "wasm32"))] +fn dataset_output_exists(folder: Option<&str>, stem: &str, extensions: &[String]) -> bool { + let Some(folder) = folder else { return false }; + extensions.iter().any(|ext| std::path::Path::new(folder).join(format!("{stem}.{ext}")).exists()) +} + /// Save when the extension is a Save format; otherwise export (PNG, JPEG…). /// `as_copy`: `file.saveCopy` so the open document keeps its path (data-set batches). #[cfg(not(target_arch = "wasm32"))] @@ -548,6 +604,142 @@ mod tests { s } + fn named_batch(s: &mut Session, dest: &std::path::Path, naming: Option<&str>) -> Value { + let mut p = json!({ + "source": "datasets", "destination": "folder", "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "object.unlockAll", "params": {}}] + }); + if let Some(naming) = naming { + p["datasetFileNaming"] = json!(naming); + } + s.execute("action.batch", &p).unwrap() + } + + #[test] + fn batch_data_set_naming_choices_and_omitted_default() { + for (i, (naming, want)) in [ + (Some("fileNumber"), ["source001.vectorcraft", "source002.vectorcraft"]), + (Some("fileDataSetName"), ["source_Alpha.vectorcraft", "source_Beta.vectorcraft"]), + (Some("dataSetName"), ["Alpha.vectorcraft", "Beta.vectorcraft"]), + (None, ["source_Alpha.vectorcraft", "source_Beta.vectorcraft"]), + ] + .into_iter() + .enumerate() + { + let dest = tmp(&format!("choice-{i}")); + let mut s = with_data_sets(&["Alpha", "Beta"]); + let saved = tmp(&format!("saved-{i}")).join("source.vectorcraft"); + s.execute("document.save", &json!({"path": saved.to_string_lossy()})).unwrap(); + let r = named_batch(&mut s, &dest, naming); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(file_names(&dest), want, "{naming:?}: {r}"); + } + } + + #[test] + fn batch_file_number_uses_three_digits_through_500() { + let names: Vec<String> = (1..=500).map(|n| format!("Set {n}")).collect(); + let run = Run { + label: "Test", + steps: &[], + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: None, + }; + let stems = dataset_stems(&names, "source", "fileNumber", &run).unwrap(); + for n in [1, 2, 10, 100, 500] { + assert_eq!(stems[n - 1], format!("source{n:03}")); + } + } + + #[test] + fn batch_unsaved_data_set_names_and_empty_fallback() { + let dest = tmp("unsaved-number"); + let mut s = with_data_sets(&["Alpha"]); + assert_eq!(named_batch(&mut s, &dest, Some("fileNumber"))["failed"], 0); + assert_eq!(file_names(&dest), ["Untitled001.vectorcraft"]); + let dest = tmp("unsaved-name"); + assert_eq!(named_batch(&mut s, &dest, Some("fileDataSetName"))["failed"], 0); + assert_eq!(file_names(&dest), ["Untitled_Alpha.vectorcraft"]); + let run = Run { + label: "Test", + steps: &[], + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: None, + }; + assert_eq!(dataset_stems(&[String::new()], "Untitled", "dataSetName", &run).unwrap(), ["Untitled001"]); + assert_eq!(dataset_stems(&[" ".to_string()], "Untitled", "dataSetName", &run).unwrap(), ["Untitled001"]); + } + + #[test] + fn batch_data_set_name_collisions_and_existing_files() { + let clear = tmp("choice-collision-clear"); + let mut s = with_data_sets(&["a:b", "a-b"]); + let r = named_batch(&mut s, &clear, Some("dataSetName")); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(file_names(&clear), ["a-b-2.vectorcraft", "a-b.vectorcraft"]); + let dest = tmp("choice-collision"); + std::fs::write(dest.join("a-b.vectorcraft"), b"keep").unwrap(); + let mut s = with_data_sets(&["a:b", "a-b"]); + let r = named_batch(&mut s, &dest, Some("dataSetName")); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(dest.join("a-b.vectorcraft")).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["a-b-2.vectorcraft", "a-b-3.vectorcraft", "a-b.vectorcraft"]); + } + + #[test] + fn batch_data_set_name_avoids_windows_device_files() { + let dest = tmp("choice-device"); + let mut s = with_data_sets(&["CON"]); + let r = named_batch(&mut s, &dest, Some("dataSetName")); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(file_names(&dest), ["CON-.vectorcraft"]); + } + + #[test] + fn batch_override_export_keeps_existing_output() { + let dest = tmp("choice-existing-export"); + std::fs::write(dest.join("Alpha.svg"), b"keep").unwrap(); + let mut s = with_data_sets(&["Alpha"]); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.export", "params": {"format": "svg"}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(dest.join("Alpha.svg")).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-2.svg", "Alpha.svg"]); + } + + #[test] + fn batch_rejects_unknown_data_set_naming_but_ignores_it_for_folders() { + let mut s = with_data_sets(&["Alpha"]); + let e = s + .execute("action.batch", &json!({"source": "datasets", "datasetFileNaming": "other", "commands": [{"command": "object.unlockAll"}]})) + .unwrap_err(); + let msg = e.to_string(); + for value in ["fileNumber", "fileDataSetName", "dataSetName"] { + assert!(msg.contains(value), "{msg}"); + } + assert!( + s.execute("action.batch", &json!({"source": "datasets", "datasetFileNaming": 7, "commands": [{"command": "object.unlockAll"}]})).is_err() + ); + let src = tmp("folder-ignore-src"); + write_svg(&src, "one.svg", "#f00"); + let r = s.execute("action.batch", &json!({"source": "folder", "folder": src.to_string_lossy(), "datasetFileNaming": "other", "commands": [{"command": "object.unlockAll"}]})).unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + } + #[test] fn batch_keeps_data_set_files_inside_the_destination_folder() { let root = tmp("set-names-root"); diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index abd6857adc..ba39d0bdb1 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document (source: datasets; File + Data Set Name for the folder destination and Override Save/Export, with `/`, `\\`, `:`, `<`, `>`, `\"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and `-2`, `-3`… added to a name already used). Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or present in the destination folder gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}", always, action_batch::action_batch ), diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index 01c27b98aa..3464fad755 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -21,26 +21,28 @@ pub fn open(app: &mut VectorcraftApp, set: usize, action: usize) -> Result<Value return Err("the action has no steps".into()); } let name = a.name.clone(); - app.ui.dialog = Some(Dialog::new( - KIND, - json!({ - "set": set, - "action": action, - "actionName": name, - "source": "folder", - "folder": "", - "includeSubdirs": false, - "destination": "folder", - "destinationFolder": "", - "overrideOpen": true, - "overrideSave": true, - "overrideExport": true, - "stopOnError": true, - }), - )); + app.ui.dialog = Some(Dialog::new(KIND, initial_fields(set, action, &name))); Ok(Value::Null) } +fn initial_fields(set: usize, action: usize, name: &str) -> Value { + json!({ + "set": set, + "action": action, + "actionName": name, + "source": "folder", + "datasetFileNaming": "fileNumber", + "folder": "", + "includeSubdirs": false, + "destination": "folder", + "destinationFolder": "", + "overrideOpen": true, + "overrideSave": true, + "overrideExport": true, + "stopOnError": true, + }) +} + fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let t = Tokens::get(ui.ctx()); ui.label(egui::RichText::new(d.str("actionName")).color(t.text_strong)); @@ -58,6 +60,14 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { form::check(ui, d, "includeSubdirs", "Include All Subdirectories"); } else { ui.label(egui::RichText::new(tl!("Uses every data set of the open document.")).size(11.5).color(t.text_dim)); + form::choice( + ui, + d, + "datasetFileNaming", + "File Name:", + (LABEL, 200.0), + &[("fileNumber", "File + Number"), ("fileDataSetName", "File + Data Set Name"), ("dataSetName", "Data Set Name")], + ); } ui.add_space(8.0); @@ -95,23 +105,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { if source == "datasets" && app.session.active().is_none() { return Err("open a document with data sets".into()); } - let mut params = json!({ - "commands": commands, - "label": a.name, - "source": source, - "destination": destination, - "overrideOpen": d.bool("overrideOpen"), - "overrideSave": d.bool("overrideSave"), - "overrideExport": d.bool("overrideExport"), - "stopOnError": d.bool("stopOnError"), - "includeSubdirs": d.bool("includeSubdirs"), - }); - if source == "folder" { - params["folder"] = json!(d.str("folder")); - } - if destination == "folder" { - params["destinationFolder"] = json!(d.str("destinationFolder")); - } + let params = params(d, &a.name, commands); let r = app.run("action.batch", params)?; app.ui.dialog = None; let count = r["count"].as_u64().unwrap_or(0); @@ -123,3 +117,76 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { } Ok(r) } + +fn params(d: &Dialog, action_name: &str, commands: Vec<Value>) -> Value { + let source = d.str("source"); + let destination = d.str("destination"); + let mut params = json!({ + "commands": commands, + "label": action_name, + "source": source, + "destination": destination, + "overrideOpen": d.bool("overrideOpen"), + "overrideSave": d.bool("overrideSave"), + "overrideExport": d.bool("overrideExport"), + "stopOnError": d.bool("stopOnError"), + "includeSubdirs": d.bool("includeSubdirs"), + }); + if source == "folder" { + params["folder"] = json!(d.str("folder")); + } else if source == "datasets" { + params["datasetFileNaming"] = json!(d.str("datasetFileNaming")); + } + if destination == "folder" { + params["destinationFolder"] = json!(d.str("destinationFolder")); + } + params +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn shown(source: &str) -> Vec<String> { + fn collect(shape: &egui::Shape, out: &mut Vec<String>) { + match shape { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, out)), + _ => {} + } + } + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test")); + d.fields["source"] = json!(source); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut frame = ctx.run_ui(Default::default(), |ui| { + body(&mut app, ui, &mut d); + }); + frame.textures_delta.clear(); + let mut labels = vec![]; + frame.shapes.iter().for_each(|shape| collect(&shape.shape, &mut labels)); + labels + } + + #[test] + fn file_name_choice_shows_only_for_data_sets() { + assert!(shown("datasets").iter().any(|label| label == "File Name:")); + assert!(shown("datasets").iter().any(|label| label == "File + Number")); + assert!(!shown("folder").iter().any(|label| label == "File Name:")); + } + + #[test] + fn data_set_naming_params_follow_dialog_choice() { + let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test")); + assert_eq!(d.str("datasetFileNaming"), "fileNumber"); + d.fields["source"] = json!("datasets"); + for choice in ["fileNumber", "fileDataSetName", "dataSetName"] { + d.fields["datasetFileNaming"] = json!(choice); + assert_eq!(params(&d, "Test", vec![])["datasetFileNaming"], choice); + } + d.fields["source"] = json!("folder"); + assert!(params(&d, "Test", vec![]).get("datasetFileNaming").is_none()); + } +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index fbb0019ec4..0becb7e965 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5860,6 +5860,11 @@ breakText Glyphs Глифи @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` трябва да е lines, paragraphs, words или glyphs, а не {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` трябва да е "line" или "paragraph", а не {other} @msg `align` must be "left", "center" or "right", not {other} `align` трябва да е "left", "center" или "right", а не {other} + File + Number Файл + номер + File + Data Set Name Файл + име на набора от данни + Data Set Name Име на набора от данни +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` трябва да е `fileNumber`, `fileDataSetName` или `dataSetName` +@msg no free data set file name in destination folder Няма свободно име за файл на набор от данни в целевата папка # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Mode Режим diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d5f5e6dad5..b1635dc7bf 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5869,6 +5869,11 @@ swatch Yellow Green Žuto-zelena Position: Položaj: Font Size: Veličina fonta: shape Open Otvoren + File + Number Datoteka + broj + File + Data Set Name Datoteka + naziv skupa podataka + Data Set Name Naziv skupa podataka +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` mora biti `fileNumber`, `fileDataSetName` ili `dataSetName` +@msg no free data set file name in destination folder Nema slobodnog naziva datoteke skupa podataka u odredišnoj mapi # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Retract Handles Uvuci ručke diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 4f2d7c6164..b875d10672 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5966,6 +5966,11 @@ breakText Glyphs Glifs @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` ha de ser lines, paragraphs, words o glyphs, no {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` ha de ser "line" o "paragraph", no {other} @msg `align` must be "left", "center" or "right", not {other} `align` ha de ser "left", "center" o "right", no {other} + File + Number Fitxer + número + File + Data Set Name Fitxer + nom del conjunt de dades + Data Set Name Nom del conjunt de dades +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` ha de ser `fileNumber`, `fileDataSetName` o `dataSetName` +@msg no free data set file name in destination folder No hi ha cap nom de fitxer de conjunt de dades lliure a la carpeta de destinació # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Efectes de traçat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index ab09e818aa..6452812168 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5977,6 +5977,11 @@ breakText Glyphs Glyfy @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` musí být lines, paragraphs, words nebo glyphs, ne {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` musí být "line" nebo "paragraph", ne {other} @msg `align` must be "left", "center" or "right", not {other} `align` musí být "left", "center" nebo "right", ne {other} + File + Number Soubor + číslo + File + Data Set Name Soubor + název sady dat + Data Set Name Název sady dat +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` musí být `fileNumber`, `fileDataSetName` nebo `dataSetName` +@msg no free data set file name in destination folder V cílové složce není volný název souboru sady dat # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Efekty cesty diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b7c6e23fda..fb80dcc0c7 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5875,6 +5875,11 @@ breakText Glyphs Glyffer @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` skal være lines, paragraphs, words eller glyphs, ikke {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` skal være "line" eller "paragraph", ikke {other} @msg `align` must be "left", "center" or "right", not {other} `align` skal være "left", "center" eller "right", ikke {other} + File + Number Fil + nummer + File + Data Set Name Fil + datasætnavn + Data Set Name Datasætnavn +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` skal være `fileNumber`, `fileDataSetName` eller `dataSetName` +@msg no free data set file name in destination folder Intet ledigt filnavn til datasættet i destinationsmappen # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Kurveeffekter diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 80bd277fd3..1ea0d5f0d9 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5562,6 +5562,11 @@ breakText Glyphs Glyphen @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` muss lines, paragraphs, words oder glyphs sein, nicht {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` muss "line" oder "paragraph" sein, nicht {other} @msg `align` must be "left", "center" or "right", not {other} `align` muss "left", "center" oder "right" sein, nicht {other} + File + Number Datei + Nummer + File + Data Set Name Datei + Datensatzname + Data Set Name Datensatzname +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` muss `fileNumber`, `fileDataSetName` oder `dataSetName` sein +@msg no free data set file name in destination folder Kein freier Dateiname für den Datensatz im Zielordner # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Pfadeffekte diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bcea580dda..383e9b4343 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5929,6 +5929,11 @@ breakText Glyphs Γλύφοι @msg `by` must be lines, paragraphs, words or glyphs, not {other} το `by` πρέπει να είναι lines, paragraphs, words ή glyphs, όχι {other} @msg `kind` must be "line" or "paragraph", not {other} το `kind` πρέπει να είναι "line" ή "paragraph", όχι {other} @msg `align` must be "left", "center" or "right", not {other} το `align` πρέπει να είναι "left", "center" ή "right", όχι {other} + File + Number Αρχείο + αριθμός + File + Data Set Name Αρχείο + όνομα συνόλου δεδομένων + Data Set Name Όνομα συνόλου δεδομένων +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` Το `datasetFileNaming` πρέπει να είναι `fileNumber`, `fileDataSetName` ή `dataSetName` +@msg no free data set file name in destination folder Δεν υπάρχει διαθέσιμο όνομα αρχείου συνόλου δεδομένων στον φάκελο προορισμού # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Mode Λειτουργία diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index e9555f3241..80d54c074e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5920,6 +5920,11 @@ breakText Glyphs Glifos @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` debe ser lines, paragraphs, words o glyphs, no {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` debe ser "line" o "paragraph", no {other} @msg `align` must be "left", "center" or "right", not {other} `align` debe ser "left", "center" o "right", no {other} + File + Number Archivo + número + File + Data Set Name Archivo + nombre del conjunto de datos + Data Set Name Nombre del conjunto de datos +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` debe ser `fileNumber`, `fileDataSetName` o `dataSetName` +@msg no free data set file name in destination folder No hay un nombre de archivo libre para el conjunto de datos en la carpeta de destino # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Efectos de trazado diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 58f8157bad..ef924d1731 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6008,6 +6008,11 @@ breakText Glyphs Merkit @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` on oltava lines, paragraphs, words tai glyphs, ei {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` on oltava "line" tai "paragraph", ei {other} @msg `align` must be "left", "center" or "right", not {other} `align` on oltava "left", "center" tai "right", ei {other} + File + Number Tiedosto + numero + File + Data Set Name Tiedosto + tietojoukon nimi + Data Set Name Tietojoukon nimi +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming`-arvon on oltava `fileNumber`, `fileDataSetName` tai `dataSetName` +@msg no free data set file name in destination folder Kohdekansiossa ei ole vapaata tietojoukon tiedostonimeä # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Polkutehosteet diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 818a363e6a..7d5fe46b1e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5975,6 +5975,11 @@ breakText Glyphs Glyphes @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` doit valoir lines, paragraphs, words ou glyphs, et non {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` doit valoir "line" ou "paragraph", et non {other} @msg `align` must be "left", "center" or "right", not {other} `align` doit valoir "left", "center" ou "right", et non {other} + File + Number Fichier + numéro + File + Data Set Name Fichier + nom du jeu de données + Data Set Name Nom du jeu de données +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` doit être `fileNumber`, `fileDataSetName` ou `dataSetName` +@msg no free data set file name in destination folder Aucun nom de fichier libre pour le jeu de données dans le dossier de destination # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Effets de tracé diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 6bb3bf986f..0d71cbb8ae 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5964,6 +5964,11 @@ breakText Glyphs Glifák @msg `by` must be lines, paragraphs, words or glyphs, not {other} a `by` értéke lines, paragraphs, words vagy glyphs lehet, nem {other} @msg `kind` must be "line" or "paragraph", not {other} a `kind` értéke "line" vagy "paragraph" lehet, nem {other} @msg `align` must be "left", "center" or "right", not {other} az `align` értéke "left", "center" vagy "right" lehet, nem {other} + File + Number Fájl + szám + File + Data Set Name Fájl + adatkészlet neve + Data Set Name Adatkészlet neve +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` A `datasetFileNaming` értéke `fileNumber`, `fileDataSetName` vagy `dataSetName` lehet +@msg no free data set file name in destination folder Nincs szabad adatkészlet-fájlnév a célmappában # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Útvonaleffektusok diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 664551a1fa..bfa0660240 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5875,6 +5875,11 @@ breakText Glyphs Glif @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` harus lines, paragraphs, words, atau glyphs, bukan {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` harus "line" atau "paragraph", bukan {other} @msg `align` must be "left", "center" or "right", not {other} `align` harus "left", "center", atau "right", bukan {other} + File + Number File + nomor + File + Data Set Name File + nama set data + Data Set Name Nama set data +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` harus `fileNumber`, `fileDataSetName`, atau `dataSetName` +@msg no free data set file name in destination folder Tidak ada nama file set data yang tersedia di folder tujuan # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Efek jalur diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ce6b0d70a1..2c587de487 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5596,6 +5596,11 @@ breakText Glyphs Glifi @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` deve essere lines, paragraphs, words o glyphs, non {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` deve essere "line" o "paragraph", non {other} @msg `align` must be "left", "center" or "right", not {other} `align` deve essere "left", "center" o "right", non {other} + File + Number File + numero + File + Data Set Name File + nome set di dati + Data Set Name Nome set di dati +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` deve essere `fileNumber`, `fileDataSetName` o `dataSetName` +@msg no free data set file name in destination folder Nessun nome file libero per il set di dati nella cartella di destinazione # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Effetti tracciato diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 69caf7f3a0..0326a5c841 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5662,6 +5662,11 @@ breakText Glyphs 字形 @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` は lines、paragraphs、words、glyphs のいずれかにしてください({other} は使用できません) @msg `kind` must be "line" or "paragraph", not {other} `kind` は "line" または "paragraph" にしてください({other} は使用できません) @msg `align` must be "left", "center" or "right", not {other} `align` は "left"、"center"、"right" のいずれかにしてください({other} は使用できません) + File + Number ファイル名 + 番号 + File + Data Set Name ファイル名 + データセット名 + Data Set Name データセット名 +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` は `fileNumber`、`fileDataSetName`、`dataSetName` のいずれかである必要があります +@msg no free data set file name in destination folder 保存先フォルダーに使用可能なデータセットのファイル名がありません # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects パス効果 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 134cc18084..b34d095505 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5967,6 +5967,11 @@ breakText Glyphs გლიფები @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` უნდა იყოს lines, paragraphs, words ან glyphs და არა {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` უნდა იყოს "line" ან "paragraph" და არა {other} @msg `align` must be "left", "center" or "right", not {other} `align` უნდა იყოს "left", "center" ან "right" და არა {other} + File + Number ფაილი + ნომერი + File + Data Set Name ფაილი + მონაცემთა ნაკრების სახელი + Data Set Name მონაცემთა ნაკრების სახელი +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` უნდა იყოს `fileNumber`, `fileDataSetName` ან `dataSetName` +@msg no free data set file name in destination folder დანიშნულების საქაღალდეში მონაცემთა ნაკრებისთვის თავისუფალი ფაილის სახელი არ არის # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects ტრაექტორიის ეფექტები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 6a12ca3638..5e7e7db024 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5559,6 +5559,11 @@ breakText Glyphs 글리프 @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by`는 lines, paragraphs, words 또는 glyphs여야 합니다({other}는 사용할 수 없음) @msg `kind` must be "line" or "paragraph", not {other} `kind`는 "line" 또는 "paragraph"여야 합니다({other}는 사용할 수 없음) @msg `align` must be "left", "center" or "right", not {other} `align`은 "left", "center" 또는 "right"여야 합니다({other}는 사용할 수 없음) + File + Number 파일 + 번호 + File + Data Set Name 파일 + 데이터 세트 이름 + Data Set Name 데이터 세트 이름 +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming`은 `fileNumber`, `fileDataSetName` 또는 `dataSetName`이어야 합니다 +@msg no free data set file name in destination folder 대상 폴더에 사용할 수 있는 데이터 세트 파일 이름이 없습니다 # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects 패스 효과 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 19fdc86635..504ecae137 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5919,6 +5919,11 @@ breakText Glyphs Glyphs @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` moet lines, paragraphs, words of glyphs zijn, niet {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` moet "line" of "paragraph" zijn, niet {other} @msg `align` must be "left", "center" or "right", not {other} `align` moet "left", "center" of "right" zijn, niet {other} + File + Number Bestand + nummer + File + Data Set Name Bestand + naam gegevensset + Data Set Name Naam gegevensset +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` moet `fileNumber`, `fileDataSetName` of `dataSetName` zijn +@msg no free data set file name in destination folder Geen vrije bestandsnaam voor de gegevensset in de doelmap # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Padeffecten diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index c153223376..fffff07ae6 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5832,6 +5832,11 @@ breakText Glyphs Glify @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` musi mieć wartość lines, paragraphs, words lub glyphs, a nie {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` musi mieć wartość "line" lub "paragraph", a nie {other} @msg `align` must be "left", "center" or "right", not {other} `align` musi mieć wartość "left", "center" lub "right", a nie {other} + File + Number Plik + numer + File + Data Set Name Plik + nazwa zestawu danych + Data Set Name Nazwa zestawu danych +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` musi mieć wartość `fileNumber`, `fileDataSetName` lub `dataSetName` +@msg no free data set file name in destination folder Brak wolnej nazwy pliku zestawu danych w folderze docelowym # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Efekty ścieżki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4fd8e2bc5c..aab46d1911 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5895,6 +5895,11 @@ breakText Glyphs Glifos @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` deve ser lines, paragraphs, words ou glyphs, não {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` deve ser "line" ou "paragraph", não {other} @msg `align` must be "left", "center" or "right", not {other} `align` deve ser "left", "center" ou "right", não {other} + File + Number Arquivo + número + File + Data Set Name Arquivo + nome do conjunto de dados + Data Set Name Nome do conjunto de dados +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` deve ser `fileNumber`, `fileDataSetName` ou `dataSetName` +@msg no free data set file name in destination folder Não há nome de arquivo livre para o conjunto de dados na pasta de destino # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Distance Distância diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 122bf5939b..a516437a62 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5955,6 +5955,11 @@ breakText Glyphs Глифы @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` должен быть lines, paragraphs, words или glyphs, а не {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` должен быть "line" или "paragraph", а не {other} @msg `align` must be "left", "center" or "right", not {other} `align` должен быть "left", "center" или "right", а не {other} + File + Number Файл + номер + File + Data Set Name Файл + имя набора данных + Data Set Name Имя набора данных +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` должно быть `fileNumber`, `fileDataSetName` или `dataSetName` +@msg no free data set file name in destination folder В папке назначения нет свободного имени файла для набора данных # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Эффекты контура diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 711f1eab46..a98780bcf2 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6030,6 +6030,11 @@ breakText Glyphs Glyfer @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` måste vara lines, paragraphs, words eller glyphs, inte {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` måste vara "line" eller "paragraph", inte {other} @msg `align` must be "left", "center" or "right", not {other} `align` måste vara "left", "center" eller "right", inte {other} + File + Number Fil + nummer + File + Data Set Name Fil + datauppsättningens namn + Data Set Name Datauppsättningens namn +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` måste vara `fileNumber`, `fileDataSetName` eller `dataSetName` +@msg no free data set file name in destination folder Inget ledigt filnamn för datauppsättningen i målmappen # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Baneffekter diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 5f69d1acb6..4d543f0270 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5935,6 +5935,11 @@ breakText Glyphs Glifler @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by`, lines, paragraphs, words veya glyphs olmalı, {other} değil @msg `kind` must be "line" or "paragraph", not {other} `kind`, "line" veya "paragraph" olmalı, {other} değil @msg `align` must be "left", "center" or "right", not {other} `align`, "left", "center" veya "right" olmalı, {other} değil + File + Number Dosya + numara + File + Data Set Name Dosya + veri kümesi adı + Data Set Name Veri kümesi adı +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` değeri `fileNumber`, `fileDataSetName` veya `dataSetName` olmalıdır +@msg no free data set file name in destination folder Hedef klasörde veri kümesi için boş bir dosya adı yok # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Yol Efektleri diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index eb9d140161..6942907990 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5576,6 +5576,11 @@ breakText Glyphs Гліфи @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` має бути lines, paragraphs, words або glyphs, а не {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` має бути "line" або "paragraph", а не {other} @msg `align` must be "left", "center" or "right", not {other} `align` має бути "left", "center" або "right", а не {other} + File + Number Файл + номер + File + Data Set Name Файл + назва набору даних + Data Set Name Назва набору даних +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` має бути `fileNumber`, `fileDataSetName` або `dataSetName` +@msg no free data set file name in destination folder У папці призначення немає вільного імені файлу набору даних # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Ефекти контуру diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f6b926e07f..1c3c493879 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5578,6 +5578,11 @@ breakText Glyphs Glyph @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` phải là lines, paragraphs, words hoặc glyphs, không phải {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` phải là "line" hoặc "paragraph", không phải {other} @msg `align` must be "left", "center" or "right", not {other} `align` phải là "left", "center" hoặc "right", không phải {other} + File + Number Tệp + số + File + Data Set Name Tệp + tên tập dữ liệu + Data Set Name Tên tập dữ liệu +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` phải là `fileNumber`, `fileDataSetName` hoặc `dataSetName` +@msg no free data set file name in destination folder Không có tên tệp tập dữ liệu còn trống trong thư mục đích # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Hiệu ứng đường dẫn diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 96b5fbe0df..a85bc1a63a 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5819,6 +5819,11 @@ breakText Glyphs 字形 @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` 必须是 lines、paragraphs、words 或 glyphs,而不是 {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` 必须是 "line" 或 "paragraph",而不是 {other} @msg `align` must be "left", "center" or "right", not {other} `align` 必须是 "left"、"center" 或 "right",而不是 {other} + File + Number 文件 + 编号 + File + Data Set Name 文件 + 数据集名称 + Data Set Name 数据集名称 +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` 必须是 `fileNumber`、`fileDataSetName` 或 `dataSetName` +@msg no free data set file name in destination folder 目标文件夹中没有可用的数据集文件名 # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects 路径效果 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 147c3b0432..7fe82d929f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5615,6 +5615,11 @@ breakText Glyphs 字符 @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` 必須是 lines、paragraphs、words 或 glyphs,而不是 {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` 必須是 "line" 或 "paragraph",而不是 {other} @msg `align` must be "left", "center" or "right", not {other} `align` 必須是 "left"、"center" 或 "right",而不是 {other} + File + Number 檔案 + 編號 + File + Data Set Name 檔案 + 資料集名稱 + Data Set Name 資料集名稱 +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` 必須是 `fileNumber`、`fileDataSetName` 或 `dataSetName` +@msg no free data set file name in destination folder 目的地資料夾中沒有可用的資料集檔案名稱 # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects 路徑效果 diff --git a/docs/mcp.md b/docs/mcp.md index 719ac6d40c..1b5c7e3c6a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1622,12 +1622,13 @@ already walks Image Trace. Short agent entry points: `%`). A declaration that holds anything else, and entity references that expand the library past 8 MiB, are refused. So are a variable or data set declared twice and a value for a variable the library doesn't declare. - Batch: `action.batch {commands, source?: folder|datasets, folder?, destination?: none|saveAndClose|folder, - destinationFolder?, overrideOpen?, overrideSave?, overrideExport?, includeSubdirs?, stopOnError?}` plays an - action on every file in a folder or every data set (the Actions panel menu's Batch…). Override Save and Override - Export end the file name of a step with `format` in that `format`, in lower case and without a leading dot, when it - is one of the format's extensions (`.svg` and `SVG` give `.svg`, `.JPEG` gives `.jpeg`), and otherwise in the - format's first extension (`png8` gives `.png`, `template` gives `.vctemplate`). A step without `format` keeps the - source file's extension (`.vectorcraft` over data sets). + destinationFolder?, datasetFileNaming?: fileNumber|fileDataSetName|dataSetName, overrideOpen?, + overrideSave?, overrideExport?, includeSubdirs?, stopOnError?}` plays an action on every file in a + folder or every data set (the Actions panel menu's Batch…). Override Save and Override Export end + the file name of a step with `format` in that `format`, in lower case and without a leading dot, + when it is one of the format's extensions (`.svg` and `SVG` give `.svg`, `.JPEG` gives `.jpeg`), + and otherwise in the format's first extension (`png8` gives `.png`, `template` gives `.vctemplate`). + A step without `format` keeps the source file's extension (`.vectorcraft` over data sets). - Image Trace: `imageTrace.presets`, `imageTrace.make {id?, preset?, params?, view?}` (or `imageTrace.makeAndExpand`), `imageTrace.setView`, `imageTrace.expand`, `imageTrace.release`. A key inside `params` that is not one of the trace settings, such as `colours`, is an error that names it and the nearest setting (`colors`), as for a command's own keys. @@ -2963,10 +2964,16 @@ earlier step deleted the active artboard when it was the last one), the step get remote mode, MCP's `run_command` calls and each step of the `command_batch` tool get the active artboard too. The Actions panel plays an action as a `command.batch`. The Actions panel menu's Batch… runs `action.batch`: the same steps on every readable file in a folder (or every data set of the open document), with -destination `none` | `saveAndClose` | `folder` and Override Open / Save / Export. Over data sets, the folder -destination and the overrides name each file after the document and the data set (`<document>_<data set>.<ext>`). +destination `none` | `saveAndClose` | `folder` and Override Open / Save / Export. For a Data Sets source, +`datasetFileNaming` chooses File + Number (`source001`), File + Data Set Name (`source_Alpha`), or Data Set Name +(`Alpha`). An omitted parameter keeps File + Data Set Name for existing callers; the dialog starts with File + +Number. A folder source ignores this parameter. The folder destination and overridden Save/Export paths use the +chosen stem with the output format's extension. An empty data set name under Data Set Name falls back to the +document stem plus its three-digit ordinal. Batch writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and -adds `-2`, `-3`… to a name an earlier data set used (compared without case). Caps: 500 files or data sets, 8 +adds the next free `-2`, `-3` suffix to a stem already used in the batch or whose generated output path exists in +the destination folder before the batch starts. Under Data Set Name, VectorCraft also makes Windows device names +safe (`CON` becomes `CON-`). This is VectorCraft's naming behavior. Caps: 500 files or data sets, 8 folder levels, 256 steps. An action recorded in the Actions panel leaves the artboard out, and its steps of these commands get the artboard that is active when the action plays. A press with the Selection, Direct Selection or Group Selection tool inside an artboard makes that artboard the active one; with the Selection diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6f0a426b26..bcc92a39b0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -548,6 +548,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Batch…: Override Save and Override Export name each file with the extension of the format the step writes, however the step spells the format (`.svg` and `SVG` give `.svg`, `png8` gives `.png`), in `action.batch`. - Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. + - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output name already in the destination folder gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). + - Export for Screens: the dialog's Example line shows the path of the file the export writes first, sub-folder included, named as the export names it, for the first chosen artboard, asset, layer or object (`document.exportForScreens`). - Export for Screens is laid out as the reference app's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`. - Save for Web: Preview in Browser writes each preview's page and images to a folder of its own inside `VectorCraft Save for Web` in the system's temporary folder. A later preview, from the same app or another one running, does not overwrite an earlier one. Each preview first removes the preview folders there that are an hour old or older and, on Linux, macOS and FreeBSD, belong to the current user; it leaves other files and folders alone. The folders a preview makes there are open to their owner only on those systems. When `VectorCraft Save for Web` is a link or is not a folder, or on those systems belongs to another user or can be written by other users, the preview goes to a new folder of its own in the temporary folder, which a later preview removes once it is an hour old (`file.saveForWeb.browser`). - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). From 1b4c050bd3781f5e9266f6d785dc9b0577cc6ad7 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 17:18:03 -0700 Subject: [PATCH 142/260] Batch: check existing data set outputs only in a folder the batch may read and write The `-2`, `-3` suffix for a data set output that already exists is now looked up only when the destination folder and the output path pass the read and write access checks, so a call cannot learn which files exist in a folder it may not use. The lookup uses only extensions of formats the app knows, without path separators or `..`, and only paths whose parent is the destination folder. A step whose `format` is unknown keeps its own path instead of being pointed into the destination folder. A data set or document named `.` or `..` gets the `Untitled` stem with its three-digit number. --- crates/engine/src/cmd/fileio/action_batch.rs | 155 ++++++++++++++++++- crates/engine/src/cmd/fileio/commands.rs | 2 +- docs/mcp.md | 8 +- docs/target-app-parity.md | 2 +- 4 files changed, 154 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index f2310962ee..307f43174d 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -221,7 +221,7 @@ fn finish_destination(s: &mut Session, run: &Run<'_>, stem: &str, ext: &str, sou "folder" => { let folder = run.dest_folder.ok_or_else(|| bad("action.batch", "missing destination folder"))?; let out_ext = if ext.is_empty() { "vectorcraft" } else { ext }; - let out = std::path::Path::new(folder).join(format!("{stem}.{out_ext}")); + let out = output_path(folder, stem, out_ext).ok_or_else(|| bad("action.batch", "unsafe destination file name"))?; let out = out.to_string_lossy().into_owned(); // When `close` is false (data sets), write a copy so the template keeps its path. write_result(s, &out, out_ext, !close)?; @@ -235,7 +235,8 @@ fn finish_destination(s: &mut Session, run: &Run<'_>, stem: &str, ext: &str, sou } /// Builds the three data set naming forms, replaces unsafe name characters, and adds `-2`, `-3` -/// suffixes when a stem was used earlier or its output already exists in the destination folder. +/// suffixes when a stem was used earlier or its output already exists in a folder the batch may +/// read and write. #[cfg(not(target_arch = "wasm32"))] fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>) -> Result<Vec<String>> { use super::screens::{file_part, safe_file_name}; @@ -243,13 +244,16 @@ fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>) if !matches!(naming, "fileNumber" | "fileDataSetName" | "dataSetName") { return Err(bad("action.batch", "`datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName`")); } + let doc_stem = safe_file_name(doc_stem); + let doc_stem = if doc_stem.is_empty() || matches!(doc_stem.as_str(), "." | "..") { "Untitled" } else { &doc_stem }; let bases = names.iter().enumerate().map(|(i, name)| { let safe = file_part(name); let safe_data_set = safe_file_name(&safe); + let ordinal = format!("{doc_stem}{:03}", i + 1); match naming { - "fileNumber" => format!("{doc_stem}{:03}", i + 1), + "fileNumber" => ordinal, "dataSetName" if !safe_data_set.is_empty() => safe_data_set, - "dataSetName" => format!("{doc_stem}{:03}", i + 1), + "dataSetName" => ordinal, _ => format!("{doc_stem}_{safe}"), } }); @@ -283,8 +287,15 @@ fn dataset_output_extensions(run: &Run<'_>) -> Vec<String> { let writes = (run.override_save && matches!(id, "document.save" | "file.save" | "file.saveAs")) || (run.override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection")); if writes { - let ext = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty()); - extensions.push(ext.map_or_else(|| "vectorcraft".to_string(), format_extension)); + let format = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty()); + let ext = match format { + Some(format) if super::format(format).is_some() => format_extension(format), + Some(_) => continue, + None => "vectorcraft".to_string(), + }; + if safe_extension(&ext) { + extensions.push(ext); + } } } extensions @@ -293,7 +304,36 @@ fn dataset_output_extensions(run: &Run<'_>) -> Vec<String> { #[cfg(not(target_arch = "wasm32"))] fn dataset_output_exists(folder: Option<&str>, stem: &str, extensions: &[String]) -> bool { let Some(folder) = folder else { return false }; - extensions.iter().any(|ext| std::path::Path::new(folder).join(format!("{stem}.{ext}")).exists()) + if super::may_read(folder).is_err() || super::may_write(folder).is_err() { + return false; + } + extensions.iter().any(|ext| { + output_path(folder, stem, ext).is_some_and(|path| { + let path_text = path.to_string_lossy(); + super::may_read(&path_text).is_ok() && super::may_write(&path_text).is_ok() && path.exists() + }) + }) +} + +/// Returns whether an extension is safe to use in an output file name. +#[cfg(not(target_arch = "wasm32"))] +fn safe_extension(ext: &str) -> bool { + !ext.is_empty() && !ext.contains(['/', '\\', ':']) && !ext.contains("..") +} + +/// Returns a path inside the destination folder for a safe stem and extension. +#[cfg(not(target_arch = "wasm32"))] +fn output_path(folder: &str, stem: &str, ext: &str) -> Option<std::path::PathBuf> { + use std::path::Path; + if stem.is_empty() || matches!(stem, "." | "..") || stem.contains(['/', '\\']) || !safe_extension(ext) { + return None; + } + let name = format!("{stem}.{ext}"); + if name.contains(['/', '\\']) { + return None; + } + let path = Path::new(folder).join(name); + (path.parent() == Some(Path::new(folder))).then_some(path) } /// Save when the extension is a Save format; otherwise export (PNG, JPEG…). @@ -341,7 +381,10 @@ fn rewrite_paths( Some(f) => format_extension(f), None => default_ext.to_string(), }; - let file = std::path::Path::new(folder).join(format!("{stem}.{ext}")); + if params.get("format").and_then(Value::as_str).filter(|f| !f.is_empty()).is_some_and(|f| super::format(f).is_none()) { + return c; + } + let Some(file) = output_path(folder, stem, &ext) else { return c }; params.insert("path".into(), json!(file.to_string_lossy())); if let Some(o) = c.as_object_mut() { o.insert("params".into(), Value::Object(params)); @@ -721,6 +764,102 @@ mod tests { assert_eq!(file_names(&dest), ["Alpha-2.svg", "Alpha.svg"]); } + #[test] + fn batch_does_not_probe_a_denied_destination() { + let allowed = tmp("probe-allowed"); + let denied = tmp("probe-denied"); + std::fs::write(denied.join("Alpha.svg"), b"private").unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[allowed.as_path()], &[allowed.as_path()]).unwrap().unwrap(); + let steps = [json!({"command": "document.export", "params": {"format": "svg"}})]; + let folder = denied.to_string_lossy().into_owned(); + let run = Run { + label: "Test", + steps: &steps, + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: Some(&folder), + }; + crate::file_access::confine(Some(&roots), || { + assert_eq!(dataset_stems(&["Alpha".into()], "source", "dataSetName", &run).unwrap(), ["Alpha"]); + let mut s = with_data_sets(&["Alpha"]); + let result = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", "destination": "none", + "destinationFolder": folder, "overrideExport": true, + "commands": steps, + }), + ) + .unwrap(); + assert!(!result.to_string().contains("Alpha-2"), "{result}"); + }); + } + + #[test] + fn batch_does_not_probe_unknown_format_paths() { + let root = tmp("probe-format"); + let folder = root.join("out"); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::write(root.join("outside"), b"private").unwrap(); + for format in ["../outside", "x/../../outside", "..\\..\\outside"] { + let steps = [json!({"command": "document.export", "params": {"format": format}})]; + let folder = folder.to_string_lossy().into_owned(); + let run = Run { + label: "Test", + steps: &steps, + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: Some(&folder), + }; + assert_eq!( + dataset_stems(&["Alpha".into()], "source", "dataSetName", &run).unwrap_or_else(|e| panic!("{format}: {e}")), + ["Alpha"], + "{format}" + ); + assert_eq!(rewrite_paths(&steps, false, true, Some(&folder), "Alpha", "vectorcraft"), steps, "{format}"); + } + } + + #[test] + fn batch_probe_and_dot_names_stay_in_destination() { + let root = tmp("probe-parent"); + let folder = root.join("out"); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::write(root.join("outside.svg"), b"private").unwrap(); + let folder = folder.to_string_lossy().into_owned(); + let run = Run { + label: "Test", + steps: &[], + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: Some(&folder), + }; + assert_eq!(dataset_stems(&[".".into(), "..".into()], ".", "dataSetName", &run).unwrap(), ["Untitled001", "Untitled002"]); + assert_eq!(dataset_stems(&["Alpha".into()], "..", "fileNumber", &run).unwrap(), ["Untitled001"]); + let output = root.join("named"); + let mut s = with_data_sets(&[".", ".."]); + let r = named_batch(&mut s, &output, Some("dataSetName")); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(file_names(&output), ["Untitled001.vectorcraft", "Untitled002.vectorcraft"]); + } + + #[test] + fn batch_probe_rejects_parent_escape() { + let root = tmp("probe-parent-only"); + let folder = root.join("out"); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::write(root.join("outside.svg"), b"private").unwrap(); + let folder = folder.to_string_lossy().into_owned(); + assert!(!dataset_output_exists(Some(&folder), "../outside", &["svg".into()])); + } + #[test] fn batch_rejects_unknown_data_set_naming_but_ignores_it_for_folders() { let mut s = with_data_sets(&["Alpha"]); diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index ba39d0bdb1..9c6861f555 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or present in the destination folder gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or whose output already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}", always, action_batch::action_batch ), diff --git a/docs/mcp.md b/docs/mcp.md index 1b5c7e3c6a..996cee88b1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1629,6 +1629,8 @@ already walks Image Trace. Short agent entry points: when it is one of the format's extensions (`.svg` and `SVG` give `.svg`, `.JPEG` gives `.jpeg`), and otherwise in the format's first extension (`png8` gives `.png`, `template` gives `.vctemplate`). A step without `format` keeps the source file's extension (`.vectorcraft` over data sets). + An output already in a destination folder gets the next free `-2`, `-3` suffix only when the batch + may read and write that folder. - Image Trace: `imageTrace.presets`, `imageTrace.make {id?, preset?, params?, view?}` (or `imageTrace.makeAndExpand`), `imageTrace.setView`, `imageTrace.expand`, `imageTrace.release`. A key inside `params` that is not one of the trace settings, such as `colours`, is an error that names it and the nearest setting (`colors`), as for a command's own keys. @@ -2972,9 +2974,9 @@ chosen stem with the output format's extension. An empty data set name under Dat document stem plus its three-digit ordinal. Batch writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds the next free `-2`, `-3` suffix to a stem already used in the batch or whose generated output path exists in -the destination folder before the batch starts. Under Data Set Name, VectorCraft also makes Windows device names -safe (`CON` becomes `CON-`). This is VectorCraft's naming behavior. Caps: 500 files or data sets, 8 -folder levels, 256 steps. An action recorded in the Actions panel leaves the artboard out, +a destination folder the batch may read and write before it starts. Under Data Set Name, VectorCraft also makes +Windows device names safe (`CON` becomes `CON-`). This is VectorCraft's naming behavior. Caps: 500 +files or data sets, 8 folder levels, 256 steps. An action recorded in the Actions panel leaves the artboard out, and its steps of these commands get the artboard that is active when the action plays. A press with the Selection, Direct Selection or Group Selection tool inside an artboard makes that artboard the active one; with the Selection tool, a Shift-click on an empty spot inside an artboard makes it active and keeps the selection. Choosing the Artboard diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bcc92a39b0..0634080f47 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -548,7 +548,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Batch…: Override Save and Override Export name each file with the extension of the format the step writes, however the step spells the format (`.svg` and `SVG` give `.svg`, `png8` gives `.png`), in `action.batch`. - Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. - - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output name already in the destination folder gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). + - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output already in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). - Export for Screens: the dialog's Example line shows the path of the file the export writes first, sub-folder included, named as the export names it, for the first chosen artboard, asset, layer or object (`document.exportForScreens`). - Export for Screens is laid out as the reference app's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`. - Save for Web: Preview in Browser writes each preview's page and images to a folder of its own inside `VectorCraft Save for Web` in the system's temporary folder. A later preview, from the same app or another one running, does not overwrite an earlier one. Each preview first removes the preview folders there that are an hour old or older and, on Linux, macOS and FreeBSD, belong to the current user; it leaves other files and folders alone. The folders a preview makes there are open to their owner only on those systems. When `VectorCraft Save for Web` is a link or is not a folder, or on those systems belongs to another user or can be written by other users, the preview goes to a new folder of its own in the temporary folder, which a later preview removes once it is an hour old (`file.saveForWeb.browser`). From c55e4a226ea1607a1350279179b74ec2f28893d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 18:56:42 -0700 Subject: [PATCH 143/260] Batch: pass the data set naming choice in the batch run The naming choice reaches batch_datasets as a field of the run, and the short Batch entry in docs/mcp.md is back to main's text; the longer Batch section names datasetFileNaming and when an existing output gets a suffix. --- crates/engine/src/cmd/fileio/action_batch.rs | 14 ++++++--- docs/mcp.md | 33 +++++++++----------- 2 files changed, 25 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 307f43174d..565710f9e5 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -34,6 +34,7 @@ struct Run<'a> { override_export: bool, destination: &'a str, dest_folder: Option<&'a str>, + dataset_file_naming: &'a str, } /// Play `commands` on each source file or data set. @@ -90,10 +91,11 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> { override_export: bool_or(p, "overrideExport", true), destination, dest_folder: dest_folder.as_deref(), + dataset_file_naming: p.get("datasetFileNaming").map_or("fileDataSetName", |v| v.as_str().unwrap_or("")), }; match source { "folder" => batch_folder(s, C, p, override_open, &run), - "datasets" => batch_datasets(s, C, &run, p), + "datasets" => batch_datasets(s, C, &run), _ => Err(bad(C, "`source` must be `folder` or `datasets`")), } } @@ -134,7 +136,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: } #[cfg(not(target_arch = "wasm32"))] -fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>, p: &Value) -> Result<Value> { +fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result<Value> { let st = s.doc()?; let names: Vec<String> = st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect(); if names.is_empty() { @@ -144,8 +146,7 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>, p: &Value) -> Resul return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} data sets"))); } let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string(); - let naming = p.get("datasetFileNaming").map_or("fileDataSetName", |v| v.as_str().unwrap_or("")); - let stems = dataset_stems(&names, &doc_stem, naming, run)?; + let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run)?; let steps = filter_steps(run.steps, true, false); let run = Run { steps: &steps, ..*run }; let mut processed = Vec::new(); @@ -690,6 +691,7 @@ mod tests { override_export: true, destination: "none", dest_folder: None, + dataset_file_naming: "fileDataSetName", }; let stems = dataset_stems(&names, "source", "fileNumber", &run).unwrap(); for n in [1, 2, 10, 100, 500] { @@ -714,6 +716,7 @@ mod tests { override_export: true, destination: "none", dest_folder: None, + dataset_file_naming: "fileDataSetName", }; assert_eq!(dataset_stems(&[String::new()], "Untitled", "dataSetName", &run).unwrap(), ["Untitled001"]); assert_eq!(dataset_stems(&[" ".to_string()], "Untitled", "dataSetName", &run).unwrap(), ["Untitled001"]); @@ -780,6 +783,7 @@ mod tests { override_export: true, destination: "none", dest_folder: Some(&folder), + dataset_file_naming: "fileDataSetName", }; crate::file_access::confine(Some(&roots), || { assert_eq!(dataset_stems(&["Alpha".into()], "source", "dataSetName", &run).unwrap(), ["Alpha"]); @@ -815,6 +819,7 @@ mod tests { override_export: true, destination: "none", dest_folder: Some(&folder), + dataset_file_naming: "fileDataSetName", }; assert_eq!( dataset_stems(&["Alpha".into()], "source", "dataSetName", &run).unwrap_or_else(|e| panic!("{format}: {e}")), @@ -840,6 +845,7 @@ mod tests { override_export: true, destination: "none", dest_folder: Some(&folder), + dataset_file_naming: "fileDataSetName", }; assert_eq!(dataset_stems(&[".".into(), "..".into()], ".", "dataSetName", &run).unwrap(), ["Untitled001", "Untitled002"]); assert_eq!(dataset_stems(&["Alpha".into()], "..", "fileNumber", &run).unwrap(), ["Untitled001"]); diff --git a/docs/mcp.md b/docs/mcp.md index 996cee88b1..bee6b96813 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1622,15 +1622,12 @@ already walks Image Trace. Short agent entry points: `%`). A declaration that holds anything else, and entity references that expand the library past 8 MiB, are refused. So are a variable or data set declared twice and a value for a variable the library doesn't declare. - Batch: `action.batch {commands, source?: folder|datasets, folder?, destination?: none|saveAndClose|folder, - destinationFolder?, datasetFileNaming?: fileNumber|fileDataSetName|dataSetName, overrideOpen?, - overrideSave?, overrideExport?, includeSubdirs?, stopOnError?}` plays an action on every file in a - folder or every data set (the Actions panel menu's Batch…). Override Save and Override Export end - the file name of a step with `format` in that `format`, in lower case and without a leading dot, - when it is one of the format's extensions (`.svg` and `SVG` give `.svg`, `.JPEG` gives `.jpeg`), - and otherwise in the format's first extension (`png8` gives `.png`, `template` gives `.vctemplate`). - A step without `format` keeps the source file's extension (`.vectorcraft` over data sets). - An output already in a destination folder gets the next free `-2`, `-3` suffix only when the batch - may read and write that folder. + destinationFolder?, overrideOpen?, overrideSave?, overrideExport?, includeSubdirs?, stopOnError?}` plays an + action on every file in a folder or every data set (the Actions panel menu's Batch…). Override Save and Override + Export end the file name of a step with `format` in that `format`, in lower case and without a leading dot, when it + is one of the format's extensions (`.svg` and `SVG` give `.svg`, `.JPEG` gives `.jpeg`), and otherwise in the + format's first extension (`png8` gives `.png`, `template` gives `.vctemplate`). A step without `format` keeps the + source file's extension (`.vectorcraft` over data sets). - Image Trace: `imageTrace.presets`, `imageTrace.make {id?, preset?, params?, view?}` (or `imageTrace.makeAndExpand`), `imageTrace.setView`, `imageTrace.expand`, `imageTrace.release`. A key inside `params` that is not one of the trace settings, such as `colours`, is an error that names it and the nearest setting (`colors`), as for a command's own keys. @@ -2967,15 +2964,15 @@ remote mode, MCP's `run_command` calls and each step of the `command_batch` tool Actions panel plays an action as a `command.batch`. The Actions panel menu's Batch… runs `action.batch`: the same steps on every readable file in a folder (or every data set of the open document), with destination `none` | `saveAndClose` | `folder` and Override Open / Save / Export. For a Data Sets source, -`datasetFileNaming` chooses File + Number (`source001`), File + Data Set Name (`source_Alpha`), or Data Set Name -(`Alpha`). An omitted parameter keeps File + Data Set Name for existing callers; the dialog starts with File + -Number. A folder source ignores this parameter. The folder destination and overridden Save/Export paths use the -chosen stem with the output format's extension. An empty data set name under Data Set Name falls back to the -document stem plus its three-digit ordinal. -Batch writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and -adds the next free `-2`, `-3` suffix to a stem already used in the batch or whose generated output path exists in -a destination folder the batch may read and write before it starts. Under Data Set Name, VectorCraft also makes -Windows device names safe (`CON` becomes `CON-`). This is VectorCraft's naming behavior. Caps: 500 +`datasetFileNaming?: fileNumber | fileDataSetName | dataSetName` chooses File + Number (`source001`), +File + Data Set Name (`source_Alpha`), or Data Set Name (`Alpha`). An omitted parameter keeps File + Data Set Name +for existing callers; the dialog starts with File + Number. A folder source ignores this parameter. The folder +destination and overridden Save/Export paths use the chosen stem with the output format's extension. An empty data +set name under Data Set Name falls back to the document stem plus its three-digit ordinal. Batch writes `/`, `\`, +`:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds the next free `-2`, +`-3` suffix to a stem already used in the batch (compared without case). An output already in a destination folder +gets the next free suffix only when the batch may read and write that folder before it starts. Under Data Set Name, +VectorCraft makes Windows device names safe (`CON` becomes `CON-`). This is VectorCraft's naming behavior. Caps: 500 files or data sets, 8 folder levels, 256 steps. An action recorded in the Actions panel leaves the artboard out, and its steps of these commands get the artboard that is active when the action plays. A press with the Selection, Direct Selection or Group Selection tool inside an artboard makes that artboard the active one; with the Selection From 483c191e242c3e3bf8edfdf0a9c21aa600a13477 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 19:13:07 -0700 Subject: [PATCH 144/260] Batch: keep a backslash in a source file name on Linux and macOS Destination and Override Save/Export paths reject only the current platform's path separators, so a folder batch writes `a\b.svg` into the destination folder on systems where that is one file name. --- crates/engine/src/cmd/fileio/action_batch.rs | 72 +++++++++++++++++++- 1 file changed, 70 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 565710f9e5..6481191efd 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -326,11 +326,11 @@ fn safe_extension(ext: &str) -> bool { #[cfg(not(target_arch = "wasm32"))] fn output_path(folder: &str, stem: &str, ext: &str) -> Option<std::path::PathBuf> { use std::path::Path; - if stem.is_empty() || matches!(stem, "." | "..") || stem.contains(['/', '\\']) || !safe_extension(ext) { + if stem.is_empty() || matches!(stem, "." | "..") || stem.contains(std::path::is_separator) || !safe_extension(ext) { return None; } let name = format!("{stem}.{ext}"); - if name.contains(['/', '\\']) { + if name.contains(std::path::is_separator) { return None; } let path = Path::new(folder).join(name); @@ -511,6 +511,74 @@ mod tests { assert!(dest.join("b.svg").is_file(), "b.svg written"); } + #[cfg(unix)] + #[test] + fn batch_folder_keeps_backslash_in_source_file_name() { + let src = tmp("backslash-src"); + let dest = tmp("backslash-dest"); + write_svg(&src, "a\\b.svg", "#f00"); + let mut s = Session::new(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "folder", + "folder": src.to_string_lossy(), + "destination": "folder", + "destinationFolder": dest.to_string_lossy(), + "stopOnError": true, + "commands": [{"command": "object.unlockAll", "params": {}}] + }), + ) + .unwrap(); + assert_eq!(r["count"], 1, "{r}"); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(r["stopped"], false, "{r}"); + assert!(dest.join("a\\b.svg").is_file(), "{r}"); + } + + #[cfg(unix)] + #[test] + fn batch_folder_override_export_keeps_backslash_in_source_file_name() { + let src = tmp("backslash-export-src"); + let dest = tmp("backslash-export-dest"); + write_svg(&src, "a\\b.svg", "#f00"); + let mut s = Session::new(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "folder", + "folder": src.to_string_lossy(), + "destination": "folder", + "destinationFolder": dest.to_string_lossy(), + "stopOnError": true, + "commands": [{"command": "document.export", "params": {"format": "svg"}}] + }), + ) + .unwrap(); + assert_eq!(r["count"], 1, "{r}"); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(r["stopped"], false, "{r}"); + assert_eq!(file_names(&dest), ["a\\b.svg"], "{r}"); + } + + #[test] + fn output_path_accepts_only_platform_file_name_separators() { + let folder = tmp("output-path"); + let folder = folder.to_string_lossy(); + let backslash = output_path(&folder, "a\\b", "svg"); + #[cfg(windows)] + assert!(backslash.is_none()); + #[cfg(not(windows))] + assert_eq!(backslash, Some(std::path::Path::new(folder.as_ref()).join("a\\b.svg"))); + for stem in ["a/b", ".", "..", ""] { + assert!(output_path(&folder, stem, "svg").is_none(), "{stem:?}"); + } + #[cfg(windows)] + assert_eq!(std::path::Path::new("a\\b.svg").file_stem(), Some(std::ffi::OsStr::new("b"))); + } + #[test] fn batch_skips_open_steps_when_override_open() { let src = tmp("open"); From 5dcc65d69a377bd783f5dce05c9f469090812b2b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 20:59:11 -0700 Subject: [PATCH 145/260] Batch: keep existing artboard files when choosing data set file names When a step can write one file per artboard (Save in the native, template or .ai formats, or Export in SVG, EPS, the raster formats, DXF, EMF, WMF or .ai) and the document has more than one artboard, an existing file with one of the stem's artboard file names now gives the data set the next free -2, -3 suffix, as the stem's own file does. Names a data set's outputs will take are also reserved for the later data sets of the same batch. --- crates/engine/src/cmd/fileio/action_batch.rs | 246 +++++++++++++++++-- docs/mcp.md | 6 +- 2 files changed, 227 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 6481191efd..1caa98db7d 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -146,7 +146,7 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result<Value> { return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} data sets"))); } let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string(); - let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run)?; + let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?; let steps = filter_steps(run.steps, true, false); let run = Run { steps: &steps, ..*run }; let mut processed = Vec::new(); @@ -239,7 +239,7 @@ fn finish_destination(s: &mut Session, run: &Run<'_>, stem: &str, ext: &str, sou /// suffixes when a stem was used earlier or its output already exists in a folder the batch may /// read and write. #[cfg(not(target_arch = "wasm32"))] -fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>) -> Result<Vec<String>> { +fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>, doc: &vectorcraft_doc::Document) -> Result<Vec<String>> { use super::screens::{file_part, safe_file_name}; if !matches!(naming, "fileNumber" | "fileDataSetName" | "dataSetName") { @@ -258,13 +258,19 @@ fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>) _ => format!("{doc_stem}_{safe}"), } }); - let extensions = dataset_output_extensions(run); + let outputs = dataset_output_extensions(run, doc); let mut taken = std::collections::HashSet::new(); + let mut reserved = std::collections::HashSet::new(); let mut stems = Vec::with_capacity(bases.len()); for base in bases { let mut candidate = base.clone(); let mut suffix = 2; - while taken.contains(&candidate.to_lowercase()) || dataset_output_exists(run.dest_folder, &candidate, &extensions) { + while taken.contains(&candidate.to_lowercase()) + || dataset_output_paths(run.dest_folder, &candidate, &outputs, doc) + .iter() + .any(|path| reserved.contains(&path.to_string_lossy().to_lowercase())) + || dataset_output_exists(run.dest_folder, &candidate, &outputs, doc) + { if suffix > 10_000 { return Err(bad("action.batch", "no free data set file name in destination folder")); } @@ -272,16 +278,27 @@ fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>) suffix += 1; } taken.insert(candidate.to_lowercase()); + reserved + .extend(dataset_output_paths(run.dest_folder, &candidate, &outputs, doc).into_iter().map(|path| path.to_string_lossy().to_lowercase())); stems.push(candidate); } Ok(stems) } #[cfg(not(target_arch = "wasm32"))] -fn dataset_output_extensions(run: &Run<'_>) -> Vec<String> { - let mut extensions = Vec::new(); +struct DatasetOutput { + ext: String, + artboards: bool, + joiner: &'static str, +} + +/// Lists step output extensions and reserves artboard file names when the document has multiple artboards. +/// Per-artboard names count for vectorcraft, template, AI and AIT saves and SVG, SVGZ, EPS, raster, DXF, EMF, WMF and AI exports. +#[cfg(not(target_arch = "wasm32"))] +fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document) -> Vec<DatasetOutput> { + let mut outputs = Vec::new(); if run.destination == "folder" { - extensions.push("vectorcraft".to_string()); + outputs.push(DatasetOutput { ext: "vectorcraft".into(), artboards: false, joiner: "-" }); } for step in run.steps { let id = step.get("command").and_then(Value::as_str).unwrap_or(""); @@ -295,27 +312,75 @@ fn dataset_output_extensions(run: &Run<'_>) -> Vec<String> { None => "vectorcraft".to_string(), }; if safe_extension(&ext) { - extensions.push(ext); + let format_id = format.and_then(super::format).map(|f| f.id).unwrap_or("vectorcraft"); + let is_save = matches!(id, "document.save" | "file.save" | "file.saveAs"); + let artboards = doc.artboards.len() > 1 + && if is_save { + matches!(format_id, "vectorcraft" | "template" | "ai" | "ait") + } else { + id == "document.export" + && matches!( + format_id, + "svg" + | "svgz" + | "eps" + | "png" + | "jpg" + | "webp" + | "gif" + | "png8" + | "tiff" + | "bmp" + | "tga" + | "psd" + | "dxf" + | "emf" + | "wmf" + | "ai" + ) + }; + outputs.push(DatasetOutput { ext, artboards, joiner: if format_id == "eps" { "_" } else { "-" } }); } } } - extensions + outputs } #[cfg(not(target_arch = "wasm32"))] -fn dataset_output_exists(folder: Option<&str>, stem: &str, extensions: &[String]) -> bool { +fn dataset_output_exists(folder: Option<&str>, stem: &str, outputs: &[DatasetOutput], doc: &vectorcraft_doc::Document) -> bool { let Some(folder) = folder else { return false }; if super::may_read(folder).is_err() || super::may_write(folder).is_err() { return false; } - extensions.iter().any(|ext| { - output_path(folder, stem, ext).is_some_and(|path| { - let path_text = path.to_string_lossy(); - super::may_read(&path_text).is_ok() && super::may_write(&path_text).is_ok() && path.exists() - }) + dataset_output_paths(Some(folder), stem, outputs, doc).iter().any(|path| { + let path_text = path.to_string_lossy(); + super::may_read(&path_text).is_ok() && super::may_write(&path_text).is_ok() && path.exists() }) } +#[cfg(not(target_arch = "wasm32"))] +fn dataset_output_paths(folder: Option<&str>, stem: &str, outputs: &[DatasetOutput], doc: &vectorcraft_doc::Document) -> Vec<std::path::PathBuf> { + let Some(folder) = folder else { return Vec::new() }; + let boards: Vec<_> = (0..doc.artboards.len()).collect(); + let mut parts = super::artboard_file_names(doc, &boards); + for board in boards { + parts.extend(super::artboard_file_names(doc, &[board])); + } + let mut paths = Vec::new(); + for output in outputs { + if !safe_extension(&output.ext) || super::format(&output.ext).is_none() { + continue; + } + paths.extend(output_path(folder, stem, &output.ext)); + if output.artboards { + for part in &parts { + paths.extend(output_path(folder, &format!("{stem}{}{part}", output.joiner), &output.ext)); + } + } + } + paths +} + /// Returns whether an extension is safe to use in an output file name. #[cfg(not(target_arch = "wasm32"))] fn safe_extension(ext: &str) -> bool { @@ -761,7 +826,7 @@ mod tests { dest_folder: None, dataset_file_naming: "fileDataSetName", }; - let stems = dataset_stems(&names, "source", "fileNumber", &run).unwrap(); + let stems = dataset_stems(&names, "source", "fileNumber", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(); for n in [1, 2, 10, 100, 500] { assert_eq!(stems[n - 1], format!("source{n:03}")); } @@ -786,8 +851,8 @@ mod tests { dest_folder: None, dataset_file_naming: "fileDataSetName", }; - assert_eq!(dataset_stems(&[String::new()], "Untitled", "dataSetName", &run).unwrap(), ["Untitled001"]); - assert_eq!(dataset_stems(&[" ".to_string()], "Untitled", "dataSetName", &run).unwrap(), ["Untitled001"]); + assert_eq!(dataset_stems(&[String::new()], "Untitled", "dataSetName", &run, &s.doc().unwrap().doc).unwrap(), ["Untitled001"]); + assert_eq!(dataset_stems(&[" ".to_string()], "Untitled", "dataSetName", &run, &s.doc().unwrap().doc).unwrap(), ["Untitled001"]); } #[test] @@ -835,6 +900,126 @@ mod tests { assert_eq!(file_names(&dest), ["Alpha-2.svg", "Alpha.svg"]); } + #[test] + fn batch_artboard_export_keeps_existing_output() { + let dest = tmp("choice-existing-artboard-export"); + let existing = dest.join("Alpha-Artboard-1.png"); + std::fs::write(&existing, b"keep").unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.export", "params": {"format": "png", "useArtboards": true}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(existing).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-2-Artboard-1.png", "Alpha-2-Artboard-2.png", "Alpha-Artboard-1.png"]); + } + + #[test] + fn batch_remembered_separate_artboards_keeps_existing_output() { + let source = tmp("choice-remembered-separate-source"); + let dest = tmp("choice-remembered-separate-dest"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("document.save", &json!({"path": source.join("source.vectorcraft").to_string_lossy(), "separateArtboards": true})).unwrap(); + assert!(source.join("source-Artboard-1.vectorcraft").exists()); + let existing = dest.join("Alpha-Artboard-1.vectorcraft"); + std::fs::write(&existing, b"keep").unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.save"}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(existing).unwrap(), b"keep"); + assert_eq!( + file_names(&dest), + ["Alpha-2-Artboard-1.vectorcraft", "Alpha-2-Artboard-2.vectorcraft", "Alpha-2.vectorcraft", "Alpha-Artboard-1.vectorcraft",] + ); + } + + #[test] + fn batch_pdf_export_ignores_artboard_named_file() { + let dest = tmp("choice-pdf-artboard-name"); + let existing = dest.join("Alpha-Artboard-1.pdf"); + std::fs::write(&existing, b"keep").unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.export", "params": {"format": "pdf"}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(existing).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-Artboard-1.pdf", "Alpha.pdf"]); + } + + #[test] + fn batch_separate_artboards_ignores_unrelated_extension() { + let dest = tmp("choice-separate-unrelated-extension"); + let unrelated = dest.join("Alpha-photo.png"); + std::fs::write(&unrelated, b"keep").unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.save", "params": {"separateArtboards": true}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(unrelated).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-Artboard-1.vectorcraft", "Alpha-Artboard-2.vectorcraft", "Alpha-photo.png", "Alpha.vectorcraft"]); + } + + #[test] + fn batch_separate_artboards_reserves_prior_output_names() { + let dest = tmp("choice-separate-reserved"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha-Artboard-1"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.save", "params": {"separateArtboards": true}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert!(dest.join("Alpha-Artboard-1.vectorcraft").exists()); + assert!(dest.join("Alpha-Artboard-1-2.vectorcraft").exists()); + } + #[test] fn batch_does_not_probe_a_denied_destination() { let allowed = tmp("probe-allowed"); @@ -854,7 +1039,10 @@ mod tests { dataset_file_naming: "fileDataSetName", }; crate::file_access::confine(Some(&roots), || { - assert_eq!(dataset_stems(&["Alpha".into()], "source", "dataSetName", &run).unwrap(), ["Alpha"]); + assert_eq!( + dataset_stems(&["Alpha".into()], "source", "dataSetName", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(), + ["Alpha"] + ); let mut s = with_data_sets(&["Alpha"]); let result = s .execute( @@ -890,7 +1078,8 @@ mod tests { dataset_file_naming: "fileDataSetName", }; assert_eq!( - dataset_stems(&["Alpha".into()], "source", "dataSetName", &run).unwrap_or_else(|e| panic!("{format}: {e}")), + dataset_stems(&["Alpha".into()], "source", "dataSetName", &run, &vectorcraft_doc::Document::new(100.0, 80.0)) + .unwrap_or_else(|e| panic!("{format}: {e}")), ["Alpha"], "{format}" ); @@ -915,8 +1104,14 @@ mod tests { dest_folder: Some(&folder), dataset_file_naming: "fileDataSetName", }; - assert_eq!(dataset_stems(&[".".into(), "..".into()], ".", "dataSetName", &run).unwrap(), ["Untitled001", "Untitled002"]); - assert_eq!(dataset_stems(&["Alpha".into()], "..", "fileNumber", &run).unwrap(), ["Untitled001"]); + assert_eq!( + dataset_stems(&[".".into(), "..".into()], ".", "dataSetName", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(), + ["Untitled001", "Untitled002"] + ); + assert_eq!( + dataset_stems(&["Alpha".into()], "..", "fileNumber", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(), + ["Untitled001"] + ); let output = root.join("named"); let mut s = with_data_sets(&[".", ".."]); let r = named_batch(&mut s, &output, Some("dataSetName")); @@ -931,7 +1126,12 @@ mod tests { std::fs::create_dir_all(&folder).unwrap(); std::fs::write(root.join("outside.svg"), b"private").unwrap(); let folder = folder.to_string_lossy().into_owned(); - assert!(!dataset_output_exists(Some(&folder), "../outside", &["svg".into()])); + assert!(!dataset_output_exists( + Some(&folder), + "../outside", + &[DatasetOutput { ext: "svg".into(), artboards: false, joiner: "-" }], + &vectorcraft_doc::Document::new(100.0, 80.0), + )); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index bee6b96813..f904715027 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2971,8 +2971,10 @@ destination and overridden Save/Export paths use the chosen stem with the output set name under Data Set Name falls back to the document stem plus its three-digit ordinal. Batch writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds the next free `-2`, `-3` suffix to a stem already used in the batch (compared without case). An output already in a destination folder -gets the next free suffix only when the batch may read and write that folder before it starts. Under Data Set Name, -VectorCraft makes Windows device names safe (`CON` becomes `CON-`). This is VectorCraft's naming behavior. Caps: 500 +gets the next free suffix only when the batch may read and write that folder before it starts. When a step can write +one file per artboard and the document has several artboards, a file with one of those artboard file names for the +stem counts too. Under Data Set Name, VectorCraft makes Windows device names safe (`CON` becomes `CON-`). This is +VectorCraft's naming behavior. Caps: 500 files or data sets, 8 folder levels, 256 steps. An action recorded in the Actions panel leaves the artboard out, and its steps of these commands get the artboard that is active when the action plays. A press with the Selection, Direct Selection or Group Selection tool inside an artboard makes that artboard the active one; with the Selection From 6f0d5f509f1076f9df6365b157d52941a4667b01 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 01:04:34 -0700 Subject: [PATCH 146/260] i18n: package, missing-font, missing-link and CSS counts use each language's plural forms MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Package status and question, the missing-links note, the Missing Fonts and Find Linked Files search counts, the modified-links questions, Apply to All, and the CSS Properties panel's notes no longer use a fixed "(s)" or plural template. They use the plural rows of each catalog, so "1 linked file not found" and Czech "Nenalezeny 2 propojené soubory" read correctly. The searched line is built from two plural phrases, "{n} folder" and "{n} file", in a "{folders} and {files} searched" frame. Package rows that joined the note to the folder without a space now keep the space. --- crates/ui-egui/src/dialogs/missing_fonts.rs | 20 ++++++----- .../src/dialogs/missing_fonts/tests.rs | 23 +++++++++++++ crates/ui-egui/src/dialogs/missing_links.rs | 34 ++++++++++++++++--- crates/ui-egui/src/dialogs/package.rs | 28 +++++++++------ crates/ui-egui/src/dialogs/tests_package.rs | 23 +++++++++++-- crates/ui-egui/src/i18n/bg.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/bs.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/ca.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/cs.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/da.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/de.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/el.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/es.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/fi.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/fr.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/hu.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/id.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/it.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/ja.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/ka.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/ko.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/nl.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/pl.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/pt-br.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/ru.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/sv.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/tr.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/uk.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/vi.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/zh-hans.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/zh-hant.tsv | 32 +++++++++-------- crates/ui-egui/src/panels/css_properties.rs | 9 ++--- .../src/panels/tests_css_properties.rs | 27 +++++++++++++++ docs/target-app-parity.md | 1 + 34 files changed, 575 insertions(+), 422 deletions(-) diff --git a/crates/ui-egui/src/dialogs/missing_fonts.rs b/crates/ui-egui/src/dialogs/missing_fonts.rs index 16fa10bea8..205e4fa98e 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts.rs @@ -337,19 +337,21 @@ pub(super) fn progress(ui: &mut egui::Ui, d: &Dialog) { widgets::dim_name(ui, &crate::i18n::message(crate::i18n::current(), e)); } if let Some(s) = d.fields.get("searched") { - let (folders, files) = (s["folders"].to_string(), s["files"].to_string()); - widgets::dim_name( - ui, - &crate::i18n::fmt(tl!("{folders} folder(s) and {files} file(s) searched"), &[("folders", &folders), ("files", &files)]), - ); + let folders = crate::i18n::tn(s["folders"].as_u64().unwrap_or(0), "{n} folder", "{n} folders"); + let files = crate::i18n::tn(s["files"].as_u64().unwrap_or(0), "{n} file", "{n} files"); + widgets::dim_name(ui, &crate::i18n::fmt(tl!("{folders} and {files} searched"), &[("folders", &folders), ("files", &files)])); } - let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).filter(|n| *n > 0).map(|n| n.to_string()); + let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).filter(|n| *n > 0); if let Some(n) = count("skipped") { - let text = tl!("{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones"); - widgets::dim_name(ui, &crate::i18n::fmt(text, &[("count", &n)])); + let text = crate::i18n::tn( + n, + "{n} folder skipped, such as another app's or the system's folder or a hidden one", + "{n} folders skipped, such as other apps' and the system's folders and hidden ones", + ); + widgets::dim_name(ui, &text); } if let Some(n) = count("unreadable") { - widgets::dim_name(ui, &crate::i18n::fmt(tl!("{count} folder(s) or file(s) couldn't be read"), &[("count", &n)])); + widgets::dim_name(ui, &crate::i18n::tn(n, "{n} folder or file couldn't be read", "{n} folders or files couldn't be read")); } if matches!(d.fields.get("stopped").and_then(Value::as_str), Some("time" | "limit")) { widgets::dim_label(ui, tl!("The search stopped at its limit: search a smaller folder.")); diff --git a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs index 20266d97b3..c2b2a4e6c8 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs @@ -328,6 +328,29 @@ fn files_go_with_their_fonts_by_name() { assert_eq!((d.str("state"), &d.fields["chosen"]), ("done".to_string(), &json!([]))); } +/// A folder search's counts use the forms the language's plural rule picks for each count. +#[test] +fn search_counts_use_each_count_form() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut progress_text = |code: &str, n: u64| { + crate::i18n::set_current(crate::i18n::Lang::from_code(code).unwrap()); + let d = Dialog::new(KIND, json!({"state": "done", "searched": {"folders": n, "files": n}, "unreadable": n})); + let text = crate::tests_labels::painted_text(&mut app, |_, ui| progress(ui, &d)); + crate::i18n::set_current(crate::i18n::Lang::EN); + text + }; + let text = progress_text("en", 1); + assert!(text.contains("1 folder and 1 file searched") && text.contains("1 folder or file couldn't be read"), "{text}"); + for (n, searched, unreadable) in [ + (1, "Prohledáno: 1 složka, 1 soubor", "Nepodařilo se přečíst 1 složku nebo soubor"), + (2, "Prohledáno: 2 složky, 2 soubory", "Nepodařilo se přečíst 2 složky nebo soubory"), + (5, "Prohledáno: 5 složek, 5 souborů", "Nepodařilo se přečíst 5 složek nebo souborů"), + ] { + let text = progress_text("cs", n); + assert!(text.contains(searched) && text.contains(unreadable), "{n}: {text}"); + } +} + #[test] fn the_web_says_how_many_fonts_are_missing() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/missing_links.rs b/crates/ui-egui/src/dialogs/missing_links.rs index b717057698..fe6a804860 100644 --- a/crates/ui-egui/src/dialogs/missing_links.rs +++ b/crates/ui-egui/src/dialogs/missing_links.rs @@ -75,17 +75,23 @@ pub(super) fn ask_next(app: &mut VectorcraftApp, rest: Vec<Value>, modified: Vec /// With Update Links: Ask When Modified, offer to read the modified linked files `ids` again. fn ask_update(app: &mut VectorcraftApp, ids: Vec<Value>) { - ask(app, ids, tl!("{count} linked image(s) changed since this document was saved. Show the new versions?")); + ask( + app, + ids, + "{n} linked image changed since this document was saved. Show the new version?", + "{n} linked images changed since this document was saved. Show the new versions?", + ); } /// The same offer for linked files another app changed while the document is open /// ([`vectorcraft_engine::link_watch`]). #[cfg(not(target_arch = "wasm32"))] pub(crate) fn ask_update_changed(app: &mut VectorcraftApp, ids: Vec<Value>) { - ask(app, ids, tl!("{count} linked image(s) changed on disk. Show the new versions?")); + ask(app, ids, "{n} linked image changed on disk. Show the new version?", "{n} linked images changed on disk. Show the new versions?"); } -fn ask(app: &mut VectorcraftApp, ids: Vec<Value>, question: &str) { +/// Ask about the modified linked files `ids`; `one` and `other` are the English forms of the question. +fn ask(app: &mut VectorcraftApp, ids: Vec<Value>, one: &str, other: &str) { if ids.is_empty() { return; } @@ -93,7 +99,7 @@ fn ask(app: &mut VectorcraftApp, ids: Vec<Value>, question: &str) { app.status(format!("{} linked image(s) changed on disk: Update Links shows the new versions", ids.len())); return; } - let detail = crate::i18n::fmt(question, &[("count", &ids.len().to_string())]); + let detail = crate::i18n::tn(ids.len() as u64, one, other); super::confirm::ask(app, tl!("Update Modified Links"), &detail, "links.update", json!({ "ids": ids })); } @@ -133,7 +139,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if rest > 0 { ui.add_space(10.0); let all = d.bool("applyToAll"); - let label = crate::i18n::fmt(tl!("Apply to All ({count} more missing)"), &[("count", &rest.to_string())]); + let label = crate::i18n::tn(rest as u64, "Apply to All ({n} more missing)", "Apply to All ({n} more missing)"); if widgets::check(ui, &label, all, true) { d.fields.insert("applyToAll".into(), json!(!all)); } @@ -262,6 +268,24 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + /// The question about modified linked files uses the form the language's plural rule picks for + /// the count. + #[test] + fn the_modified_links_question_uses_each_count_form() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut question = |code: &str, n: u64| { + crate::i18n::set_current(crate::i18n::Lang::from_code(code).unwrap()); + ask_update(&mut app, (0..n).map(|id| json!(id)).collect()); + let detail = app.ui.dialog.take().map(|d| d.str("detail")); + crate::i18n::set_current(crate::i18n::Lang::EN); + detail.unwrap_or_default() + }; + assert_eq!(question("en", 1), "1 linked image changed since this document was saved. Show the new version?"); + assert_eq!(question("cs", 1), "Od uložení dokumentu se změnil 1 propojený obrázek. Zobrazit novou verzi?"); + assert_eq!(question("cs", 2), "Od uložení dokumentu se změnily 2 propojené obrázky. Zobrazit nové verze?"); + assert_eq!(question("cs", 5), "Od uložení dokumentu se změnilo 5 propojených obrázků. Zobrazit nové verze?"); + } + #[test] fn apply_to_all_replaces_the_others_from_the_same_folder() { let (mut app, dir, _) = opened_without_links("all"); diff --git a/crates/ui-egui/src/dialogs/package.rs b/crates/ui-egui/src/dialogs/package.rs index 839f763835..9c2b3deb97 100644 --- a/crates/ui-egui/src/dialogs/package.rs +++ b/crates/ui-egui/src/dialogs/package.rs @@ -155,32 +155,38 @@ fn packaged(app: &mut VectorcraftApp, r: Result<Value, String>, web: bool, later // The fonts left out: their license doesn't allow it, or they aren't on this computer. let fonts = r["skippedFonts"].as_array().into_iter().flatten().filter_map(|f| f["font"].as_str()).collect::<Vec<_>>().join(", "); let shown_note = package_status_note(missing, &fonts); - let n_s = n.to_string(); + let n = n as u64; if web { let (name, data) = (r["name"].as_str().unwrap_or("package.zip"), r["dataBase64"].as_str().unwrap_or_default()); let bytes = vectorcraft_format::base64_decode(data).ok_or("the package came back damaged")?; io::write_named(app, None, name, &bytes)?; let status = if shown_note.is_empty() { - crate::i18n::fmt(tl!("Packaged {n} file(s)"), &[("n", &n_s)]) + crate::i18n::tn(n, "Packaged {n} file", "Packaged {n} files") } else { - crate::i18n::fmt(tl!("Packaged {n} file(s) {note}"), &[("n", &n_s), ("note", &shown_note)]) + crate::i18n::fmt(&crate::i18n::tn(n, "Packaged {n} file {note}", "Packaged {n} files {note}"), &[("note", &shown_note)]) }; app.status(status); return Ok(r); } let folder = r["folder"].as_str().unwrap_or_default().to_string(); let status = if shown_note.is_empty() { - crate::i18n::fmt(tl!("Packaged {n} file(s) in {folder}"), &[("n", &n_s), ("folder", &folder)]) + crate::i18n::fmt(&crate::i18n::tn(n, "Packaged {n} file in {folder}", "Packaged {n} files in {folder}"), &[("folder", &folder)]) } else { - crate::i18n::fmt(tl!("Packaged {n} file(s) in {folder} {note}"), &[("n", &n_s), ("folder", &folder), ("note", &shown_note)]) + crate::i18n::fmt( + &crate::i18n::tn(n, "Packaged {n} file in {folder} {note}", "Packaged {n} files in {folder} {note}"), + &[("folder", &folder), ("note", &shown_note)], + ) }; app.status(status); let detail = if shown_note.is_empty() { - crate::i18n::fmt(tl!("{count} file(s) in {folder}. Show the package folder?"), &[("count", &n_s), ("folder", &folder)]) + crate::i18n::fmt( + &crate::i18n::tn(n, "{n} file in {folder}. Show the package folder?", "{n} files in {folder}. Show the package folder?"), + &[("folder", &folder)], + ) } else { crate::i18n::fmt( - tl!("{count} file(s) in {folder} {note}. Show the package folder?"), - &[("count", &n_s), ("folder", &folder), ("note", &shown_note)], + &crate::i18n::tn(n, "{n} file in {folder} {note}. Show the package folder?", "{n} files in {folder} {note}. Show the package folder?"), + &[("folder", &folder), ("note", &shown_note)], ) }; if app.ui.dialog.is_none() { @@ -189,12 +195,12 @@ fn packaged(app: &mut VectorcraftApp, r: Result<Value, String>, web: bool, later Ok(r) } -/// Parenthetical notes after the folder path in a package status (`(2 linked file(s) not found)` …), +/// Parenthetical notes after the folder path in a package status (`(2 linked files not found)` …), /// joined with spaces and without a leading space (#3494). -fn package_status_note(missing: usize, fonts: &str) -> String { +pub(super) fn package_status_note(missing: usize, fonts: &str) -> String { let mut parts = Vec::new(); if missing > 0 { - parts.push(format!("({})", crate::i18n::fmt(tl!("{count} linked file(s) not found"), &[("count", &missing.to_string())]))); + parts.push(format!("({})", crate::i18n::tn(missing as u64, "{n} linked file not found", "{n} linked files not found"))); } if !fonts.is_empty() { parts.push(format!("({})", crate::i18n::fmt(tl!("fonts not copied: {fonts}"), &[("fonts", fonts)]))); diff --git a/crates/ui-egui/src/dialogs/tests_package.rs b/crates/ui-egui/src/dialogs/tests_package.rs index cd34213afe..22c5e2a357 100644 --- a/crates/ui-egui/src/dialogs/tests_package.rs +++ b/crates/ui-egui/src/dialogs/tests_package.rs @@ -167,7 +167,7 @@ fn edits_after_ok_do_not_reach_the_package() { gate.open(); background::wait_all(&mut app); assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("package")); - assert!(app.ui.status.starts_with("Packaged 3 file(s) in "), "{}", app.ui.status); + assert!(app.ui.status.starts_with("Packaged 3 files in "), "{}", app.ui.status); let files = files.lock().unwrap(); let (_, bytes) = files.iter().find(|(p, _)| p.ends_with("card.vectorcraft")).unwrap(); assert_eq!(vectorcraft_format::load(bytes).unwrap().node_count(), nodes, "the document as it was at OK"); @@ -213,7 +213,7 @@ fn a_dirty_documents_save_is_written_before_its_package() { release.join().unwrap(); assert_eq!(written(&files), [doc]); assert!(app.background.jobs.is_empty() && !app.session.active().unwrap().is_dirty()); - assert!(app.ui.status.starts_with("Packaged 3 file(s) in "), "the package's status came last: {}", app.ui.status); + assert!(app.ui.status.starts_with("Packaged 3 files in "), "the package's status came last: {}", app.ui.status); } #[test] @@ -254,7 +254,7 @@ fn the_web_downloads_a_zip() { assert!(!frame(&mut app).contains("Location:"), "no folder to choose"); confirm(&mut app).unwrap(); assert!(app.ui.dialog.is_none()); - assert!(app.ui.status.contains("Packaged") && app.ui.status.contains("file(s)"), "{}", app.ui.status); + assert!(app.ui.status.contains("Packaged") && app.ui.status.contains("files"), "{}", app.ui.status); let got = got.borrow(); assert_eq!(got.len(), 1); assert_eq!(got[0].0, "card Folder.zip"); @@ -285,6 +285,23 @@ fn fonts_left_out_of_the_package_are_named() { assert!(app.ui.status.contains(gone), "{}", app.ui.status); } +/// The note on linked files left out of a package uses the form the language's plural rule picks +/// for the count. +#[test] +fn the_missing_links_note_uses_each_count_form() { + let note = |code: &str, missing: usize| { + crate::i18n::set_current(crate::i18n::Lang::from_code(code).unwrap()); + let note = package::package_status_note(missing, ""); + crate::i18n::set_current(crate::i18n::Lang::EN); + note + }; + assert_eq!(note("en", 1), "(1 linked file not found)"); + assert_eq!(note("en", 2), "(2 linked files not found)"); + assert_eq!(note("cs", 1), "(Nenalezen 1 propojený soubor)"); + assert_eq!(note("cs", 2), "(Nenalezeny 2 propojené soubory)"); + assert_eq!(note("cs", 5), "(Nenalezeno 5 propojených souborů)"); +} + #[test] fn package_status_without_notes_has_no_extra_spaces() { let dir = Folder::new("spaces"); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 0becb7e965..fd7a177514 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -203,7 +203,7 @@ font-technology Variable Променливи Apply Paragraph Style Прилагане на стил на абзац Apply SVG Filter… Прилагане на SVG филтър… Apply to All Прилагане към всички - Apply to All ({count} more missing) Прилагане към всички (още {count} липсващи) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Прилагане към всички (още {n} липсващ)|Прилагане към всички (още {n} липсващи) Arc Дъга Arc Lower… Дъга надолу… Arc Tool Инструмент „Дъга“ @@ -2217,7 +2217,7 @@ font-technology Variable Променливи Package Пакет Package collects a saved document with its linked files and fonts. Пакетът събира запазен документ заедно с неговите свързани файлове и шрифтове. Package created Пакетът е създаден - Packaged {n} file(s) in {folder} {note} Пакетирани са {n} файла в {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Пакетиран е {n} файл в {folder} {note}|Пакетирани са {n} файла в {folder} {note} Packaged {n} file(s){note} Пакетирани са {n} файла{note} Package… Пакет… Page Страница @@ -2534,9 +2534,11 @@ font-technology Variable Променливи Stop Спиране Searching… Търсене… Not found Няма намерени резултати - {folders} folder(s) and {files} file(s) searched Претърсени са {folders} папки и {files} файла - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Пропуснати са {count} папки (като системни папки, папки на други приложения и скрити папки) - {count} folder(s) or file(s) couldn't be read {count} папки или файла не можаха да бъдат прочетени + {folders} and {files} searched Претърсени са {folders} и {files} +@plural {n} folder|{n} folders {n} папка|{n} папки +@plural {n} file|{n} files {n} файл|{n} файла +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Пропусната е {n} папка (като системни папки, папки на други приложения и скрити папки)|Пропуснати са {n} папки (като системни папки, папки на други приложения и скрити папки) +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} папка или файл не можа да бъде прочетен|{n} папки или файла не можаха да бъдат прочетени The search stopped at its limit: search a smaller folder. Търсенето спре поради достигане на лимита: потърсете в по-малка папка. Copy only fonts you own or are licensed to install. Копирайте само шрифтове, които притежавате или имате лиценз да инсталирате. VectorCraft copies the fonts to {folder}. VectorCraft копира шрифтовете в {folder}. @@ -3604,13 +3606,13 @@ font-technology Variable Променливи Zoom Tool Инструмент „Мащаб“ Zoom with Mouse Wheel Мащабиране с колелцето на мишката Scrub Numeric Fields by Dragging Плъзгане на числени полета чрез влачене - {count} file(s) in {folder} {note}. Show the package folder? {count} файл(а) в {folder}{note}. Показване на папката на пакета? - {count} linked file(s) not found {count} свързан(и) файл(а) не са намерени +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} файл в {folder} {note}. Показване на папката на пакета?|{n} файла в {folder} {note}. Показване на папката на пакета? +@plural {n} linked file not found|{n} linked files not found {n} свързан файл не е намерен|{n} свързани файла не са намерени fonts not copied: {fonts} некопирани шрифтове: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? {count} свързано(и) изображение(я) е/са променено(и) след запазването на този документ. Показване на новите версии? - {count} linked image(s) changed on disk. Show the new versions? {count} свързано(и) изображение(я) е/са променено(и) на диска. Показване на новите версии? - {count} more rules: Export writes every one. {count} още правила: Експортът записва всяко едно. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} ненаименувани обекта са пропуснати: наименувайте ги или включете „Ненаименувани обекти“ в менюто на панела. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} свързано изображение е променено след запазването на този документ. Показване на новата версия?|{n} свързани изображения са променени след запазването на този документ. Показване на новите версии? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} свързано изображение е променено на диска. Показване на новата версия?|{n} свързани изображения са променени на диска. Показване на новите версии? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. Още {n} правило: Експортът го записва.|Още {n} правила: Експортът записва всяко едно. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} ненаименуван обект е пропуснат: наименувайте го или включете „Ненаименувани обекти“ в менюто на панела.|{n} ненаименувани обекта са пропуснати: наименувайте ги или включете „Ненаименувани обекти“ в менюто на панела. {effect} is already applied {effect} вече е приложен {format} Options Опции за {format} {kind} Gradient {kind} градиент @@ -5505,10 +5507,10 @@ axis Y Axis Y ос @msg Packaged {n} file(s) in {folder} Пакетирани са {n} файла в {folder} @msg Packaged {n} file(s) {note} Пакетирани са {n} файла {note} @msg Packaged {n} file(s) Пакетирани са {n} файла - Packaged {n} file(s) Пакетирани са {n} файла - Packaged {n} file(s) in {folder} Пакетирани са {n} файла в {folder} - Packaged {n} file(s) {note} Пакетирани са {n} файла {note} - {count} file(s) in {folder}. Show the package folder? {count} файл(а) в {folder}. Показване на папката на пакета? +@plural Packaged {n} file|Packaged {n} files Пакетиран е {n} файл|Пакетирани са {n} файла +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Пакетиран е {n} файл в {folder}|Пакетирани са {n} файла в {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Пакетиран е {n} файл {note}|Пакетирани са {n} файла {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} файл в {folder}. Показване на папката на пакета?|{n} файла в {folder}. Показване на папката на пакета? Clockwise По часовниковата стрелка Dither Дитъринг Fine noise hides banding in the gradient fill Фин шум скрива ивиците в градиентната запълка diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index b1635dc7bf..0ff4eeeb64 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -662,7 +662,7 @@ 1 Layer 1 sloj Libraries Biblioteke Links Veze - {count} linked image(s) changed on disk. Show the new versions? Povezanih slika promijenjenih na disku: {count}. Prikazati nove verzije? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? Povezanih slika promijenjenih na disku: {n}. Prikazati nove verzije?|Povezanih slika promijenjenih na disku: {n}. Prikazati nove verzije?|Povezanih slika promijenjenih na disku: {n}. Prikazati nove verzije? Update Changed Links Ažuriraj promijenjene veze @msg Updated {_1} linked file(s) changed on disk Ažurirano povezanih datoteka promijenjenih na disku: {_1} Magic Wand Čarobni štapić @@ -1482,8 +1482,8 @@ lighting Light Svjetlo Select objects to see their CSS, or Generate CSS for the whole document. Odaberite objekte da vidite njihov CSS ili Generiši CSS za cijeli dokument. The selected objects have no CSS of their own (see below). Odabrani objekti nemaju vlastiti CSS (vidi ispod). Units: {units} Jedinice: {units} - {count} more rules: Export writes every one. Još pravila: {count}; izvoz zapisuje svako. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Izostavljeno neimenovanih objekata: {count}; imenujte ih ili uključite Neimenovani objekti u meniju panela. +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. Još pravila: {n}; izvoz zapisuje svako.|Još pravila: {n}; izvoz zapisuje svako.|Još pravila: {n}; izvoz zapisuje svako. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Izostavljeno neimenovanih objekata: {n}; imenujte ih ili uključite Neimenovani objekti u meniju panela.|Izostavljeno neimenovanih objekata: {n}; imenujte ih ili uključite Neimenovani objekti u meniju panela.|Izostavljeno neimenovanih objekata: {n}; imenujte ih ili uključite Neimenovani objekti u meniju panela. All Categories Sve kategorije Repeat Objects Ponovi objekte Save… Sačuvaj… @@ -2376,19 +2376,21 @@ lighting Light Svjetlo Stop Zaustavi Searching… Pretraga… Not found Nije pronađeno - {folders} folder(s) and {files} file(s) searched Pretraženo foldera: {folders}, datoteka: {files} - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Preskočeno foldera: {count}, npr. foldera drugih aplikacija, sistemskih i skrivenih - {count} folder(s) or file(s) couldn't be read Foldera ili datoteka koje nije moguće pročitati: {count} + {folders} and {files} searched Pretraženo: {folders}, {files} +@plural {n} folder|{n} folders {n} folder|{n} foldera|{n} foldera +@plural {n} file|{n} files {n} datoteka|{n} datoteke|{n} datoteka +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Preskočeno foldera: {n}, npr. foldera drugih aplikacija, sistemskih i skrivenih|Preskočeno foldera: {n}, npr. foldera drugih aplikacija, sistemskih i skrivenih|Preskočeno foldera: {n}, npr. foldera drugih aplikacija, sistemskih i skrivenih +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Foldera ili datoteka koje nije moguće pročitati: {n}|Foldera ili datoteka koje nije moguće pročitati: {n}|Foldera ili datoteka koje nije moguće pročitati: {n} The search stopped at its limit: search a smaller folder. Pretraga se zaustavila na svom ograničenju: pretražite manji folder. Copy only fonts you own or are licensed to install. Kopirajte samo fontove koje posjedujete ili imate licencu za instaliranje. VectorCraft copies the fonts to {folder}. VectorCraft kopira fontove u {folder}. - Apply to All ({count} more missing) Primijeni na sve (još {count} nedostaje) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Primijeni na sve (još {n} nedostaje)|Primijeni na sve (još {n} nedostaju)|Primijeni na sve (još {n} nedostaje) Ignore Zanemari Linked File Not Found Povezana datoteka nije pronađena Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Zamijenite je drugom datotekom ili je zanemarite: njene slike i dalje prikazuju pregled sačuvan s dokumentom. Replace… Zamijeni… Update Modified Links Ažuriraj izmijenjene veze - {count} linked image(s) changed since this document was saved. Show the new versions? Povezanih slika promijenjenih otkako je dokument sačuvan: {count}. Prikazati nove verzije? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? Povezanih slika promijenjenih otkako je dokument sačuvan: {n}. Prikazati nove verzije?|Povezanih slika promijenjenih otkako je dokument sačuvan: {n}. Prikazati nove verzije?|Povezanih slika promijenjenih otkako je dokument sačuvan: {n}. Prikazati nove verzije? Dialog Dijalog Convert Process to Global Pretvori procesne u globalne Create From: Kreiraj iz: @@ -2427,12 +2429,12 @@ lighting Light Svjetlo Fonts whose licence doesn't allow embedding are not copied. Fontovi čija licenca ne dozvoljava ugrađivanje ne kopiraju se. Package collects a saved document with its linked files and fonts. Paket prikuplja sačuvani dokument s njegovim povezanim datotekama i fontovima. Package created Paket je kreiran - Packaged {n} file(s) in {folder} {note} Upakovano datoteka u {folder}: {n} {note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Upakovano datoteka u {folder}: {n} {note}|Upakovano datoteka u {folder}: {n} {note}|Upakovano datoteka u {folder}: {n} {note} Packaged {n} file(s){note} Upakovano datoteka: {n}{note} Relink Linked Files to the Document Ponovo poveži povezane datoteke s dokumentom Save the document first? Prvo sačuvati dokument? - {count} file(s) in {folder} {note}. Show the package folder? Datoteka u {folder}: {count} {note}. Prikazati folder paketa? - {count} linked file(s) not found Povezanih datoteka nije pronađeno: {count} +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? Datoteka u {folder}: {n} {note}. Prikazati folder paketa?|Datoteka u {folder}: {n} {note}. Prikazati folder paketa?|Datoteka u {folder}: {n} {note}. Prikazati folder paketa? +@plural {n} linked file not found|{n} linked files not found Povezanih datoteka nije pronađeno: {n}|Povezanih datoteka nije pronađeno: {n}|Povezanih datoteka nije pronađeno: {n} fonts not copied: {fonts} fontovi nisu kopirani: {fonts} Built-in presets are read-only: New… starts an editable copy. Ugrađeni predlošci su samo za čitanje: Novo… započinje kopiju koja se može uređivati. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} na radnoj ploči predstavlja {real} {unit} u sceni. @@ -5525,10 +5527,10 @@ axis Y Axis Y osa @msg Packaged {n} file(s) in {folder} Upakovano datoteka u {folder}: {n} @msg Packaged {n} file(s) {note} Upakovano datoteka: {n} {note} @msg Packaged {n} file(s) Upakovano datoteka: {n} - Packaged {n} file(s) Upakovano datoteka: {n} - Packaged {n} file(s) in {folder} Upakovano datoteka u {folder}: {n} - Packaged {n} file(s) {note} Upakovano datoteka: {n} {note} - {count} file(s) in {folder}. Show the package folder? Datoteka u {folder}: {count}. Prikazati folder paketa? +@plural Packaged {n} file|Packaged {n} files Upakovano datoteka: {n}|Upakovano datoteka: {n}|Upakovano datoteka: {n} +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Upakovano datoteka u {folder}: {n}|Upakovano datoteka u {folder}: {n}|Upakovano datoteka u {folder}: {n} +@plural Packaged {n} file {note}|Packaged {n} files {note} Upakovano datoteka: {n} {note}|Upakovano datoteka: {n} {note}|Upakovano datoteka: {n} {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? Datoteka u {folder}: {n}. Prikazati folder paketa?|Datoteka u {folder}: {n}. Prikazati folder paketa?|Datoteka u {folder}: {n}. Prikazati folder paketa? Clockwise U smjeru kazaljke na satu Dither Dithering Fine noise hides banding in the gradient fill Fini šum skriva trake u gradijentnoj ispuni diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index b875d10672..04608e692c 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -320,7 +320,7 @@ Apply Paragraph Style Aplica l’estil de paràgraf Apply SVG Filter… Aplica el filtre SVG… Apply to All Aplica-ho a tot - Apply to All ({count} more missing) Aplica-ho a tot ({count} més que falten) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Aplica-ho a tot ({n} més que falta)|Aplica-ho a tot ({n} més que falten) Apply {name} Aplica {name} Approximate path Aproxima el traçat Arabic Àrab @@ -2812,10 +2812,10 @@ Package Empaqueta Package collects a saved document with its linked files and fonts. L’empaquetatge recull un document desat amb els fitxers enllaçats i els tipus de lletra. Package created Empaquetatge creat - Packaged {n} file(s) S’han empaquetat {n} fitxers - Packaged {n} file(s) in {folder} S’han empaquetat {n} fitxers a {folder} - Packaged {n} file(s) in {folder} {note} S’han empaquetat {n} fitxers a {folder} {note} - Packaged {n} file(s) {note} S’han empaquetat {n} fitxers {note} +@plural Packaged {n} file|Packaged {n} files S’ha empaquetat {n} fitxer|S’han empaquetat {n} fitxers +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} S’ha empaquetat {n} fitxer a {folder}|S’han empaquetat {n} fitxers a {folder} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} S’ha empaquetat {n} fitxer a {folder} {note}|S’han empaquetat {n} fitxers a {folder} {note} +@plural Packaged {n} file {note}|Packaged {n} files {note} S’ha empaquetat {n} fitxer {note}|S’han empaquetat {n} fitxers {note} Packaged {n} file(s){note} S’han empaquetat {n} fitxers{note} Package… Empaqueta… Page Pàgina @@ -4653,19 +4653,21 @@ Zoom to Selection Amplia a la selecció Zoom Tool Eina de zoom Zoom with Mouse Wheel Zoom amb la roda del ratolí - {count} file(s) in {folder} {note}. Show the package folder? {count} fitxer(s) a {folder} {note}. Voleu mostrar la carpeta del paquet? - {count} file(s) in {folder}. Show the package folder? {count} fitxer(s) a {folder}. Voleu mostrar la carpeta del paquet? - {count} folder(s) or file(s) couldn't be read No s’han pogut llegir {count} carpeta(es) o fitxer(s) - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones S’han omès {count} carpeta(es), com ara les d’altres aplicacions, les del sistema i les ocultes - {count} linked file(s) not found No s’han trobat {count} fitxer(s) enllaçat(s) - {count} linked image(s) changed on disk. Show the new versions? {count} imatge(s) enllaçada(es) han canviat al disc. Voleu mostrar les versions noves? - {count} linked image(s) changed since this document was saved. Show the new versions? {count} imatge(s) enllaçada(es) han canviat des que es va desar aquest document. Voleu mostrar les versions noves? - {count} more rules: Export writes every one. {count} regles més: l’exportació les escriu totes. +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fitxer a {folder} {note}. Voleu mostrar la carpeta del paquet?|{n} fitxers a {folder} {note}. Voleu mostrar la carpeta del paquet? +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} fitxer a {folder}. Voleu mostrar la carpeta del paquet?|{n} fitxers a {folder}. Voleu mostrar la carpeta del paquet? +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read No s’ha pogut llegir {n} carpeta o fitxer|No s’han pogut llegir {n} carpetes o fitxers +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones S’ha omès {n} carpeta, com ara les d’altres aplicacions, les del sistema i les ocultes|S’han omès {n} carpetes, com ara les d’altres aplicacions, les del sistema i les ocultes +@plural {n} linked file not found|{n} linked files not found No s’ha trobat {n} fitxer enllaçat|No s’han trobat {n} fitxers enllaçats +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} imatge enllaçada ha canviat al disc. Voleu mostrar la versió nova?|{n} imatges enllaçades han canviat al disc. Voleu mostrar les versions noves? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} imatge enllaçada ha canviat des que es va desar aquest document. Voleu mostrar la versió nova?|{n} imatges enllaçades han canviat des que es va desar aquest document. Voleu mostrar les versions noves? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regla més: l’exportació l’escriu.|{n} regles més: l’exportació les escriu totes. {count} of {total} artboards {count} de {total} taulers - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. S’han omès {count} objectes sense nom: poseu-los un nom o activeu Objectes sense nom al menú del panell. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. S’ha omès {n} objecte sense nom: poseu-li un nom o activeu Objectes sense nom al menú del panell.|S’han omès {n} objectes sense nom: poseu-los un nom o activeu Objectes sense nom al menú del panell. {effect} is already applied {effect} ja està aplicat {file}, line {line} {file}, línia {line} - {folders} folder(s) and {files} file(s) searched S’han cercat {folders} carpeta(es) i {files} fitxer(s) + {folders} and {files} searched S’han cercat {folders} i {files} +@plural {n} folder|{n} folders {n} carpeta|{n} carpetes +@plural {n} file|{n} files {n} fitxer|{n} fitxers {format} Options Opcions de {format} {kind} Gradient Degradat {kind} {kind} Style Options… Opcions d’estil de {kind}… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 6452812168..28929b1cf8 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -672,7 +672,7 @@ 1 Layer 1 vrstva Libraries Knihovny Links Propojení - {count} linked image(s) changed on disk. Show the new versions? Počet propojených obrázků změněných na disku: {count}. Zobrazit nové verze? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? Na disku se změnil {n} propojený obrázek. Zobrazit novou verzi?|Na disku se změnily {n} propojené obrázky. Zobrazit nové verze?|Na disku se změnilo {n} propojených obrázků. Zobrazit nové verze? Update Changed Links Aktualizovat změněná propojení @msg Updated {_1} linked file(s) changed on disk Aktualizováno propojených souborů změněných na disku: {_1} Magic Wand Kouzelná hůlka @@ -1505,8 +1505,8 @@ lighting Light Světlo Select objects to see their CSS, or Generate CSS for the whole document. Vyberte objekty, abyste viděli jejich CSS, nebo vygenerujte CSS pro celý dokument. The selected objects have no CSS of their own (see below). Vybrané objekty nemají vlastní CSS (viz níže). Units: {units} Jednotky: {units} - {count} more rules: Export writes every one. Další pravidla ({count}): Export zapíše všechna. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Vynecháno nepojmenovaných objektů: {count}. Pojmenujte je, nebo v nabídce panelu zapněte Nepojmenované objekty. +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. Další {n} pravidlo: Export ho zapíše.|Další {n} pravidla: Export zapíše všechna.|Dalších {n} pravidel: Export zapíše všechna. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Vynechán {n} nepojmenovaný objekt. Pojmenujte ho, nebo v nabídce panelu zapněte Nepojmenované objekty.|Vynechány {n} nepojmenované objekty. Pojmenujte je, nebo v nabídce panelu zapněte Nepojmenované objekty.|Vynecháno {n} nepojmenovaných objektů. Pojmenujte je, nebo v nabídce panelu zapněte Nepojmenované objekty. All Categories Všechny kategorie Repeat Objects Objekty opakování Save… Uložit… @@ -2403,19 +2403,21 @@ lighting Light Světlo Stop Zastavit Searching… Hledání… Not found Nenalezeno - {folders} folder(s) and {files} file(s) searched Prohledáno složek: {folders}, souborů: {files} - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Přeskočeno složek: {count} (např. složky jiných aplikací, systému a skryté složky) - {count} folder(s) or file(s) couldn't be read Nepodařilo se přečíst složek nebo souborů: {count} + {folders} and {files} searched Prohledáno: {folders}, {files} +@plural {n} folder|{n} folders {n} složka|{n} složky|{n} složek +@plural {n} file|{n} files {n} soubor|{n} soubory|{n} souborů +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Přeskočena {n} složka (např. složky jiných aplikací, systému a skryté složky)|Přeskočeny {n} složky (např. složky jiných aplikací, systému a skryté složky)|Přeskočeno {n} složek (např. složky jiných aplikací, systému a skryté složky) +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Nepodařilo se přečíst {n} složku nebo soubor|Nepodařilo se přečíst {n} složky nebo soubory|Nepodařilo se přečíst {n} složek nebo souborů The search stopped at its limit: search a smaller folder. Hledání se zastavilo na limitu: prohledejte menší složku. Copy only fonts you own or are licensed to install. Kopírujte jen písma, která vlastníte nebo máte licenci instalovat. VectorCraft copies the fonts to {folder}. VectorCraft zkopíruje písma do {folder}. - Apply to All ({count} more missing) Použít na všechny (chybí ještě {count}) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Použít na všechny (chybí ještě {n})|Použít na všechny (chybí ještě {n})|Použít na všechny (chybí ještě {n}) Ignore Ignorovat Linked File Not Found Propojený soubor nebyl nalezen Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Nahraďte jej jiným souborem, nebo jej ignorujte: jeho obrázky dál zobrazují náhled uložený s dokumentem. Replace… Nahradit… Update Modified Links Aktualizovat upravená propojení - {count} linked image(s) changed since this document was saved. Show the new versions? Počet propojených obrázků změněných od uložení dokumentu: {count}. Zobrazit nové verze? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? Od uložení dokumentu se změnil {n} propojený obrázek. Zobrazit novou verzi?|Od uložení dokumentu se změnily {n} propojené obrázky. Zobrazit nové verze?|Od uložení dokumentu se změnilo {n} propojených obrázků. Zobrazit nové verze? Dialog Dialogové okno Convert Process to Global Převést procesní na globální Create From: Vytvořit z: @@ -2454,12 +2456,12 @@ lighting Light Světlo Fonts whose licence doesn't allow embedding are not copied. Písma, jejichž licence nepovoluje vkládání, se nekopírují. Package collects a saved document with its linked files and fonts. Sbalení shromáždí uložený dokument s jeho propojenými soubory a písmy. Package created Balíček vytvořen - Packaged {n} file(s) in {folder} {note} Zabaleno souborů: {n} do {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Zabalen {n} soubor do {folder} {note}|Zabaleny {n} soubory do {folder} {note}|Zabaleno {n} souborů do {folder} {note} Packaged {n} file(s){note} Zabaleno souborů: {n}{note} Relink Linked Files to the Document Znovu propojit propojené soubory s dokumentem Save the document first? Nejprve uložit dokument? - {count} file(s) in {folder} {note}. Show the package folder? Souborů: {count} v {folder}{note}. Zobrazit složku balíčku? - {count} linked file(s) not found Nenalezeno propojených souborů: {count} +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} soubor v {folder} {note}. Zobrazit složku balíčku?|{n} soubory v {folder} {note}. Zobrazit složku balíčku?|{n} souborů v {folder} {note}. Zobrazit složku balíčku? +@plural {n} linked file not found|{n} linked files not found Nenalezen {n} propojený soubor|Nenalezeny {n} propojené soubory|Nenalezeno {n} propojených souborů fonts not copied: {fonts} nezkopírovaná písma: {fonts} Built-in presets are read-only: New… starts an editable copy. Vestavěná přednastavení jsou jen pro čtení: Nový… vytvoří kopii, kterou lze upravit. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} na pracovní ploše odpovídá {real} {unit} ve scéně. @@ -5594,10 +5596,10 @@ axis Y Axis osa Y @msg Packaged {n} file(s) in {folder} Zabaleno souborů: {n} do {folder} @msg Packaged {n} file(s) {note} Zabaleno souborů: {n} {note} @msg Packaged {n} file(s) Zabaleno souborů: {n} - Packaged {n} file(s) Zabaleno souborů: {n} - Packaged {n} file(s) in {folder} Zabaleno souborů: {n} do {folder} - Packaged {n} file(s) {note} Zabaleno souborů: {n} {note} - {count} file(s) in {folder}. Show the package folder? Souborů: {count} v {folder}. Zobrazit složku balíčku? +@plural Packaged {n} file|Packaged {n} files Zabalen {n} soubor|Zabaleny {n} soubory|Zabaleno {n} souborů +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Zabalen {n} soubor do {folder}|Zabaleny {n} soubory do {folder}|Zabaleno {n} souborů do {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Zabalen {n} soubor {note}|Zabaleny {n} soubory {note}|Zabaleno {n} souborů {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} soubor v {folder}. Zobrazit složku balíčku?|{n} soubory v {folder}. Zobrazit složku balíčku?|{n} souborů v {folder}. Zobrazit složku balíčku? Clockwise Ve směru hodinových ručiček Dither Rozptýlení Fine noise hides banding in the gradient fill Jemný šum skryje pruhy ve výplni přechodem diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index fb80dcc0c7..cd1eb284af 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -624,7 +624,7 @@ 1 Layer 1 lag Libraries Biblioteker Links Links - {count} linked image(s) changed on disk. Show the new versions? {count} linket billede(r) er ændret på disken. Vis de nye versioner? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} linket billede er ændret på disken. Vis den nye version?|{n} linkede billeder er ændret på disken. Vis de nye versioner? Update Changed Links Opdatér ændrede links @msg Updated {_1} linked file(s) changed on disk Opdaterede {_1} linket fil(er) ændret på disken Magic Wand Magisk tryllestav @@ -1419,8 +1419,8 @@ lighting Light Lys Select objects to see their CSS, or Generate CSS for the whole document. Markér objekter for at se deres CSS, eller generér CSS for hele dokumentet. The selected objects have no CSS of their own (see below). De markerede objekter har ingen egen CSS (se nedenfor). Units: {units} Enheder: {units} - {count} more rules: Export writes every one. {count} flere regler: Eksport skriver hver enkelt. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} unavngivne objekter udeladt: giv dem navne, eller aktivér Unavngivne objekter i panelmenuen. +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regel mere: Eksport skriver den.|{n} flere regler: Eksport skriver hver enkelt. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} unavngivet objekt udeladt: giv det et navn, eller aktivér Unavngivne objekter i panelmenuen.|{n} unavngivne objekter udeladt: giv dem navne, eller aktivér Unavngivne objekter i panelmenuen. All Categories Alle kategorier Repeat Objects Gentagelsesobjekter Save… Gem… @@ -2196,19 +2196,21 @@ lighting Light Lys Stop Stop Searching… Søger… Not found Ikke fundet - {folders} folder(s) and {files} file(s) searched {folders} mappe(r) og {files} fil(er) gennemsøgt - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} mappe(r) sprunget over, f.eks. andre apps' og systemets mapper samt skjulte mapper - {count} folder(s) or file(s) couldn't be read {count} mappe(r) eller fil(er) kunne ikke læses + {folders} and {files} searched {folders} og {files} gennemsøgt +@plural {n} folder|{n} folders {n} mappe|{n} mapper +@plural {n} file|{n} files {n} fil|{n} filer +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} mappe sprunget over, f.eks. andre apps' og systemets mapper samt skjulte mapper|{n} mapper sprunget over, f.eks. andre apps' og systemets mapper samt skjulte mapper +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} mappe eller fil kunne ikke læses|{n} mapper eller filer kunne ikke læses The search stopped at its limit: search a smaller folder. Søgningen stoppede ved sin grænse: søg i en mindre mappe. Copy only fonts you own or are licensed to install. Kopiér kun skrifttyper, du ejer eller har licens til at installere. VectorCraft copies the fonts to {folder}. VectorCraft kopierer skrifttyperne til {folder}. - Apply to All ({count} more missing) Anvend på alle ({count} flere mangler) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Anvend på alle ({n} mere mangler)|Anvend på alle ({n} flere mangler) Ignore Ignorér Linked File Not Found Linket fil blev ikke fundet Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Erstat den med en anden fil, eller ignorér den: dens billeder viser stadig den forhåndsvisning, der er gemt sammen med dokumentet. Replace… Erstat… Update Modified Links Opdatér ændrede links - {count} linked image(s) changed since this document was saved. Show the new versions? {count} linkede billede(r) er ændret, siden dette dokument blev gemt. Vis de nye versioner? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} linket billede er ændret, siden dette dokument blev gemt. Vis den nye version?|{n} linkede billeder er ændret, siden dette dokument blev gemt. Vis de nye versioner? Dialog Dialog Convert Process to Global Konvertér procesfarve til global Create From: Opret ud fra: @@ -2247,12 +2249,12 @@ lighting Light Lys Fonts whose licence doesn't allow embedding are not copied. Skrifttyper, hvis licens ikke tillader indlejring, kopieres ikke. Package collects a saved document with its linked files and fonts. Pakning samler et gemt dokument med dets linkede filer og skrifttyper. Package created Pakke oprettet - Packaged {n} file(s) in {folder} {note} Pakkede {n} fil(er) i {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Pakkede {n} fil i {folder} {note}|Pakkede {n} filer i {folder} {note} Packaged {n} file(s){note} Pakkede {n} fil(er){note} Relink Linked Files to the Document Genopret link til dokumentets linkede filer Save the document first? Gem dokumentet først? - {count} file(s) in {folder} {note}. Show the package folder? {count} fil(er) i {folder}{note}. Vis pakkemappen? - {count} linked file(s) not found {count} linkede fil(er) ikke fundet +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fil i {folder} {note}. Vis pakkemappen?|{n} filer i {folder} {note}. Vis pakkemappen? +@plural {n} linked file not found|{n} linked files not found {n} linket fil ikke fundet|{n} linkede filer ikke fundet fonts not copied: {fonts} skrifttyper ikke kopieret: {fonts} Built-in presets are read-only: New… starts an editable copy. Indbyggede forudindstillinger er skrivebeskyttede: Ny… starter en redigerbar kopi. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} på tegnebrættet svarer til {real} {unit} i scenen. @@ -5520,10 +5522,10 @@ axis Y Axis Y-akse @msg Packaged {n} file(s) in {folder} Pakkede {n} fil(er) i {folder} @msg Packaged {n} file(s) {note} Pakkede {n} fil(er) {note} @msg Packaged {n} file(s) Pakkede {n} fil(er) - Packaged {n} file(s) Pakkede {n} fil(er) - Packaged {n} file(s) in {folder} Pakkede {n} fil(er) i {folder} - Packaged {n} file(s) {note} Pakkede {n} fil(er) {note} - {count} file(s) in {folder}. Show the package folder? {count} fil(er) i {folder}. Vis pakkemappen? +@plural Packaged {n} file|Packaged {n} files Pakkede {n} fil|Pakkede {n} filer +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Pakkede {n} fil i {folder}|Pakkede {n} filer i {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Pakkede {n} fil {note}|Pakkede {n} filer {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} fil i {folder}. Vis pakkemappen?|{n} filer i {folder}. Vis pakkemappen? Clockwise Med uret Dither Dither Fine noise hides banding in the gradient fill Fin støj skjuler striber i gradientfyldet diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 1ea0d5f0d9..00b281ec71 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -192,7 +192,7 @@ font-technology Variable Variabel Apply Paragraph Style Absatzformat anwenden Apply SVG Filter… SVG-Filter anwenden… Apply to All Auf alle anwenden - Apply to All ({count} more missing) Auf alle anwenden ({count} weitere fehlen) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Auf alle anwenden ({n} weitere fehlt)|Auf alle anwenden ({n} weitere fehlen) Arc Bogen Arc Lower… Bogen unten… Arc Tool Bogen-Werkzeug @@ -2230,7 +2230,7 @@ file-filter Templates Vorlagen Package Verpacken Package collects a saved document with its linked files and fonts. „Verpacken“ sammelt ein gespeichertes Dokument mit seinen verknüpften Dateien und Schriften. Package created Paket erstellt - Packaged {n} file(s) in {folder} {note} {n} Datei(en) in {folder} verpackt{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} Datei in {folder} verpackt {note}|{n} Dateien in {folder} verpackt {note} Packaged {n} file(s){note} {n} Datei(en) verpackt{note} Package… Verpacken… Page Seite @@ -2554,9 +2554,11 @@ mark-style Japanese Japanisch Stop Stoppen Searching… Suche läuft… Not found Nicht gefunden - {folders} folder(s) and {files} file(s) searched {folders} Ordner und {files} Datei(en) durchsucht - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} Ordner übersprungen, etwa Ordner anderer Apps und des Systems sowie versteckte Ordner - {count} folder(s) or file(s) couldn't be read {count} Ordner oder Datei(en) konnten nicht gelesen werden + {folders} and {files} searched {folders} und {files} durchsucht +@plural {n} folder|{n} folders {n} Ordner|{n} Ordner +@plural {n} file|{n} files {n} Datei|{n} Dateien +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} Ordner übersprungen, etwa Ordner anderer Apps und des Systems sowie versteckte Ordner|{n} Ordner übersprungen, etwa Ordner anderer Apps und des Systems sowie versteckte Ordner +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} Ordner oder Datei konnte nicht gelesen werden|{n} Ordner oder Dateien konnten nicht gelesen werden The search stopped at its limit: search a smaller folder. Die Suche hat ihr Limit erreicht: Durchsuchen Sie einen kleineren Ordner. Copy only fonts you own or are licensed to install. Kopieren Sie nur Schriften, die Ihnen gehören oder für deren Installation Sie eine Lizenz haben. VectorCraft copies the fonts to {folder}. VectorCraft kopiert die Schriften nach {folder}. @@ -3591,12 +3593,12 @@ effect Points Punkte Zoom Tool Zoom-Werkzeug Zoom with Mouse Wheel Mit Mausrad zoomen Scrub Numeric Fields by Dragging Zahlenfelder durch Ziehen ändern - {count} file(s) in {folder} {note}. Show the package folder? {count} Datei(en) in {folder} {note}. Paketordner anzeigen? - {count} linked file(s) not found {count} verknüpfte Datei(en) nicht gefunden +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} Datei in {folder} {note}. Paketordner anzeigen?|{n} Dateien in {folder} {note}. Paketordner anzeigen? +@plural {n} linked file not found|{n} linked files not found {n} verknüpfte Datei nicht gefunden|{n} verknüpfte Dateien nicht gefunden fonts not copied: {fonts} nicht kopierte Schriften: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? {count} verknüpfte(s) Bild(er) wurde(n) seit dem Speichern dieses Dokuments geändert. Die neuen Versionen anzeigen? - {count} more rules: Export writes every one. {count} weitere Regeln: Der Export schreibt alle. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} unbenannte Objekte ausgelassen: Benennen Sie sie oder aktivieren Sie „Unbenannte Objekte“ im Bedienfeldmenü. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} verknüpftes Bild wurde seit dem Speichern dieses Dokuments geändert. Die neue Version anzeigen?|{n} verknüpfte Bilder wurden seit dem Speichern dieses Dokuments geändert. Die neuen Versionen anzeigen? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} weitere Regel: Der Export schreibt sie.|{n} weitere Regeln: Der Export schreibt alle. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} unbenanntes Objekt ausgelassen: Benennen Sie es oder aktivieren Sie „Unbenannte Objekte“ im Bedienfeldmenü.|{n} unbenannte Objekte ausgelassen: Benennen Sie sie oder aktivieren Sie „Unbenannte Objekte“ im Bedienfeldmenü. {effect} is already applied {effect} ist bereits angewendet {format} Options {format}-Optionen {kind} Gradient Verlauf ({kind}) @@ -4580,7 +4582,7 @@ theme Appearance Erscheinungsbild @msg Imported library {name} Bibliothek {name} importiert # Linked files changed on disk. Update Changed Links Geänderte Verknüpfungen aktualisieren - {count} linked image(s) changed on disk. Show the new versions? {count} verknüpfte(s) Bild(er) wurde(n) auf dem Datenträger geändert. Neue Versionen anzeigen? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} verknüpftes Bild wurde auf dem Datenträger geändert. Neue Version anzeigen?|{n} verknüpfte Bilder wurden auf dem Datenträger geändert. Neue Versionen anzeigen? @msg Updated {_1} linked file(s) changed on disk {_1} auf dem Datenträger geänderte verknüpfte Datei(en) aktualisiert # Window: the system's title bar (Windows, Linux). System Title Bar Systemtitelleiste @@ -5175,10 +5177,10 @@ axis Y Axis Y-Achse @msg Packaged {n} file(s) in {folder} {n} Datei(en) in {folder} verpackt @msg Packaged {n} file(s) {note} {n} Datei(en) verpackt {note} @msg Packaged {n} file(s) {n} Datei(en) verpackt - Packaged {n} file(s) {n} Datei(en) verpackt - Packaged {n} file(s) in {folder} {n} Datei(en) in {folder} verpackt - Packaged {n} file(s) {note} {n} Datei(en) verpackt {note} - {count} file(s) in {folder}. Show the package folder? {count} Datei(en) in {folder}. Paketordner anzeigen? +@plural Packaged {n} file|Packaged {n} files {n} Datei verpackt|{n} Dateien verpackt +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} Datei in {folder} verpackt|{n} Dateien in {folder} verpackt +@plural Packaged {n} file {note}|Packaged {n} files {note} {n} Datei verpackt {note}|{n} Dateien verpackt {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} Datei in {folder}. Paketordner anzeigen?|{n} Dateien in {folder}. Paketordner anzeigen? Clockwise Im Uhrzeigersinn Dither Dithering Fine noise hides banding in the gradient fill Feines Rauschen verbirgt Streifen in der Verlaufsfläche diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 383e9b4343..2ff75d2053 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -196,7 +196,7 @@ font-technology Variable Μεταβλητές Apply Paragraph Style Εφαρμογή στυλ παραγράφου Apply SVG Filter… Εφαρμογή φίλτρου SVG… Apply to All Εφαρμογή σε όλα - Apply to All ({count} more missing) Εφαρμογή σε όλα (λείπουν ακόμη {count}) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Εφαρμογή σε όλα (λείπει ακόμη {n})|Εφαρμογή σε όλα (λείπουν ακόμη {n}) Arc Τόξο Arc Lower… Κάτω τόξο… Arc Tool Τόξο (Arc Tool) @@ -2928,7 +2928,7 @@ theme Appearance Εμφάνιση Override Character Color Παράκαμψη χρώματος χαρακτήρων Package collects a saved document with its linked files and fonts. Η συσκευασία συγκεντρώνει ένα αποθηκευμένο έγγραφο μαζί με συνδεδεμένα αρχεία και γραμματοσειρές. Package created Η συσκευασία δημιουργήθηκε - Packaged {n} file(s) in {folder} {note} Συσκευάστηκαν {n} αρχεία στον φάκελο {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Συσκευάστηκε {n} αρχείο στον φάκελο {folder} {note}|Συσκευάστηκαν {n} αρχεία στον φάκελο {folder} {note} Packaged {n} file(s){note} Συσκευάστηκαν {n} αρχεία{note} Page Σελίδα Page information Πληροφορίες σελίδας @@ -3157,9 +3157,11 @@ theme Appearance Εμφάνιση Find Fonts Εύρεση γραμματοσειρών Searching… Αναζήτηση… Not found Δεν βρέθηκε - {folders} folder(s) and {files} file(s) searched Έγινε αναζήτηση σε {folders} φακέλους και {files} αρχεία - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Παραλείφθηκαν {count} φάκελοι, όπως φάκελοι άλλων εφαρμογών, του συστήματος και κρυφοί φάκελοι - {count} folder(s) or file(s) couldn't be read Δεν ήταν δυνατή η ανάγνωση {count} φακέλων ή αρχείων + {folders} and {files} searched Έγινε αναζήτηση: {folders}, {files} +@plural {n} folder|{n} folders {n} φάκελος|{n} φάκελοι +@plural {n} file|{n} files {n} αρχείο|{n} αρχεία +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Παραλείφθηκε {n} φάκελος, όπως φάκελοι άλλων εφαρμογών, του συστήματος και κρυφοί φάκελοι|Παραλείφθηκαν {n} φάκελοι, όπως φάκελοι άλλων εφαρμογών, του συστήματος και κρυφοί φάκελοι +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Δεν ήταν δυνατή η ανάγνωση {n} φακέλου ή αρχείου|Δεν ήταν δυνατή η ανάγνωση {n} φακέλων ή αρχείων The search stopped at its limit: search a smaller folder. Η αναζήτηση έφτασε στο όριό της: επιλέξτε μικρότερο φάκελο. Copy only fonts you own or are licensed to install. Αντιγράψτε μόνο γραμματοσειρές που σας ανήκουν ή έχετε άδεια να εγκαταστήσετε. VectorCraft copies the fonts to {folder}. Το VectorCraft αντιγράφει τις γραμματοσειρές στον φάκελο {folder}. @@ -3922,13 +3924,13 @@ theme Appearance Εμφάνιση Zoom to Selection Ζουμ στην επιλογή Zoom with Mouse Wheel Ζουμ με τον τροχό του ποντικιού Scrub Numeric Fields by Dragging Ρύθμιση αριθμητικών πεδίων με σύρσιμο - {count} file(s) in {folder} {note}. Show the package folder? {count} αρχεία στον φάκελο {folder}{note}. Να εμφανιστεί ο φάκελος συσκευασίας; - {count} linked file(s) not found Δεν βρέθηκαν {count} συνδεδεμένα αρχεία +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} αρχείο στον φάκελο {folder} {note}. Να εμφανιστεί ο φάκελος συσκευασίας;|{n} αρχεία στον φάκελο {folder} {note}. Να εμφανιστεί ο φάκελος συσκευασίας; +@plural {n} linked file not found|{n} linked files not found Δεν βρέθηκε {n} συνδεδεμένο αρχείο|Δεν βρέθηκαν {n} συνδεδεμένα αρχεία fonts not copied: {fonts} γραμματοσειρές που δεν αντιγράφηκαν: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? {count} συνδεδεμένες εικόνες άλλαξαν μετά την αποθήκευση του εγγράφου. Να εμφανιστούν οι νέες εκδόσεις; - {count} linked image(s) changed on disk. Show the new versions? {count} συνδεδεμένες εικόνες άλλαξαν στον δίσκο. Να εμφανιστούν οι νέες εκδόσεις; - {count} more rules: Export writes every one. {count} ακόμη κανόνες: η εξαγωγή περιλαμβάνει όλους. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Παραλείφθηκαν {count} αντικείμενα χωρίς όνομα: ονομάστε τα ή ενεργοποιήστε τα Αντικείμενα χωρίς όνομα από το μενού του πίνακα. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} συνδεδεμένη εικόνα άλλαξε μετά την αποθήκευση του εγγράφου. Να εμφανιστεί η νέα έκδοση;|{n} συνδεδεμένες εικόνες άλλαξαν μετά την αποθήκευση του εγγράφου. Να εμφανιστούν οι νέες εκδόσεις; +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} συνδεδεμένη εικόνα άλλαξε στον δίσκο. Να εμφανιστεί η νέα έκδοση;|{n} συνδεδεμένες εικόνες άλλαξαν στον δίσκο. Να εμφανιστούν οι νέες εκδόσεις; +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} ακόμη κανόνας: η εξαγωγή τον περιλαμβάνει.|{n} ακόμη κανόνες: η εξαγωγή περιλαμβάνει όλους. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Παραλείφθηκε {n} αντικείμενο χωρίς όνομα: ονομάστε το ή ενεργοποιήστε τα Αντικείμενα χωρίς όνομα από το μενού του πίνακα.|Παραλείφθηκαν {n} αντικείμενα χωρίς όνομα: ονομάστε τα ή ενεργοποιήστε τα Αντικείμενα χωρίς όνομα από το μενού του πίνακα. {effect} is already applied Το εφέ {effect} έχει ήδη εφαρμοστεί {format} Options Επιλογές {format} {kind} Gradient Ντεγκραντέ {kind} @@ -5546,10 +5548,10 @@ axis Y Axis Άξονας Y @msg Packaged {n} file(s) in {folder} Συσκευάστηκαν {n} αρχεία στον φάκελο {folder} @msg Packaged {n} file(s) {note} Συσκευάστηκαν {n} αρχεία {note} @msg Packaged {n} file(s) Συσκευάστηκαν {n} αρχεία - Packaged {n} file(s) Συσκευάστηκαν {n} αρχεία - Packaged {n} file(s) in {folder} Συσκευάστηκαν {n} αρχεία στον φάκελο {folder} - Packaged {n} file(s) {note} Συσκευάστηκαν {n} αρχεία {note} - {count} file(s) in {folder}. Show the package folder? {count} αρχεία στον φάκελο {folder}. Να εμφανιστεί ο φάκελος συσκευασίας; +@plural Packaged {n} file|Packaged {n} files Συσκευάστηκε {n} αρχείο|Συσκευάστηκαν {n} αρχεία +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Συσκευάστηκε {n} αρχείο στον φάκελο {folder}|Συσκευάστηκαν {n} αρχεία στον φάκελο {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Συσκευάστηκε {n} αρχείο {note}|Συσκευάστηκαν {n} αρχεία {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} αρχείο στον φάκελο {folder}. Να εμφανιστεί ο φάκελος συσκευασίας;|{n} αρχεία στον φάκελο {folder}. Να εμφανιστεί ο φάκελος συσκευασίας; Clockwise Δεξιόστροφα Dither Πρόσθεση θορύβου Fine noise hides banding in the gradient fill Ο λεπτός θόρυβος κρύβει τις λωρίδες στο γέμισμα ντεγκραντέ diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 80d54c074e..693173a181 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -217,7 +217,7 @@ font-technology Variable Variables Apply Paragraph Style Aplicar estilo de párrafo Apply SVG Filter… Aplicar filtro SVG… Apply to All Aplicar a todo - Apply to All ({count} more missing) Aplicar a todo (faltan {count} más) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Aplicar a todo (falta {n} más)|Aplicar a todo (faltan {n} más) Arc Arco Arc Lower… Arco inferior… Arc Tool Herramienta Arco @@ -2272,7 +2272,7 @@ font-technology Variable Variables Package Empaquetar Package collects a saved document with its linked files and fonts. Empaquetar reúne un documento guardado con sus archivos vinculados y fuentes. Package created Paquete creado - Packaged {n} file(s) in {folder} {note} Se empaquetaron {n} archivo(s) en {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Se empaquetó {n} archivo en {folder} {note}|Se empaquetaron {n} archivos en {folder} {note} Packaged {n} file(s){note} Se empaquetaron {n} archivo(s){note} Package… Empaquetar… Page Página @@ -2592,9 +2592,11 @@ font-technology Variable Variables Stop Detener Searching… Buscando… Not found No se encontró - {folders} folder(s) and {files} file(s) searched Se buscó en {folders} carpeta(s) y {files} archivo(s) - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Se omitieron {count} carpeta(s), como las de otras aplicaciones y del sistema y las ocultas - {count} folder(s) or file(s) couldn't be read No se pudieron leer {count} carpeta(s) o archivo(s) + {folders} and {files} searched Se buscó en {folders} y {files} +@plural {n} folder|{n} folders {n} carpeta|{n} carpetas +@plural {n} file|{n} files {n} archivo|{n} archivos +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Se omitió {n} carpeta, como las de otras aplicaciones y del sistema y las ocultas|Se omitieron {n} carpetas, como las de otras aplicaciones y del sistema y las ocultas +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read No se pudo leer {n} carpeta o archivo|No se pudieron leer {n} carpetas o archivos The search stopped at its limit: search a smaller folder. La búsqueda se detuvo en su límite: busca en una carpeta más pequeña. Copy only fonts you own or are licensed to install. Copia solo fuentes que te pertenezcan o cuya licencia te permita instalarlas. VectorCraft copies the fonts to {folder}. VectorCraft copia las fuentes en {folder}. @@ -3676,13 +3678,13 @@ font-technology Variable Variables Zoom Tool Herramienta Zoom Zoom with Mouse Wheel Zoom con la rueda del mouse Scrub Numeric Fields by Dragging Ajustar campos numéricos arrastrando - {count} file(s) in {folder} {note}. Show the package folder? {count} archivo(s) en {folder}{note}. ¿Mostrar la carpeta del paquete? - {count} linked file(s) not found No se encontraron {count} archivo(s) vinculado(s) +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} archivo en {folder} {note}. ¿Mostrar la carpeta del paquete?|{n} archivos en {folder} {note}. ¿Mostrar la carpeta del paquete? +@plural {n} linked file not found|{n} linked files not found No se encontró {n} archivo vinculado|No se encontraron {n} archivos vinculados fonts not copied: {fonts} fuentes no copiadas: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? {count} imagen(es) vinculada(s) cambiaron desde que se guardó este documento. ¿Mostrar las versiones nuevas? - {count} linked image(s) changed on disk. Show the new versions? {count} imagen(es) vinculada(s) cambiaron en el disco. ¿Mostrar las versiones nuevas? - {count} more rules: Export writes every one. {count} reglas más: Exportar las escribe todas. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Se omitieron {count} objetos sin nombre: ponles nombre o activa Objetos sin nombre en el menú del panel. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} imagen vinculada cambió desde que se guardó este documento. ¿Mostrar la versión nueva?|{n} imágenes vinculadas cambiaron desde que se guardó este documento. ¿Mostrar las versiones nuevas? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} imagen vinculada cambió en el disco. ¿Mostrar la versión nueva?|{n} imágenes vinculadas cambiaron en el disco. ¿Mostrar las versiones nuevas? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regla más: Exportar la escribe.|{n} reglas más: Exportar las escribe todas. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Se omitió {n} objeto sin nombre: ponle nombre o activa Objetos sin nombre en el menú del panel.|Se omitieron {n} objetos sin nombre: ponles nombre o activa Objetos sin nombre en el menú del panel. {effect} is already applied {effect} ya está aplicado {format} Options Opciones de {format} {kind} Gradient Degradado {kind} @@ -5536,10 +5538,10 @@ axis Y Axis Eje Y @msg Packaged {n} file(s) in {folder} Se empaquetaron {n} archivo(s) en {folder} @msg Packaged {n} file(s) {note} Se empaquetaron {n} archivo(s) {note} @msg Packaged {n} file(s) Se empaquetaron {n} archivo(s) - Packaged {n} file(s) Se empaquetaron {n} archivo(s) - Packaged {n} file(s) in {folder} Se empaquetaron {n} archivo(s) en {folder} - Packaged {n} file(s) {note} Se empaquetaron {n} archivo(s) {note} - {count} file(s) in {folder}. Show the package folder? {count} archivo(s) en {folder}. ¿Mostrar la carpeta del paquete? +@plural Packaged {n} file|Packaged {n} files Se empaquetó {n} archivo|Se empaquetaron {n} archivos +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Se empaquetó {n} archivo en {folder}|Se empaquetaron {n} archivos en {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Se empaquetó {n} archivo {note}|Se empaquetaron {n} archivos {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} archivo en {folder}. ¿Mostrar la carpeta del paquete?|{n} archivos en {folder}. ¿Mostrar la carpeta del paquete? Clockwise En sentido horario Dither Tramado Fine noise hides banding in the gradient fill Un ruido fino oculta las bandas del relleno de degradado diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index ef924d1731..2d86cc5f7f 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -663,7 +663,7 @@ 1 Layer 1 taso Libraries Kirjastot Links Linkit - {count} linked image(s) changed on disk. Show the new versions? {count} linkitettyä kuvaa muuttui levyllä. Näytetäänkö uudet versiot? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} linkitetty kuva muuttui levyllä. Näytetäänkö uusi versio?|{n} linkitettyä kuvaa muuttui levyllä. Näytetäänkö uudet versiot? Update Changed Links Päivitä muuttuneet linkit @msg Updated {_1} linked file(s) changed on disk Päivitettiin {_1} levyllä muuttunutta linkitettyä tiedostoa Magic Wand Taikasauva @@ -1479,8 +1479,8 @@ lighting Light Valo Select objects to see their CSS, or Generate CSS for the whole document. Valitse objektit, niin näet niiden CSS:n, tai luo CSS koko asiakirjalle. The selected objects have no CSS of their own (see below). Valituilla objekteilla ei ole omaa CSS:ää (katso alta). Units: {units} Yksiköt: {units} - {count} more rules: Export writes every one. {count} sääntöä lisää: vienti kirjoittaa ne kaikki. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} nimetöntä objektia jätetty pois: nimeä ne tai ota Nimettömät objektit käyttöön paneelin valikosta. +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} sääntö lisää: vienti kirjoittaa sen.|{n} sääntöä lisää: vienti kirjoittaa ne kaikki. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} nimetön objekti jätetty pois: nimeä se tai ota Nimettömät objektit käyttöön paneelin valikosta.|{n} nimetöntä objektia jätetty pois: nimeä ne tai ota Nimettömät objektit käyttöön paneelin valikosta. All Categories Kaikki luokat Repeat Objects Toisto-objektit Save… Tallenna… @@ -2348,19 +2348,21 @@ lighting Light Valo Stop Pysäytä Searching… Haetaan… Not found Ei löytynyt - {folders} folder(s) and {files} file(s) searched Haettu {folders} kansio(ta) ja {files} tiedosto(a) - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} kansio(ta) ohitettu, kuten muiden sovellusten ja järjestelmän kansiot sekä piilotetut kansiot - {count} folder(s) or file(s) couldn't be read {count} kansiota tai tiedostoa ei voitu lukea + {folders} and {files} searched Haettu {folders} ja {files} +@plural {n} folder|{n} folders {n} kansio|{n} kansiota +@plural {n} file|{n} files {n} tiedosto|{n} tiedostoa +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} kansio ohitettu, kuten muiden sovellusten ja järjestelmän kansiot sekä piilotetut kansiot|{n} kansiota ohitettu, kuten muiden sovellusten ja järjestelmän kansiot sekä piilotetut kansiot +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} kansiota tai tiedostoa ei voitu lukea|{n} kansiota tai tiedostoa ei voitu lukea The search stopped at its limit: search a smaller folder. Haku pysähtyi rajaansa: hae pienemmästä kansiosta. Copy only fonts you own or are licensed to install. Kopioi vain fontteja, jotka omistat tai joiden asentamiseen sinulla on lisenssi. VectorCraft copies the fonts to {folder}. VectorCraft kopioi fontit kansioon {folder}. - Apply to All ({count} more missing) Käytä kaikkiin ({count} muuta puuttuu) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Käytä kaikkiin ({n} muu puuttuu)|Käytä kaikkiin ({n} muuta puuttuu) Ignore Ohita Linked File Not Found Linkitettyä tiedostoa ei löydy Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Korvaa se toisella tiedostolla tai ohita se: sen kuvissa näkyy asiakirjaan tallennettu esikatselu. Replace… Korvaa… Update Modified Links Päivitä muokatut linkit - {count} linked image(s) changed since this document was saved. Show the new versions? {count} linkitettyä kuvaa on muuttunut asiakirjan tallentamisen jälkeen. Näytetäänkö uudet versiot? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} linkitetty kuva on muuttunut asiakirjan tallentamisen jälkeen. Näytetäänkö uusi versio?|{n} linkitettyä kuvaa on muuttunut asiakirjan tallentamisen jälkeen. Näytetäänkö uudet versiot? Dialog Valintaikkuna Convert Process to Global Muunna prosessivärit globaaleiksi Create From: Luo kohteesta: @@ -2399,12 +2401,12 @@ lighting Light Valo Fonts whose licence doesn't allow embedding are not copied. Fontteja, joiden lisenssi ei salli upottamista, ei kopioida. Package collects a saved document with its linked files and fonts. Paketointi kokoaa tallennetun asiakirjan sekä sen linkitetyt tiedostot ja fontit. Package created Paketti luotu - Packaged {n} file(s) in {folder} {note} Paketoitiin {n} tiedosto(a) kansioon {folder} {note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Paketoitiin {n} tiedosto kansioon {folder} {note}|Paketoitiin {n} tiedostoa kansioon {folder} {note} Packaged {n} file(s){note} Paketoitu {n} tiedosto(a){note} Relink Linked Files to the Document Linkitä linkitetyt tiedostot uudelleen asiakirjaan Save the document first? Tallennetaanko asiakirja ensin? - {count} file(s) in {folder} {note}. Show the package folder? {count} tiedosto(a) kansiossa {folder} {note}. Näytetäänkö pakettikansio? - {count} linked file(s) not found {count} linkitettyä tiedostoa ei löytynyt +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} tiedosto kansiossa {folder} {note}. Näytetäänkö pakettikansio?|{n} tiedostoa kansiossa {folder} {note}. Näytetäänkö pakettikansio? +@plural {n} linked file not found|{n} linked files not found {n} linkitettyä tiedostoa ei löytynyt|{n} linkitettyä tiedostoa ei löytynyt fonts not copied: {fonts} fontteja ei kopioitu: {fonts} Built-in presets are read-only: New… starts an editable copy. Sisäiset esiasetukset ovat vain luku -tilassa: Uusi… luo muokattavan kopion. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} piirtoalustalla vastaa {real} {unit} näkymässä. @@ -5625,10 +5627,10 @@ axis Y Axis Y-akseli @msg Packaged {n} file(s) in {folder} Paketoitiin {n} tiedosto(a) kansioon {folder} @msg Packaged {n} file(s) {note} Paketoitiin {n} tiedosto(a) {note} @msg Packaged {n} file(s) Paketoitiin {n} tiedosto(a) - Packaged {n} file(s) Paketoitiin {n} tiedosto(a) - Packaged {n} file(s) in {folder} Paketoitiin {n} tiedosto(a) kansioon {folder} - Packaged {n} file(s) {note} Paketoitiin {n} tiedosto(a) {note} - {count} file(s) in {folder}. Show the package folder? {count} tiedosto(a) kansiossa {folder}. Näytetäänkö pakettikansio? +@plural Packaged {n} file|Packaged {n} files Paketoitiin {n} tiedosto|Paketoitiin {n} tiedostoa +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Paketoitiin {n} tiedosto kansioon {folder}|Paketoitiin {n} tiedostoa kansioon {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Paketoitiin {n} tiedosto {note}|Paketoitiin {n} tiedostoa {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} tiedosto kansiossa {folder}. Näytetäänkö pakettikansio?|{n} tiedostoa kansiossa {folder}. Näytetäänkö pakettikansio? Clockwise Myötäpäivään Dither Rasterointi Fine noise hides banding in the gradient fill Hieno kohina piilottaa raidat liukuväritäytöstä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 7d5fe46b1e..29cb4e6d1c 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -218,7 +218,7 @@ font-technology Variable Variables Apply Paragraph Style Appliquer le style de paragraphe Apply SVG Filter… Appliquer un filtre SVG… Apply to All Appliquer à tous - Apply to All ({count} more missing) Appliquer à tous ({count} autres manquants) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Appliquer à tous ({n} autre manquant)|Appliquer à tous ({n} autres manquants) Arc Arc Arc Lower… Arc inférieur… Arc Tool Outil Arc @@ -2270,7 +2270,7 @@ font-technology Variable Variables Package Assembler Package collects a saved document with its linked files and fonts. Assembler rassemble un document enregistré avec ses fichiers liés et ses polices. Package created Assemblage créé - Packaged {n} file(s) in {folder} {note} {n} fichier(s) assemblé(s) dans {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} fichier assemblé dans {folder} {note}|{n} fichiers assemblés dans {folder} {note} Packaged {n} file(s){note} {n} fichier(s) assemblé(s){note} Package… Assembler… Page Page @@ -2590,9 +2590,11 @@ font-technology Variable Variables Stop Arrêter Searching… Recherche… Not found Introuvable - {folders} folder(s) and {files} file(s) searched {folders} dossier(s) et {files} fichier(s) parcourus - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} dossier(s) ignoré(s), comme ceux d’autres apps et du système et les dossiers masqués - {count} folder(s) or file(s) couldn't be read {count} dossier(s) ou fichier(s) illisible(s) + {folders} and {files} searched {folders} et {files} parcourus +@plural {n} folder|{n} folders {n} dossier|{n} dossiers +@plural {n} file|{n} files {n} fichier|{n} fichiers +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} dossier ignoré, comme ceux d’autres apps et du système et les dossiers masqués|{n} dossiers ignorés, comme ceux d’autres apps et du système et les dossiers masqués +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} dossier ou fichier illisible|{n} dossiers ou fichiers illisibles The search stopped at its limit: search a smaller folder. La recherche s’est arrêtée à sa limite : recherchez dans un dossier plus petit. Copy only fonts you own or are licensed to install. Ne copiez que des polices qui vous appartiennent ou dont la licence vous autorise l’installation. VectorCraft copies the fonts to {folder}. VectorCraft copie les polices dans {folder}. @@ -3674,13 +3676,13 @@ font-technology Variable Variables Zoom Tool Outil Zoom Zoom with Mouse Wheel Zoom avec la molette de la souris Scrub Numeric Fields by Dragging Modifier les champs numériques en faisant glisser - {count} file(s) in {folder} {note}. Show the package folder? {count} fichier(s) dans {folder}{note}. Afficher le dossier de l’assemblage ? - {count} linked file(s) not found {count} fichier(s) lié(s) introuvable(s) +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fichier dans {folder} {note}. Afficher le dossier de l’assemblage ?|{n} fichiers dans {folder} {note}. Afficher le dossier de l’assemblage ? +@plural {n} linked file not found|{n} linked files not found {n} fichier lié introuvable|{n} fichiers liés introuvables fonts not copied: {fonts} polices non copiées : {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? {count} image(s) liée(s) modifiée(s) depuis l’enregistrement de ce document. Afficher les nouvelles versions ? - {count} linked image(s) changed on disk. Show the new versions? {count} image(s) liée(s) modifiée(s) sur le disque. Afficher les nouvelles versions ? - {count} more rules: Export writes every one. {count} règles de plus : Exporter les écrit toutes. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} objets sans nom omis : nommez-les ou activez Objets sans nom dans le menu du panneau. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} image liée modifiée depuis l’enregistrement de ce document. Afficher la nouvelle version ?|{n} images liées modifiées depuis l’enregistrement de ce document. Afficher les nouvelles versions ? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} image liée modifiée sur le disque. Afficher la nouvelle version ?|{n} images liées modifiées sur le disque. Afficher les nouvelles versions ? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} règle de plus : Exporter l’écrit.|{n} règles de plus : Exporter les écrit toutes. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} objet sans nom omis : nommez-le ou activez Objets sans nom dans le menu du panneau.|{n} objets sans nom omis : nommez-les ou activez Objets sans nom dans le menu du panneau. {effect} is already applied {effect} est déjà appliqué {format} Options Options {format} {kind} Gradient Dégradé {kind} @@ -5592,10 +5594,10 @@ axis Y Axis Axe Y @msg Packaged {n} file(s) in {folder} {n} fichier(s) assemblé(s) dans {folder} @msg Packaged {n} file(s) {note} {n} fichier(s) assemblé(s) {note} @msg Packaged {n} file(s) {n} fichier(s) assemblé(s) - Packaged {n} file(s) {n} fichier(s) assemblé(s) - Packaged {n} file(s) in {folder} {n} fichier(s) assemblé(s) dans {folder} - Packaged {n} file(s) {note} {n} fichier(s) assemblé(s) {note} - {count} file(s) in {folder}. Show the package folder? {count} fichier(s) dans {folder}. Afficher le dossier de l’assemblage ? +@plural Packaged {n} file|Packaged {n} files {n} fichier assemblé|{n} fichiers assemblés +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} fichier assemblé dans {folder}|{n} fichiers assemblés dans {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} {n} fichier assemblé {note}|{n} fichiers assemblés {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} fichier dans {folder}. Afficher le dossier de l’assemblage ?|{n} fichiers dans {folder}. Afficher le dossier de l’assemblage ? Clockwise Sens horaire Dither Simulation Fine noise hides banding in the gradient fill Un bruit fin masque les bandes du fond en dégradé diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0d71cbb8ae..74a25582c0 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -300,7 +300,7 @@ font-technology Variable Változó Apply Paragraph Style Bekezdésstílus alkalmazása Apply SVG Filter… SVG-szűrő alkalmazása… Apply to All Alkalmazás az összesre - Apply to All ({count} more missing) Alkalmazás mindegyikre (további hiányzók: {count}) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Alkalmazás mindegyikre (további hiányzók: {n}) Approximate path Útvonal közelítése Arabic Arab Arc Ív @@ -2754,7 +2754,7 @@ file-filter Templates Sablonok Package Csomagolás Package collects a saved document with its linked files and fonts. A csomagolás egy mentett dokumentumot a csatolt fájljaival és betűtípusaival együtt gyűjt össze. Package created A csomag elkészült - Packaged {n} file(s) in {folder} {note} Becsomagolt fájlok: {n}, mappa: {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Becsomagolt fájlok: {n}, mappa: {folder} {note} Packaged {n} file(s){note} Becsomagolt fájlok: {n}{note} Package… Csomagolás… Page Oldal @@ -4406,16 +4406,18 @@ mark-style Japanese Japán Zoom to Selection Nagyítás a kijelölésre Zoom Tool Nagyító Zoom with Mouse Wheel Nagyítás egérgörgővel - {count} file(s) in {folder} {note}. Show the package folder? Fájlok: {count}, mappa: {folder}{note}. Megnyitod a csomag mappáját? - {count} folder(s) or file(s) couldn't be read Nem olvasható mappák vagy fájlok: {count} - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Kihagyott mappák: {count} (például más alkalmazások, a rendszer és a rejtett mappák) - {count} linked file(s) not found Nem található csatolt fájlok: {count} - {count} linked image(s) changed on disk. Show the new versions? A lemezen módosult csatolt képek: {count}. Megjelenítsük az új változatokat? - {count} linked image(s) changed since this document was saved. Show the new versions? A dokumentum mentése óta módosult csatolt képek: {count}. Megjelenítsük az új változatokat? - {count} more rules: Export writes every one. További szabályok: {count}. Az exportálás mindet kiírja. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Kimaradt névtelen objektumok: {count}. Nevezd el őket, vagy kapcsold be a panelmenüben a Névtelen objektumok elemet. +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? Fájlok: {n}, mappa: {folder} {note}. Megnyitod a csomag mappáját? +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Nem olvasható mappák vagy fájlok: {n} +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Kihagyott mappák: {n} (például más alkalmazások, a rendszer és a rejtett mappák) +@plural {n} linked file not found|{n} linked files not found Nem található csatolt fájlok: {n} +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? A lemezen módosult csatolt képek: {n}. Megjelenítsük az új változatokat? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? A dokumentum mentése óta módosult csatolt képek: {n}. Megjelenítsük az új változatokat? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. További szabályok: {n}. Az exportálás mindet kiírja. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Kimaradt névtelen objektumok: {n}. Nevezd el őket, vagy kapcsold be a panelmenüben a Névtelen objektumok elemet. {effect} is already applied Már alkalmazva: {effect} - {folders} folder(s) and {files} file(s) searched Átkeresett mappák: {folders}, fájlok: {files} + {folders} and {files} searched Átkeresve: {folders} és {files} +@plural {n} folder|{n} folders {n} mappa +@plural {n} file|{n} files {n} fájl {format} Options Formátumbeállítások: {format} {kind} Gradient Színátmenet: {kind} gradient-kind Radial Körkörös @@ -5580,10 +5582,10 @@ axis Y Axis Y tengely @msg Packaged {n} file(s) in {folder} Becsomagolt fájlok: {n}, mappa: {folder} @msg Packaged {n} file(s) {note} Becsomagolt fájlok: {n} {note} @msg Packaged {n} file(s) Becsomagolt fájlok: {n} - Packaged {n} file(s) Becsomagolt fájlok: {n} - Packaged {n} file(s) in {folder} Becsomagolt fájlok: {n}, mappa: {folder} - Packaged {n} file(s) {note} Becsomagolt fájlok: {n} {note} - {count} file(s) in {folder}. Show the package folder? Fájlok: {count}, mappa: {folder}. Megnyitod a csomag mappáját? +@plural Packaged {n} file|Packaged {n} files Becsomagolt fájlok: {n} +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Becsomagolt fájlok: {n}, mappa: {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Becsomagolt fájlok: {n} {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? Fájlok: {n}, mappa: {folder}. Megnyitod a csomag mappáját? Clockwise Óramutató járásával megegyező Dither Árnyalatkeverés Fine noise hides banding in the gradient fill A finom zaj elrejti a sávokat a színátmenetes kitöltésben diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index bfa0660240..f8bee41744 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -624,7 +624,7 @@ 1 Layer 1 lapisan Libraries Pustaka Links Tautan - {count} linked image(s) changed on disk. Show the new versions? {count} gambar tertaut di disk telah berubah. Tampilkan versi baru? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} gambar tertaut di disk telah berubah. Tampilkan versi baru? Update Changed Links Perbarui tautan yang berubah @msg Updated {_1} linked file(s) changed on disk Telah memperbarui {_1} berkas tertaut yang berubah di disk Magic Wand Tongkat ajaib @@ -1419,8 +1419,8 @@ lighting Light Cahaya Select objects to see their CSS, or Generate CSS for the whole document. Pilih objek untuk melihat CSS-nya, atau buat CSS untuk seluruh dokumen. The selected objects have no CSS of their own (see below). Objek terpilih tidak memiliki CSS tersendiri (lihat di bawah). Units: {units} Unit: {units} - {count} more rules: Export writes every one. {count} aturan lagi: Ekspor menuliskan semuanya. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} objek tanpa nama tidak disertakan: beri nama, atau aktifkan Objek Tanpa Nama di menu panel. +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} aturan lagi: Ekspor menuliskan semuanya. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} objek tanpa nama tidak disertakan: beri nama, atau aktifkan Objek Tanpa Nama di menu panel. All Categories Semua kategori Repeat Objects Objek pengulangan Save… Simpan… @@ -2196,19 +2196,21 @@ lighting Light Cahaya Stop Hentikan Searching… Mencari… Not found Tidak ditemukan - {folders} folder(s) and {files} file(s) searched {folders} folder dan {files} file telah dicari - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} folder dilewati, seperti folder aplikasi lain, folder sistem, dan folder tersembunyi - {count} folder(s) or file(s) couldn't be read {count} folder atau file tidak dapat dibaca + {folders} and {files} searched {folders} dan {files} telah dicari +@plural {n} folder|{n} folders {n} folder +@plural {n} file|{n} files {n} file +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} folder dilewati, seperti folder aplikasi lain, folder sistem, dan folder tersembunyi +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} folder atau file tidak dapat dibaca The search stopped at its limit: search a smaller folder. Pencarian berhenti pada batasnya: cari folder yang lebih kecil. Copy only fonts you own or are licensed to install. Salin hanya font yang Anda miliki atau yang dilisensikan untuk dipasang. VectorCraft copies the fonts to {folder}. VectorCraft menyalin font ke {folder}. - Apply to All ({count} more missing) Terapkan ke semua ({count} lagi hilang) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Terapkan ke semua ({n} lagi hilang) Ignore Abaikan Linked File Not Found File tertaut tidak ditemukan Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Ganti dengan file lain, atau abaikan: gambarnya tetap menampilkan pratinjau yang tersimpan bersama dokumen. Replace… Ganti… Update Modified Links Perbarui tautan yang diubah - {count} linked image(s) changed since this document was saved. Show the new versions? {count} gambar tertaut berubah sejak dokumen ini disimpan. Tampilkan versi barunya? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} gambar tertaut berubah sejak dokumen ini disimpan. Tampilkan versi barunya? Dialog Dialog Convert Process to Global Konversi proses ke global Create From: Buat dari: @@ -2247,12 +2249,12 @@ lighting Light Cahaya Fonts whose licence doesn't allow embedding are not copied. Font yang lisensinya tidak mengizinkan penyematan tidak disalin. Package collects a saved document with its linked files and fonts. Package mengumpulkan dokumen tersimpan beserta file dan font yang tertaut. Package created Paket dibuat - Packaged {n} file(s) in {folder} {note} {n} file dipaketkan dalam {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} file dipaketkan dalam {folder} {note} Packaged {n} file(s){note} {n} file dipaketkan{note} Relink Linked Files to the Document Tautkan ulang file tertaut ke dokumen Save the document first? Simpan dokumen terlebih dahulu? - {count} file(s) in {folder} {note}. Show the package folder? {count} file dalam {folder}{note}. Tampilkan folder paket? - {count} linked file(s) not found {count} file tertaut tidak ditemukan +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} file dalam {folder} {note}. Tampilkan folder paket? +@plural {n} linked file not found|{n} linked files not found {n} file tertaut tidak ditemukan fonts not copied: {fonts} font tidak disalin: {fonts} Built-in presets are read-only: New… starts an editable copy. Preset bawaan bersifat hanya-baca: Baru… memulai salinan yang dapat diedit. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} pada artboard mewakili {real} {unit} dalam scene. @@ -5520,10 +5522,10 @@ axis Y Axis Sumbu Y @msg Packaged {n} file(s) in {folder} Berhasil mengemas {n} file di {folder} @msg Packaged {n} file(s) {note} Berhasil mengemas {n} file {note} @msg Packaged {n} file(s) Berhasil mengemas {n} file - Packaged {n} file(s) Berhasil mengemas {n} file - Packaged {n} file(s) in {folder} Berhasil mengemas {n} file di {folder} - Packaged {n} file(s) {note} Berhasil mengemas {n} file {note} - {count} file(s) in {folder}. Show the package folder? {count} file dalam {folder}. Tampilkan folder paket? +@plural Packaged {n} file|Packaged {n} files Berhasil mengemas {n} file +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Berhasil mengemas {n} file di {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Berhasil mengemas {n} file {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} file dalam {folder}. Tampilkan folder paket? Clockwise Searah jarum jam Dither Dither Fine noise hides banding in the gradient fill Derau halus menyembunyikan pita warna pada isian gradien diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 2c587de487..5fd0ed4b79 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -217,7 +217,7 @@ font-technology Variable Variabili Apply Paragraph Style Applica stile paragrafo Apply SVG Filter… Applica filtro SVG… Apply to All Applica a tutti - Apply to All ({count} more missing) Applica a tutti (ne mancano altri {count}) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Applica a tutti (ne manca ancora {n})|Applica a tutti (ne mancano altri {n}) Arc Arco Arc Lower… Arco inferiore… Arc Tool Strumento Arco @@ -2299,7 +2299,7 @@ file-filter Templates Modelli Package Crea pacchetto Package collects a saved document with its linked files and fonts. Il comando Crea pacchetto raccoglie un documento salvato insieme ai file collegati e ai font. Package created Pacchetto creato - Packaged {n} file(s) in {folder} {note} Pacchetto creato con {n} file in {folder} {note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Pacchetto creato con {n} file in {folder} {note}|Pacchetto creato con {n} file in {folder} {note} Packaged {n} file(s){note} Pacchetto creato con {n} file{note} Package… Crea pacchetto… Page Pagina @@ -2623,9 +2623,11 @@ mark-style Japanese Giapponese Stop Interrompi Searching… Ricerca in corso… Not found Non trovato - {folders} folder(s) and {files} file(s) searched Cartelle cercate: {folders}, file: {files} - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Cartelle saltate: {count}, ad esempio quelle di altre app e di sistema e quelle nascoste - {count} folder(s) or file(s) couldn't be read Cartelle o file non leggibili: {count} + {folders} and {files} searched Cercato in {folders} e {files} +@plural {n} folder|{n} folders {n} cartella|{n} cartelle +@plural {n} file|{n} files {n} file|{n} file +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Cartelle saltate: {n}, ad esempio quelle di altre app e di sistema e quelle nascoste|Cartelle saltate: {n}, ad esempio quelle di altre app e di sistema e quelle nascoste +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Cartelle o file non leggibili: {n}|Cartelle o file non leggibili: {n} The search stopped at its limit: search a smaller folder. La ricerca si è fermata al suo limite: cerca in una cartella più piccola. Copy only fonts you own or are licensed to install. Copia solo font di tua proprietà o con una licenza che ti consente di installarli. VectorCraft copies the fonts to {folder}. VectorCraft copia i font in {folder}. @@ -3711,13 +3713,13 @@ mark-style Japanese Giapponese Zoom Tool Strumento Zoom Zoom with Mouse Wheel Zoom con la rotellina del mouse Scrub Numeric Fields by Dragging Regola i campi numerici trascinando - {count} file(s) in {folder} {note}. Show the package folder? {count} file in {folder} {note}. Vuoi mostrare la cartella del pacchetto? - {count} linked file(s) not found File collegati non trovati: {count} +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} file in {folder} {note}. Vuoi mostrare la cartella del pacchetto?|{n} file in {folder} {note}. Vuoi mostrare la cartella del pacchetto? +@plural {n} linked file not found|{n} linked files not found File collegati non trovati: {n}|File collegati non trovati: {n} fonts not copied: {fonts} font non copiati: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? Immagini collegate modificate dopo il salvataggio di questo documento: {count}. Vuoi mostrare le nuove versioni? - {count} linked image(s) changed on disk. Show the new versions? Immagini collegate modificate su disco: {count}. Vuoi mostrare le nuove versioni? - {count} more rules: Export writes every one. Altre {count} regole: Esporta le scrive tutte. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} oggetti senza nome esclusi: assegna loro un nome o attiva Oggetti senza nome nel menu del pannello. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? Immagini collegate modificate dopo il salvataggio di questo documento: {n}. Vuoi mostrare le nuove versioni?|Immagini collegate modificate dopo il salvataggio di questo documento: {n}. Vuoi mostrare le nuove versioni? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? Immagini collegate modificate su disco: {n}. Vuoi mostrare le nuove versioni?|Immagini collegate modificate su disco: {n}. Vuoi mostrare le nuove versioni? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regola in più: Esporta la scrive.|Altre {n} regole: Esporta le scrive tutte. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} oggetto senza nome escluso: assegnagli un nome o attiva Oggetti senza nome nel menu del pannello.|{n} oggetti senza nome esclusi: assegna loro un nome o attiva Oggetti senza nome nel menu del pannello. {effect} is already applied L'effetto {effect} è già applicato {format} Options Opzioni {format} {kind} Gradient Sfumatura {kind} @@ -5209,10 +5211,10 @@ axis Y Axis Asse Y @msg Packaged {n} file(s) in {folder} Pacchetto creato con {n} file in {folder} @msg Packaged {n} file(s) {note} Pacchetto creato con {n} file {note} @msg Packaged {n} file(s) Pacchetto creato con {n} file - Packaged {n} file(s) Pacchetto creato con {n} file - Packaged {n} file(s) in {folder} Pacchetto creato con {n} file in {folder} - Packaged {n} file(s) {note} Pacchetto creato con {n} file {note} - {count} file(s) in {folder}. Show the package folder? {count} file in {folder}. Vuoi mostrare la cartella del pacchetto? +@plural Packaged {n} file|Packaged {n} files Pacchetto creato con {n} file|Pacchetto creato con {n} file +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Pacchetto creato con {n} file in {folder}|Pacchetto creato con {n} file in {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Pacchetto creato con {n} file {note}|Pacchetto creato con {n} file {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} file in {folder}. Vuoi mostrare la cartella del pacchetto?|{n} file in {folder}. Vuoi mostrare la cartella del pacchetto? Clockwise In senso orario Dither Dithering Fine noise hides banding in the gradient fill Un rumore fine nasconde le bande nel riempimento sfumato diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 0326a5c841..57715d1363 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -954,7 +954,7 @@ font-technology Variable バリアブル Apply Last Gradient 最後のグラデーションを適用 Apply Paragraph Style 段落スタイルを適用 Apply to All すべてに適用 - Apply to All ({count} more missing) すべてに適用 (ほかに {count} 個が見つかりません) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) すべてに適用 (ほかに {n} 個が見つかりません) Arc 円弧 Arc Tool 円弧ツール Area / Path Type エリア内文字/パス上文字 @@ -2618,9 +2618,11 @@ mark-style Japanese 日本式 Stop 停止 Searching… 検索中… Not found 見つかりません - {folders} folder(s) and {files} file(s) searched {folders} 個のフォルダーと {files} 個のファイルを検索しました - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} 個のフォルダーをスキップしました(他のアプリやシステムのフォルダー、隠しフォルダーなど) - {count} folder(s) or file(s) couldn't be read {count} 個のフォルダーまたはファイルを読み込めませんでした + {folders} and {files} searched {folders} と {files} を検索しました +@plural {n} folder|{n} folders {n} 個のフォルダー +@plural {n} file|{n} files {n} 個のファイル +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} 個のフォルダーをスキップしました(他のアプリやシステムのフォルダー、隠しフォルダーなど) +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} 個のフォルダーまたはファイルを読み込めませんでした The search stopped at its limit: search a smaller folder. 検索は上限で停止しました。より小さなフォルダーを検索してください。 Copy only fonts you own or are licensed to install. 所有しているフォント、またはインストールするライセンスがあるフォントだけをコピーしてください。 VectorCraft copies the fonts to {folder}. VectorCraft はフォントを {folder} にコピーします。 @@ -3305,13 +3307,13 @@ mark-style Japanese 日本式 the preset プリセット tile {number} タイル {number} to → - {count} file(s) in {folder} {note}. Show the package folder? {folder} に {count} 個のファイル{note}。パッケージフォルダーを表示しますか? - {count} linked file(s) not found リンクファイルが {count} 個見つかりません +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder} に {n} 個のファイル{note}。パッケージフォルダーを表示しますか? +@plural {n} linked file not found|{n} linked files not found リンクファイルが {n} 個見つかりません fonts not copied: {fonts} コピーされなかったフォント:{fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? 保存後に {count} 個のリンク画像が変更されています。新しいバージョンを表示しますか? - {count} linked image(s) changed on disk. Show the new versions? {count} 個のリンク画像がディスク上で変更されました。新しいバージョンを表示しますか? - {count} more rules: Export writes every one. ほかに {count} 個のルールがあります。書き出しにはすべて含まれます。 - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 名前のないオブジェクト {count} 個を除外しました。名前を付けるか、パネルメニューで「名前のないオブジェクト」をオンにしてください。 +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? 保存後に {n} 個のリンク画像が変更されています。新しいバージョンを表示しますか? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} 個のリンク画像がディスク上で変更されました。新しいバージョンを表示しますか? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. ほかに {n} 個のルールがあります。書き出しにはすべて含まれます。 +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 名前のないオブジェクト {n} 個を除外しました。名前を付けるか、パネルメニューで「名前のないオブジェクト」をオンにしてください。 {effect} is already applied {effect} はすでに適用されています {format} Options {format} オプション {kind} Gradient {kind}グラデーション @@ -3583,7 +3585,7 @@ file-filter Templates テンプレート Output Black 出力ブラック Output White 出力ホワイト Output › Mode 出力 › モード - Packaged {n} file(s) in {folder} {note} {folder} に {n} 個のファイルをパッケージしました{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {folder} に {n} 個のファイルをパッケージしました{note} Packaged {n} file(s){note} {n} 個のファイルをパッケージしました{note} Page information ページ情報 Paragraph Style 段落スタイル @@ -5275,10 +5277,10 @@ axis Y Axis Y 軸 @msg Packaged {n} file(s) in {folder} {n} 個のファイルを {folder} にパッケージしました @msg Packaged {n} file(s) {note} {n} 個のファイルをパッケージしました {note} @msg Packaged {n} file(s) {n} 個のファイルをパッケージしました - Packaged {n} file(s) {n} 個のファイルをパッケージしました - Packaged {n} file(s) in {folder} {n} 個のファイルを {folder} にパッケージしました - Packaged {n} file(s) {note} {n} 個のファイルをパッケージしました {note} - {count} file(s) in {folder}. Show the package folder? {folder} に {count} 個のファイル。パッケージフォルダーを表示しますか? +@plural Packaged {n} file|Packaged {n} files {n} 個のファイルをパッケージしました +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} 個のファイルを {folder} にパッケージしました +@plural Packaged {n} file {note}|Packaged {n} files {note} {n} 個のファイルをパッケージしました {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {folder} に {n} 個のファイル。パッケージフォルダーを表示しますか? Clockwise 時計回り Dither ディザ Fine noise hides banding in the gradient fill 細かいノイズでグラデーションの塗りの縞を目立たなくします diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b34d095505..423d50a0af 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -566,7 +566,7 @@ Layers შრეები Libraries ბიბლიოთეკა Links ბმულები - {count} linked image(s) changed on disk. Show the new versions? დისკზე შეიცვალა დაკავშირებული გამოსახულებები ({count}). ვაჩვენო ახალი ვერსიები? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? დისკზე შეიცვალა დაკავშირებული გამოსახულებები ({n}). ვაჩვენო ახალი ვერსიები? Update Changed Links შეცვლილი ბმულების განახლება @msg Updated {_1} linked file(s) changed on disk განახლდა დისკზე შეცვლილი დაკავშირებული ფაილები: {_1} Magic Wand ჯადოსნური ჯოხი @@ -1336,8 +1336,8 @@ lighting Light სინათლე Select objects to see their CSS, or Generate CSS for the whole document. მონიშნეთ ობიექტები მათი CSS-ის სანახავად, ან შექმენით CSS მთელი დოკუმენტისთვის. The selected objects have no CSS of their own (see below). მონიშნულ ობიექტებს საკუთარი CSS არ აქვს (იხ. ქვემოთ). Units: {units} ერთეულები: {units} - {count} more rules: Export writes every one. კიდევ წესები: {count}. ექსპორტი ყველას ჩაწერს. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. გამოტოვებულია უსახელო ობიექტები: {count}. დაარქვით მათ სახელი ან პანელის მენიუში ჩართეთ „უსახელო ობიექტები“. +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. კიდევ წესები: {n}. ექსპორტი ყველას ჩაწერს. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. გამოტოვებულია უსახელო ობიექტები: {n}. დაარქვით მათ სახელი ან პანელის მენიუში ჩართეთ „უსახელო ობიექტები“. All Categories ყველა კატეგორია Repeat Objects გამეორების ობიექტები Save… შენახვა… @@ -2093,19 +2093,21 @@ lighting Light სინათლე Stop შეწყვეტა Searching… ძიება… Not found ვერ მოიძებნა - {folders} folder(s) and {files} file(s) searched მოიძებნა საქაღალდეები: {folders}, ფაილები: {files} - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones გამოტოვებული საქაღალდეები: {count} — მაგ. სხვა აპლიკაციების, სისტემის და დამალული საქაღალდეები - {count} folder(s) or file(s) couldn't be read ვერ წაიკითხა საქაღალდეები ან ფაილები: {count} + {folders} and {files} searched მოიძებნა: {folders}, {files} +@plural {n} folder|{n} folders {n} საქაღალდე +@plural {n} file|{n} files {n} ფაილი +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones გამოტოვებული საქაღალდეები: {n} — მაგ. სხვა აპლიკაციების, სისტემის და დამალული საქაღალდეები +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read ვერ წაიკითხა საქაღალდეები ან ფაილები: {n} The search stopped at its limit: search a smaller folder. ძიება ზღვარზე შეჩერდა: მოძებნეთ უფრო პატარა საქაღალდეში. Copy only fonts you own or are licensed to install. დააკოპირეთ მხოლოდ ის შრიფტები, რომლებიც გეკუთვნით ან რომელთა დაყენების ლიცენზია გაქვთ. VectorCraft copies the fonts to {folder}. VectorCraft შრიფტებს აკოპირებს აქ: {folder}. - Apply to All ({count} more missing) ყველაზე გამოყენება (კიდევ დაკარგული: {count}) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) ყველაზე გამოყენება (კიდევ დაკარგული: {n}) Ignore უგულებელყოფა Linked File Not Found დაკავშირებული ფაილი ვერ მოიძებნა Replace it with another file, or ignore it: its images keep showing the preview saved with the document. ჩაანაცვლეთ სხვა ფაილით ან უგულებელყავით: მისი გამოსახულებები დოკუმენტთან შენახულ წინასწარ ხედს აჩვენებს. Replace… ჩანაცვლება… Update Modified Links შეცვლილი ბმულების განახლება - {count} linked image(s) changed since this document was saved. Show the new versions? დოკუმენტის შენახვის შემდეგ შეიცვალა დაკავშირებული გამოსახულებები: {count}. ვაჩვენოთ ახალი ვერსიები? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? დოკუმენტის შენახვის შემდეგ შეიცვალა დაკავშირებული გამოსახულებები: {n}. ვაჩვენოთ ახალი ვერსიები? Dialog დიალოგი Convert Process to Global პროცესულის გლობალურად გარდაქმნა Create From: შექმნის წყარო: @@ -2143,12 +2145,12 @@ lighting Light სინათლე Fonts whose licence doesn't allow embedding are not copied. შრიფტები, რომელთა ლიცენზია ჩაშენების უფლებას არ იძლევა, არ კოპირდება. Package collects a saved document with its linked files and fonts. შეფუთვა აგროვებს შენახულ დოკუმენტს მის დაკავშირებულ ფაილებთან და შრიფტებთან ერთად. Package created შეფუთვა შეიქმნა - Packaged {n} file(s) in {folder} {note} შეიფუთა ფაილები: {n}, ადგილი: {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} შეიფუთა ფაილები: {n}, ადგილი: {folder} {note} Packaged {n} file(s){note} შეიფუთა ფაილები: {n}{note} Relink Linked Files to the Document დაკავშირებული ფაილების დოკუმენტთან ხელახლა დაკავშირება Save the document first? ჯერ შევინახოთ დოკუმენტი? - {count} file(s) in {folder} {note}. Show the package folder? ფაილები: {count}, ადგილი: {folder}{note}. ვაჩვენოთ შეფუთვის საქაღალდე? - {count} linked file(s) not found ვერ მოიძებნა დაკავშირებული ფაილები: {count} +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? ფაილები: {n}, ადგილი: {folder} {note}. ვაჩვენოთ შეფუთვის საქაღალდე? +@plural {n} linked file not found|{n} linked files not found ვერ მოიძებნა დაკავშირებული ფაილები: {n} fonts not copied: {fonts} არ დაკოპირდა შრიფტები: {fonts} Built-in presets are read-only: New… starts an editable copy. ჩაშენებული პრესეტები მხოლოდ წასაკითხია: „ახალი…“ ქმნის რედაქტირებად ასლს. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} სამუშაო დაფაზე სცენაში {real} {unit}-ს შეესაბამება. @@ -5506,10 +5508,10 @@ axis Y Axis Y ღერძი @msg Packaged {n} file(s) in {folder} შეფუთულია ფაილი ({n}) საქაღალდეში {folder} @msg Packaged {n} file(s) {note} შეფუთულია ფაილი ({n}) {note} @msg Packaged {n} file(s) შეფუთულია ფაილი ({n}) - Packaged {n} file(s) შეფუთულია ფაილი ({n}) - Packaged {n} file(s) in {folder} შეფუთულია ფაილი ({n}) საქაღალდეში {folder} - Packaged {n} file(s) {note} შეფუთულია ფაილი ({n}) {note} - {count} file(s) in {folder}. Show the package folder? ფაილები: {count}, ადგილი: {folder}. ვაჩვენოთ შეფუთვის საქაღალდე? +@plural Packaged {n} file|Packaged {n} files შეფუთულია ფაილი ({n}) +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} შეფუთულია ფაილი ({n}) საქაღალდეში {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} შეფუთულია ფაილი ({n}) {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? ფაილები: {n}, ადგილი: {folder}. ვაჩვენოთ შეფუთვის საქაღალდე? Create PDF layers from top-level layers PDF-ის ფენების შექმნა ზედა დონის ფენებიდან @msg this kind of brush has no options dialog yet ამ ტიპის ფუნჯს პარამეტრების დიალოგი ჯერ არ აქვს Drag art, colors and text styles here to reuse them across documents. Libraries are stored on this machine — no account required. გადმოათრიეთ აქ გრაფიკა, ფერები და ტექსტის სტილები, რომ სხვა დოკუმენტებშიც გამოიყენოთ. ბიბლიოთეკები ამ კომპიუტერზე ინახება — ანგარიში არ არის საჭირო. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 5e7e7db024..9be4625826 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -945,7 +945,7 @@ font-technology Variable 가변 Apply Last Gradient 마지막 그레이디언트 적용 Apply Paragraph Style 단락 스타일 적용 Apply to All 모두에 적용 - Apply to All ({count} more missing) 모두에 적용(누락 {count}개 더 있음) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) 모두에 적용(누락 {n}개 더 있음) Arc 호 Arc Tool 호 도구 Area / Path Type 영역/패스 문자 @@ -2608,9 +2608,11 @@ mark-style Japanese 일본식 Stop 중지 Searching… 검색 중… Not found 찾을 수 없음 - {folders} folder(s) and {files} file(s) searched 폴더 {folders}개, 파일 {files}개 검색함 - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones 다른 앱과 시스템 폴더, 숨김 폴더 등 {count}개 폴더 건너뜀 - {count} folder(s) or file(s) couldn't be read 폴더 또는 파일 {count}개를 읽을 수 없음 + {folders} and {files} searched {folders}, {files} 검색함 +@plural {n} folder|{n} folders 폴더 {n}개 +@plural {n} file|{n} files 파일 {n}개 +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones 다른 앱과 시스템 폴더, 숨김 폴더 등 {n}개 폴더 건너뜀 +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read 폴더 또는 파일 {n}개를 읽을 수 없음 The search stopped at its limit: search a smaller folder. 검색이 한도에서 중단됨: 더 작은 폴더를 검색하세요. Copy only fonts you own or are licensed to install. 소유했거나 설치 라이선스가 있는 글꼴만 복사하세요. VectorCraft copies the fonts to {folder}. VectorCraft가 글꼴을 {folder}에 복사합니다. @@ -3295,13 +3297,13 @@ mark-style Japanese 일본식 the preset 프리셋 tile {number} 타일 {number} to ~ - {count} file(s) in {folder} {note}. Show the package folder? {folder}에 파일 {count}개{note}. 패키지 폴더를 표시하시겠습니까? - {count} linked file(s) not found 연결된 파일 {count}개를 찾을 수 없습니다 +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder}에 파일 {n}개 {note}. 패키지 폴더를 표시하시겠습니까? +@plural {n} linked file not found|{n} linked files not found 연결된 파일 {n}개를 찾을 수 없습니다 fonts not copied: {fonts} 복사되지 않은 글꼴: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? 이 문서를 저장한 이후 연결된 이미지 {count}개가 변경되었습니다. 새 버전을 표시하시겠습니까? - {count} linked image(s) changed on disk. Show the new versions? 연결된 이미지 {count}개가 디스크에서 변경되었습니다. 새 버전을 표시하시겠습니까? - {count} more rules: Export writes every one. 규칙 {count}개 더 있음: 내보내기 시 모두 기록됩니다. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 이름 없는 개체 {count}개가 제외되었습니다. 이름을 지정하거나 패널 메뉴에서 이름 없는 개체를 켜십시오. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? 이 문서를 저장한 이후 연결된 이미지 {n}개가 변경되었습니다. 새 버전을 표시하시겠습니까? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? 연결된 이미지 {n}개가 디스크에서 변경되었습니다. 새 버전을 표시하시겠습니까? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. 규칙 {n}개 더 있음: 내보내기 시 모두 기록됩니다. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 이름 없는 개체 {n}개가 제외되었습니다. 이름을 지정하거나 패널 메뉴에서 이름 없는 개체를 켜십시오. {effect} is already applied {effect}이(가) 이미 적용되어 있습니다 {format} Options {format} 옵션 {kind} Gradient {kind} 그레이디언트 @@ -3572,7 +3574,7 @@ file-filter Templates 템플릿 Output Black 출력 검정 Output White 출력 흰색 Output › Mode 출력 › 모드 - Packaged {n} file(s) in {folder} {note} {folder}에 파일 {n}개를 패키지했습니다{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {folder}에 파일 {n}개를 패키지했습니다 {note} Packaged {n} file(s){note} 파일 {n}개를 패키지했습니다{note} Page information 페이지 정보 Paragraph Style 단락 스타일 @@ -5172,10 +5174,10 @@ axis Y Axis Y축 @msg Packaged {n} file(s) in {folder} {folder}에 파일 {n}개를 패키지했습니다 @msg Packaged {n} file(s) {note} 파일 {n}개를 패키지했습니다 {note} @msg Packaged {n} file(s) 파일 {n}개를 패키지했습니다 - Packaged {n} file(s) 파일 {n}개를 패키지했습니다 - Packaged {n} file(s) in {folder} {folder}에 파일 {n}개를 패키지했습니다 - Packaged {n} file(s) {note} 파일 {n}개를 패키지했습니다 {note} - {count} file(s) in {folder}. Show the package folder? {folder}에 파일 {count}개. 패키지 폴더를 표시하시겠습니까? +@plural Packaged {n} file|Packaged {n} files 파일 {n}개를 패키지했습니다 +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {folder}에 파일 {n}개를 패키지했습니다 +@plural Packaged {n} file {note}|Packaged {n} files {note} 파일 {n}개를 패키지했습니다 {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {folder}에 파일 {n}개. 패키지 폴더를 표시하시겠습니까? Clockwise 시계 방향 Dither 디더 Fine noise hides banding in the gradient fill 미세한 노이즈로 그레이디언트 칠의 띠를 감춥니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 504ecae137..1a12b403ef 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -638,7 +638,7 @@ 1 Layer 1 laag Libraries Bibliotheken Links Koppelingen - {count} linked image(s) changed on disk. Show the new versions? {count} gekoppelde afbeelding(en) gewijzigd op de schijf. Nieuwe versies tonen? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} gekoppelde afbeelding gewijzigd op de schijf. Nieuwe versie tonen?|{n} gekoppelde afbeeldingen gewijzigd op de schijf. Nieuwe versies tonen? Update Changed Links Gewijzigde koppelingen bijwerken @msg Updated {_1} linked file(s) changed on disk Bijgewerkt: {_1} gekoppelde bestand(en) gewijzigd op de schijf Magic Wand Magische toverstaf @@ -1433,8 +1433,8 @@ lighting Light Licht Select objects to see their CSS, or Generate CSS for the whole document. Selecteer objecten om hun CSS te zien, of Genereer CSS voor het hele document. The selected objects have no CSS of their own (see below). De geselecteerde objecten hebben geen eigen CSS (zie hieronder). Units: {units} Eenheden: {units} - {count} more rules: Export writes every one. {count} regels meer: Export schrijft ze allemaal. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} naamloze objecten weggelaten: geef ze een naam, of zet Naamloze objecten aan in het paneelmenu. +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regel meer: Export schrijft hem.|{n} regels meer: Export schrijft ze allemaal. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} naamloos object weggelaten: geef het een naam, of zet Naamloze objecten aan in het paneelmenu.|{n} naamloze objecten weggelaten: geef ze een naam, of zet Naamloze objecten aan in het paneelmenu. All Categories Alle categorieën Repeat Objects Herhalingsobjecten Save… Opslaan… @@ -2210,19 +2210,21 @@ lighting Light Licht Stop Stoppen Searching… Zoeken… Not found Niet gevonden - {folders} folder(s) and {files} file(s) searched {folders} map(pen) en {files} bestand(en) doorzocht - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} map(pen) overgeslagen, zoals mappen van andere apps, van het systeem en verborgen mappen - {count} folder(s) or file(s) couldn't be read {count} map(pen) of bestand(en) konden niet worden gelezen + {folders} and {files} searched {folders} en {files} doorzocht +@plural {n} folder|{n} folders {n} map|{n} mappen +@plural {n} file|{n} files {n} bestand|{n} bestanden +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} map overgeslagen, zoals mappen van andere apps, van het systeem en verborgen mappen|{n} mappen overgeslagen, zoals mappen van andere apps, van het systeem en verborgen mappen +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} map of bestand kon niet worden gelezen|{n} mappen of bestanden konden niet worden gelezen The search stopped at its limit: search a smaller folder. De zoekopdracht is gestopt bij de limiet: doorzoek een kleinere map. Copy only fonts you own or are licensed to install. Kopieer alleen lettertypen die je bezit of waarvoor je een licentie hebt om ze te installeren. VectorCraft copies the fonts to {folder}. VectorCraft kopieert de lettertypen naar {folder}. - Apply to All ({count} more missing) Op alles toepassen (er ontbreken nog {count}) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Op alles toepassen (er ontbreekt nog {n})|Op alles toepassen (er ontbreken nog {n}) Ignore Negeren Linked File Not Found Gekoppeld bestand niet gevonden Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Vervang het door een ander bestand of negeer het: de afbeeldingen blijven de voorbeeldweergave tonen die met het document is opgeslagen. Replace… Vervangen… Update Modified Links Gewijzigde koppelingen bijwerken - {count} linked image(s) changed since this document was saved. Show the new versions? {count} gekoppelde afbeelding(en) zijn gewijzigd sinds dit document is opgeslagen. De nieuwe versies weergeven? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} gekoppelde afbeelding is gewijzigd sinds dit document is opgeslagen. De nieuwe versie weergeven?|{n} gekoppelde afbeeldingen zijn gewijzigd sinds dit document is opgeslagen. De nieuwe versies weergeven? Dialog Dialoogvenster Convert Process to Global Proces omzetten naar globaal Create From: Maken van: @@ -2261,12 +2263,12 @@ lighting Light Licht Fonts whose licence doesn't allow embedding are not copied. Lettertypen waarvan de licentie insluiten niet toestaat, worden niet gekopieerd. Package collects a saved document with its linked files and fonts. Verpakken verzamelt een opgeslagen document met zijn gekoppelde bestanden en lettertypen. Package created Pakket gemaakt - Packaged {n} file(s) in {folder} {note} {n} bestand(en) verpakt in {folder} {note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} bestand verpakt in {folder} {note}|{n} bestanden verpakt in {folder} {note} Packaged {n} file(s){note} {n} bestand(en) verpakt{note} Relink Linked Files to the Document Gekoppelde bestanden opnieuw koppelen aan het document Save the document first? Wil je het document eerst opslaan? - {count} file(s) in {folder} {note}. Show the package folder? {count} bestand(en) in {folder} {note}. De pakketmap openen? - {count} linked file(s) not found {count} gekoppelde bestand(en) niet gevonden +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} bestand in {folder} {note}. De pakketmap openen?|{n} bestanden in {folder} {note}. De pakketmap openen? +@plural {n} linked file not found|{n} linked files not found {n} gekoppeld bestand niet gevonden|{n} gekoppelde bestanden niet gevonden fonts not copied: {fonts} niet gekopieerde lettertypen: {fonts} Built-in presets are read-only: New… starts an editable copy. Ingebouwde voorinstellingen zijn alleen-lezen: Nieuw… start een bewerkbare kopie. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} op het tekenbord staat voor {real} {unit} in de scène. @@ -5564,10 +5566,10 @@ axis Y Axis Y-as @msg Packaged {n} file(s) in {folder} {n} bestand(en) verpakt in {folder} @msg Packaged {n} file(s) {note} {n} bestand(en) verpakt {note} @msg Packaged {n} file(s) {n} bestand(en) verpakt - Packaged {n} file(s) {n} bestand(en) verpakt - Packaged {n} file(s) in {folder} {n} bestand(en) verpakt in {folder} - Packaged {n} file(s) {note} {n} bestand(en) verpakt {note} - {count} file(s) in {folder}. Show the package folder? {count} bestand(en) in {folder}. De pakketmap openen? +@plural Packaged {n} file|Packaged {n} files {n} bestand verpakt|{n} bestanden verpakt +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} bestand verpakt in {folder}|{n} bestanden verpakt in {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} {n} bestand verpakt {note}|{n} bestanden verpakt {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} bestand in {folder}. De pakketmap openen?|{n} bestanden in {folder}. De pakketmap openen? Clockwise Met de klok mee Dither Dither Fine noise hides banding in the gradient fill Fijne ruis verbergt banden in de verloopvulling diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index fffff07ae6..1113eddd45 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -620,7 +620,7 @@ Layers Warstwy Libraries Biblioteki Links Łącza - {count} linked image(s) changed on disk. Show the new versions? Połączone obrazy zmienione na dysku: {count}. Pokazać nowe wersje? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? Połączone obrazy zmienione na dysku: {n}. Pokazać nowe wersje?|Połączone obrazy zmienione na dysku: {n}. Pokazać nowe wersje?|Połączone obrazy zmienione na dysku: {n}. Pokazać nowe wersje? Update Changed Links Aktualizuj zmienione łącza @msg Updated {_1} linked file(s) changed on disk Zaktualizowano połączone pliki zmienione na dysku: {_1} Magic Wand Różdżka @@ -1419,8 +1419,8 @@ lighting Light Światło Select objects to see their CSS, or Generate CSS for the whole document. Zaznacz obiekty, aby zobaczyć ich CSS, lub wygeneruj CSS całego dokumentu. The selected objects have no CSS of their own (see below). Zaznaczone obiekty nie mają własnego CSS (patrz niżej). Units: {units} Jednostki: {units} - {count} more rules: Export writes every one. Więcej reguł: {count}. Eksport zapisze wszystkie. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Pominięto obiekty bez nazwy: {count}. Nadaj im nazwy lub włącz Obiekty bez nazwy w menu panelu. +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. Więcej reguł: {n}. Eksport zapisze wszystkie.|Więcej reguł: {n}. Eksport zapisze wszystkie.|Więcej reguł: {n}. Eksport zapisze wszystkie. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Pominięto obiekty bez nazwy: {n}. Nadaj im nazwy lub włącz Obiekty bez nazwy w menu panelu.|Pominięto obiekty bez nazwy: {n}. Nadaj im nazwy lub włącz Obiekty bez nazwy w menu panelu.|Pominięto obiekty bez nazwy: {n}. Nadaj im nazwy lub włącz Obiekty bez nazwy w menu panelu. All Categories Wszystkie kategorie Repeat Objects Obiekty powtórzenia Save… Zapisz… @@ -2319,19 +2319,21 @@ lighting Light Światło Stop Zatrzymaj Searching… Wyszukiwanie… Not found Nie znaleziono - {folders} folder(s) and {files} file(s) searched Przeszukano foldery: {folders} i pliki: {files} - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Pominięte foldery: {count} — np. foldery innych aplikacji, systemowe i ukryte - {count} folder(s) or file(s) couldn't be read Nie udało się odczytać folderów lub plików: {count} + {folders} and {files} searched Przeszukano {folders} i {files} +@plural {n} folder|{n} folders {n} folder|{n} foldery|{n} folderów +@plural {n} file|{n} files {n} plik|{n} pliki|{n} plików +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Pominięte foldery: {n} — np. foldery innych aplikacji, systemowe i ukryte|Pominięte foldery: {n} — np. foldery innych aplikacji, systemowe i ukryte|Pominięte foldery: {n} — np. foldery innych aplikacji, systemowe i ukryte +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Nie udało się odczytać folderów lub plików: {n}|Nie udało się odczytać folderów lub plików: {n}|Nie udało się odczytać folderów lub plików: {n} The search stopped at its limit: search a smaller folder. Wyszukiwanie zatrzymało się na limicie: przeszukaj mniejszy folder. Copy only fonts you own or are licensed to install. Kopiuj tylko czcionki, które posiadasz lub masz licencję na ich instalację. VectorCraft copies the fonts to {folder}. VectorCraft kopiuje czcionki do {folder}. - Apply to All ({count} more missing) Zastosuj do wszystkich (brakuje jeszcze: {count}) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Zastosuj do wszystkich (brakuje jeszcze: {n})|Zastosuj do wszystkich (brakuje jeszcze: {n})|Zastosuj do wszystkich (brakuje jeszcze: {n}) Ignore Ignoruj Linked File Not Found Nie znaleziono połączonego pliku Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Zastąp go innym plikiem lub zignoruj: jego obrazy nadal będą pokazywać podgląd zapisany w dokumencie. Replace… Zastąp… Update Modified Links Aktualizuj zmodyfikowane łącza - {count} linked image(s) changed since this document was saved. Show the new versions? Połączone obrazy zmienione od zapisania dokumentu: {count}. Pokazać nowe wersje? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? Połączone obrazy zmienione od zapisania dokumentu: {n}. Pokazać nowe wersje?|Połączone obrazy zmienione od zapisania dokumentu: {n}. Pokazać nowe wersje?|Połączone obrazy zmienione od zapisania dokumentu: {n}. Pokazać nowe wersje? Dialog Okno dialogowe Convert Process to Global Konwertuj triadowe na globalne Create From: Utwórz z: @@ -2369,12 +2371,12 @@ lighting Light Światło Fonts whose licence doesn't allow embedding are not copied. Czcionki, których licencja nie zezwala na osadzanie, nie są kopiowane. Package collects a saved document with its linked files and fonts. Pakowanie zbiera zapisany dokument wraz z połączonymi plikami i czcionkami. Package created Utworzono pakiet - Packaged {n} file(s) in {folder} {note} Spakowane pliki: {n} w {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Spakowane pliki: {n} w {folder} {note}|Spakowane pliki: {n} w {folder} {note}|Spakowane pliki: {n} w {folder} {note} Packaged {n} file(s){note} Spakowane pliki: {n}{note} Relink Linked Files to the Document Połącz ponownie połączone pliki z dokumentem Save the document first? Najpierw zapisać dokument? - {count} file(s) in {folder} {note}. Show the package folder? Pliki: {count} w {folder}{note}. Pokazać folder pakietu? - {count} linked file(s) not found Nie znaleziono połączonych plików: {count} +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? Pliki: {n} w {folder} {note}. Pokazać folder pakietu?|Pliki: {n} w {folder} {note}. Pokazać folder pakietu?|Pliki: {n} w {folder} {note}. Pokazać folder pakietu? +@plural {n} linked file not found|{n} linked files not found Nie znaleziono połączonych plików: {n}|Nie znaleziono połączonych plików: {n}|Nie znaleziono połączonych plików: {n} fonts not copied: {fonts} nieskopiowane czcionki: {fonts} Built-in presets are read-only: New… starts an editable copy. Wbudowane ustawienia są tylko do odczytu: Nowe… tworzy edytowalną kopię. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} na obszarze kompozycji odpowiada {real} {unit} w scenie. @@ -5448,10 +5450,10 @@ axis Y Axis Oś Y @msg Packaged {n} file(s) in {folder} Spakowane pliki: {n} w {folder} @msg Packaged {n} file(s) {note} Spakowane pliki: {n} {note} @msg Packaged {n} file(s) Spakowane pliki: {n} - Packaged {n} file(s) Spakowane pliki: {n} - Packaged {n} file(s) in {folder} Spakowane pliki: {n} w {folder} - Packaged {n} file(s) {note} Spakowane pliki: {n} {note} - {count} file(s) in {folder}. Show the package folder? Pliki: {count} w {folder}. Pokazać folder pakietu? +@plural Packaged {n} file|Packaged {n} files Spakowane pliki: {n}|Spakowane pliki: {n}|Spakowane pliki: {n} +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Spakowane pliki: {n} w {folder}|Spakowane pliki: {n} w {folder}|Spakowane pliki: {n} w {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Spakowane pliki: {n} {note}|Spakowane pliki: {n} {note}|Spakowane pliki: {n} {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? Pliki: {n} w {folder}. Pokazać folder pakietu?|Pliki: {n} w {folder}. Pokazać folder pakietu?|Pliki: {n} w {folder}. Pokazać folder pakietu? Clockwise Zgodnie z ruchem wskazówek zegara Dither Rozpraszanie Fine noise hides banding in the gradient fill Drobny szum ukrywa pasy w wypełnieniu gradientem diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index aab46d1911..129533e078 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -212,7 +212,7 @@ Apply Paragraph Style Aplicar Estilo de Parágrafo Apply SVG Filter… Aplicar Filtro SVG… Apply to All Aplicar a Todos - Apply to All ({count} more missing) Aplicar a Todos ({count} mais faltando) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Aplicar a Todos ({n} mais faltando)|Aplicar a Todos ({n} mais faltando) Arc Arco Arc Lower… Arco Inferior… Arc Tool Ferramenta Arco @@ -2144,9 +2144,11 @@ Stop Parar Searching… Pesquisando… Not found Não encontrado - {folders} folder(s) and {files} file(s) searched {folders} pasta(s) e {files} arquivo(s) pesquisados - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} pasta(s) ignorada(s), como as de outros aplicativos e do sistema e as ocultas - {count} folder(s) or file(s) couldn't be read {count} pasta(s) ou arquivo(s) não puderam ser lidos + {folders} and {files} searched {folders} e {files} pesquisados +@plural {n} folder|{n} folders {n} pasta|{n} pastas +@plural {n} file|{n} files {n} arquivo|{n} arquivos +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} pasta ignorada, como as de outros aplicativos e do sistema e as ocultas|{n} pastas ignoradas, como as de outros aplicativos e do sistema e as ocultas +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} pasta ou arquivo não pôde ser lido|{n} pastas ou arquivos não puderam ser lidos The search stopped at its limit: search a smaller folder. A pesquisa parou no limite: pesquise uma pasta menor. Copy only fonts you own or are licensed to install. Copie apenas fontes que sejam suas ou que você tenha licença para instalar. VectorCraft copies the fonts to {folder}. O VectorCraft copia as fontes para {folder}. @@ -2866,7 +2868,7 @@ Update Link Atualizar Link Update Links Atualizar Links Update Changed Links Atualizar Links alterados - {count} linked image(s) changed on disk. Show the new versions? {count} imagem(ns) vinculada(s) alterada(s) no disco. Mostrar as novas versões? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} imagem vinculada alterada no disco. Mostrar a nova versão?|{n} imagens vinculadas alteradas no disco. Mostrar as novas versões? @msg Updated {_1} linked file(s) changed on disk {_1} arquivo(s) vinculado(s) alterado(s) no disco atualizado(s) Update Modified Links Atualizar Links Modificados Use Use @@ -3015,12 +3017,12 @@ the preset o predefinido tile {number} bloco {number} to para - {count} file(s) in {folder} {note}. Show the package folder? {count} arquivo(s) em {folder}{note}. Mostrar a pasta do pacote? - {count} linked file(s) not found {count} arquivo(s) vinculado(s) não encontrado(s) +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} arquivo em {folder} {note}. Mostrar a pasta do pacote?|{n} arquivos em {folder} {note}. Mostrar a pasta do pacote? +@plural {n} linked file not found|{n} linked files not found {n} arquivo vinculado não encontrado|{n} arquivos vinculados não encontrados fonts not copied: {fonts} fontes não copiadas: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? {count} imagem(ns) vinculada(s) alterada(s) desde que este documento foi salvo. Mostrar as novas versões? - {count} more rules: Export writes every one. {count} regras a mais: a Exportação escreve cada uma. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} objetos sem nome deixados de fora: nomeie-os, ou ative Objetos Sem Nome no menu do painel. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} imagem vinculada alterada desde que este documento foi salvo. Mostrar a nova versão?|{n} imagens vinculadas alteradas desde que este documento foi salvo. Mostrar as novas versões? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regra a mais: a Exportação a escreve.|{n} regras a mais: a Exportação escreve cada uma. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} objeto sem nome deixado de fora: nomeie-o, ou ative Objetos Sem Nome no menu do painel.|{n} objetos sem nome deixados de fora: nomeie-os, ou ative Objetos Sem Nome no menu do painel. {effect} is already applied {effect} já está aplicado {format} Options Opções de {format} {kind} Gradient Gradiente de {kind} @@ -4588,7 +4590,7 @@ axis Both Ambos Output Black Preto de Saída Output White Branco de Saída Output › Mode Saída › Modo - Packaged {n} file(s) in {folder} {note} {n} arquivo(s) empacotado(s) em {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} arquivo empacotado em {folder} {note}|{n} arquivos empacotados em {folder} {note} Packaged {n} file(s){note} {n} arquivo(s) empacotado(s){note} Page information Informações da página Paragraph Style Estilo de Parágrafo @@ -5511,10 +5513,10 @@ axis Y Axis Eixo Y @msg Packaged {n} file(s) in {folder} {n} arquivo(s) empacotado(s) em {folder} @msg Packaged {n} file(s) {note} {n} arquivo(s) empacotado(s) {note} @msg Packaged {n} file(s) {n} arquivo(s) empacotado(s) - Packaged {n} file(s) {n} arquivo(s) empacotado(s) - Packaged {n} file(s) in {folder} {n} arquivo(s) empacotado(s) em {folder} - Packaged {n} file(s) {note} {n} arquivo(s) empacotado(s) {note} - {count} file(s) in {folder}. Show the package folder? {count} arquivo(s) em {folder}. Mostrar a pasta do pacote? +@plural Packaged {n} file|Packaged {n} files {n} arquivo empacotado|{n} arquivos empacotados +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} arquivo empacotado em {folder}|{n} arquivos empacotados em {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} {n} arquivo empacotado {note}|{n} arquivos empacotados {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} arquivo em {folder}. Mostrar a pasta do pacote?|{n} arquivos em {folder}. Mostrar a pasta do pacote? Clockwise Sentido horário Dither Dither Fine noise hides banding in the gradient fill Um ruído fino esconde as faixas do preenchimento em gradiente diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a516437a62..a735dbb079 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -215,7 +215,7 @@ font-technology Variable Вариативные Apply Paragraph Style Применить стиль абзаца Apply SVG Filter… Применить фильтр SVG… Apply to All Применить ко всем - Apply to All ({count} more missing) Применить ко всем (ещё {count} отсутствуют) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Применить ко всем (ещё {n} отсутствует)|Применить ко всем (ещё {n} отсутствуют)|Применить ко всем (ещё {n} отсутствуют) Arc Дуга Arc Lower… Дуга снизу… Arc Tool Инструмент «Дуга» @@ -2295,7 +2295,7 @@ file-filter Templates Шаблоны Package Упаковать Package collects a saved document with its linked files and fonts. Упаковка собирает сохранённый документ с его связанными файлами и шрифтами. Package created Пакет создан - Packaged {n} file(s) in {folder} {note} Упаковано файлов: {n} в {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Упаковано файлов: {n} в {folder} {note}|Упаковано файлов: {n} в {folder} {note}|Упаковано файлов: {n} в {folder} {note} Packaged {n} file(s){note} Упаковано файлов: {n}{note} Package… Упаковать… Page Страница @@ -2619,9 +2619,11 @@ mark-style Japanese Японский Stop Остановить Searching… Поиск… Not found Не найдено - {folders} folder(s) and {files} file(s) searched Просмотрено папок: {folders}, файлов: {files} - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Пропущено папок: {count}, например папки других приложений и системы и скрытые папки - {count} folder(s) or file(s) couldn't be read Не удалось прочитать папок или файлов: {count} + {folders} and {files} searched Просмотрено: {folders}, {files} +@plural {n} folder|{n} folders {n} папка|{n} папки|{n} папок +@plural {n} file|{n} files {n} файл|{n} файла|{n} файлов +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Пропущено папок: {n}, например папки других приложений и системы и скрытые папки|Пропущено папок: {n}, например папки других приложений и системы и скрытые папки|Пропущено папок: {n}, например папки других приложений и системы и скрытые папки +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Не удалось прочитать папок или файлов: {n}|Не удалось прочитать папок или файлов: {n}|Не удалось прочитать папок или файлов: {n} The search stopped at its limit: search a smaller folder. Поиск остановился на пределе: выберите папку поменьше. Copy only fonts you own or are licensed to install. Копируйте только шрифты, которые принадлежат вам или которые вы вправе устанавливать по лицензии. VectorCraft copies the fonts to {folder}. VectorCraft копирует шрифты в {folder}. @@ -3707,13 +3709,13 @@ mark-style Japanese Японский Zoom Tool Инструмент «Масштаб» Zoom with Mouse Wheel Масштабировать колесом мыши Scrub Numeric Fields by Dragging Изменять числовые поля перетаскиванием - {count} file(s) in {folder} {note}. Show the package folder? Файлов: {count} в {folder}{note}. Показать папку пакета? - {count} linked file(s) not found Не найдено связанных файлов: {count} +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? Файлов: {n} в {folder} {note}. Показать папку пакета?|Файлов: {n} в {folder} {note}. Показать папку пакета?|Файлов: {n} в {folder} {note}. Показать папку пакета? +@plural {n} linked file not found|{n} linked files not found Не найдено связанных файлов: {n}|Не найдено связанных файлов: {n}|Не найдено связанных файлов: {n} fonts not copied: {fonts} шрифты не скопированы: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? Связанных изображений ({count}) изменились с момента сохранения этого документа. Показать новые версии? - {count} linked image(s) changed on disk. Show the new versions? Связанных изображений ({count}) изменились на диске. Показать новые версии? - {count} more rules: Export writes every one. Ещё правил: {count}: экспорт записывает все. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Пропущено объектов без имени: {count}: назовите их или включите «Объекты без имени» в меню панели. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} связанное изображение изменилось с момента сохранения этого документа. Показать новую версию?|{n} связанных изображения изменились с момента сохранения этого документа. Показать новые версии?|{n} связанных изображений изменились с момента сохранения этого документа. Показать новые версии? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} связанное изображение изменилось на диске. Показать новую версию?|{n} связанных изображения изменились на диске. Показать новые версии?|{n} связанных изображений изменились на диске. Показать новые версии? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. Ещё правил: {n}: экспорт записывает все.|Ещё правил: {n}: экспорт записывает все.|Ещё правил: {n}: экспорт записывает все. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Пропущено объектов без имени: {n}: назовите их или включите «Объекты без имени» в меню панели.|Пропущено объектов без имени: {n}: назовите их или включите «Объекты без имени» в меню панели.|Пропущено объектов без имени: {n}: назовите их или включите «Объекты без имени» в меню панели. {effect} is already applied {effect} уже применён {format} Options Параметры {format} {kind} Gradient Градиент {kind} @@ -5205,10 +5207,10 @@ axis Y Axis Ось Y @msg Packaged {n} file(s) in {folder} Упаковано файлов: {n} в {folder} @msg Packaged {n} file(s) {note} Упаковано файлов: {n} {note} @msg Packaged {n} file(s) Упаковано файлов: {n} - Packaged {n} file(s) Упаковано файлов: {n} - Packaged {n} file(s) in {folder} Упаковано файлов: {n} в {folder} - Packaged {n} file(s) {note} Упаковано файлов: {n} {note} - {count} file(s) in {folder}. Show the package folder? Файлов: {count} в {folder}. Показать папку пакета? +@plural Packaged {n} file|Packaged {n} files Упаковано файлов: {n}|Упаковано файлов: {n}|Упаковано файлов: {n} +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Упаковано файлов: {n} в {folder}|Упаковано файлов: {n} в {folder}|Упаковано файлов: {n} в {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Упаковано файлов: {n} {note}|Упаковано файлов: {n} {note}|Упаковано файлов: {n} {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? Файлов: {n} в {folder}. Показать папку пакета?|Файлов: {n} в {folder}. Показать папку пакета?|Файлов: {n} в {folder}. Показать папку пакета? Clockwise По часовой стрелке Dither Дизеринг Fine noise hides banding in the gradient fill Мелкий шум скрывает полосы в градиентной заливке diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index a98780bcf2..20d412a5ec 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -205,7 +205,7 @@ font-technology Variable Variabla Apply Paragraph Style Använd styckestil Apply SVG Filter… Använd SVG-filter… Apply to All Använd på alla - Apply to All ({count} more missing) Använd på alla ({count} till saknas) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Använd på alla ({n} till saknas)|Använd på alla ({n} till saknas) Arc Båge Arc Lower… Nedre båge… Arc Tool Bågverktyg @@ -2217,7 +2217,7 @@ font-technology Variable Variabla Package Paketera Package collects a saved document with its linked files and fonts. Paketera samlar ett sparat dokument med dess länkade filer och typsnitt. Package created Paketet har skapats - Packaged {n} file(s) in {folder} {note} Paketerade {n} fil(er) i {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Paketerade {n} fil i {folder} {note}|Paketerade {n} filer i {folder} {note} Packaged {n} file(s){note} Paketerade {n} fil(er){note} Package… Paketera… Page Sida @@ -2534,9 +2534,11 @@ font-technology Variable Variabla Stop Stoppa Searching… Söker… Not found Hittades inte - {folders} folder(s) and {files} file(s) searched {folders} mapp(ar) och {files} fil(er) genomsökta - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} mapp(ar) överhoppade, t.ex. andra appars och systemets mappar samt dolda mappar - {count} folder(s) or file(s) couldn't be read {count} mapp(ar) eller fil(er) kunde inte läsas + {folders} and {files} searched {folders} och {files} genomsökta +@plural {n} folder|{n} folders {n} mapp|{n} mappar +@plural {n} file|{n} files {n} fil|{n} filer +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} mapp överhoppad, t.ex. andra appars och systemets mappar samt dolda mappar|{n} mappar överhoppade, t.ex. andra appars och systemets mappar samt dolda mappar +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} mapp eller fil kunde inte läsas|{n} mappar eller filer kunde inte läsas The search stopped at its limit: search a smaller folder. Sökningen stoppades vid sin gräns: sök i en mindre mapp. Copy only fonts you own or are licensed to install. Kopiera bara typsnitt som du äger eller har licens att installera. VectorCraft copies the fonts to {folder}. VectorCraft kopierar typsnitten till {folder}. @@ -3604,13 +3606,13 @@ font-technology Variable Variabla Zoom Tool Zoomverktyg Zoom with Mouse Wheel Zooma med mushjulet Scrub Numeric Fields by Dragging Ändra numeriska fält genom att dra - {count} file(s) in {folder} {note}. Show the package folder? {count} fil(er) i {folder}{note}. Visa paketmappen? - {count} linked file(s) not found {count} länkad(e) fil(er) hittades inte +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fil i {folder} {note}. Visa paketmappen?|{n} filer i {folder} {note}. Visa paketmappen? +@plural {n} linked file not found|{n} linked files not found {n} länkad fil hittades inte|{n} länkade filer hittades inte fonts not copied: {fonts} typsnitt som inte kopierats: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? {count} länkad(e) bild(er) har ändrats sedan dokumentet sparades. Visa de nya versionerna? - {count} linked image(s) changed on disk. Show the new versions? {count} länkad(e) bild(er) har ändrats på disken. Visa de nya versionerna? - {count} more rules: Export writes every one. {count} regler till: Exportera skriver alla. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} namnlösa objekt utelämnade: namnge dem eller aktivera Namnlösa objekt i panelmenyn. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} länkad bild har ändrats sedan dokumentet sparades. Visa den nya versionen?|{n} länkade bilder har ändrats sedan dokumentet sparades. Visa de nya versionerna? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} länkad bild har ändrats på disken. Visa den nya versionen?|{n} länkade bilder har ändrats på disken. Visa de nya versionerna? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regel till: Exportera skriver den.|{n} regler till: Exportera skriver alla. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} namnlöst objekt utelämnat: namnge det eller aktivera Namnlösa objekt i panelmenyn.|{n} namnlösa objekt utelämnade: namnge dem eller aktivera Namnlösa objekt i panelmenyn. {effect} is already applied {effect} används redan {format} Options {format}-alternativ {kind} Gradient {kind} gradient @@ -5618,10 +5620,10 @@ axis Y Axis Y-axel @msg Packaged {n} file(s) in {folder} Paketerade {n} fil(er) i {folder} @msg Packaged {n} file(s) {note} Paketerade {n} fil(er) {note} @msg Packaged {n} file(s) Paketerade {n} fil(er) - Packaged {n} file(s) Paketerade {n} fil(er) - Packaged {n} file(s) in {folder} Paketerade {n} fil(er) i {folder} - Packaged {n} file(s) {note} Paketerade {n} fil(er) {note} - {count} file(s) in {folder}. Show the package folder? {count} fil(er) i {folder}. Visa paketmappen? +@plural Packaged {n} file|Packaged {n} files Paketerade {n} fil|Paketerade {n} filer +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Paketerade {n} fil i {folder}|Paketerade {n} filer i {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Paketerade {n} fil {note}|Paketerade {n} filer {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} fil i {folder}. Visa paketmappen?|{n} filer i {folder}. Visa paketmappen? Clockwise Medurs Dither Dithering Fine noise hides banding in the gradient fill Fint brus döljer bandningen i gradientfyllningen diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 4d543f0270..ce569f47b5 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -202,7 +202,7 @@ font-technology Variable Değişken Apply Paragraph Style Paragraf Stilini Uygula Apply SVG Filter… SVG Filtresini Uygula… Apply to All Tümüne Uygula - Apply to All ({count} more missing) Tümüne Uygula ({count} daha eksik) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Tümüne Uygula ({n} daha eksik) Arc Yay Arc Lower… Ark Alt… Arc Tool Yay Aracı @@ -2095,7 +2095,7 @@ shape Open Açık Package Paket Package collects a saved document with its linked files and fonts. Paket, kayıtlı bir belgeyi bağlantılı dosyaları ve yazı tipleriyle birlikte toplar. Package created Paket oluşturuldu - Packaged {n} file(s) in {folder} {note} {folder}{note} biçiminde paketlenmiş {n} dosyası/dosyaları +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} dosya {folder} klasörüne paketlendi {note} Packaged {n} file(s){note} Paketlenmiş {n} dosyası/dosyaları{note} Package… Paket… Page Sayfa @@ -2411,9 +2411,11 @@ shape Open Açık Stop Durdur Searching… Aranıyor… Not found Bulunamadı - {folders} folder(s) and {files} file(s) searched {folders} klasör(ler)i ve {files} dosya(lar)ı arandı - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Diğer uygulamaların ve sistemin klasörleri ve gizli klasörleri gibi {count} klasörleri atlandı - {count} folder(s) or file(s) couldn't be read {count} klasör(ler)i veya dosya(lar) okunamadı + {folders} and {files} searched {folders} ve {files} arandı +@plural {n} folder|{n} folders {n} klasör +@plural {n} file|{n} files {n} dosya +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Diğer uygulamaların ve sistemin klasörleri ve gizli klasörler gibi {n} klasör atlandı +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} klasör veya dosya okunamadı The search stopped at its limit: search a smaller folder. Arama sınırda durdu: daha küçük bir klasörde arama yapın. Copy only fonts you own or are licensed to install. Yalnızca sahip olduğunuz veya yükleme lisansına sahip olduğunuz yazı tiplerini kopyalayın. VectorCraft copies the fonts to {folder}. VectorCraft yazı tiplerini {folder}'ye kopyalar. @@ -3498,13 +3500,13 @@ shape Open Açık Zoom Tool Yakınlaştırma Aracı Zoom with Mouse Wheel Fare Tekerleği ile Yakınlaştırma Scrub Numeric Fields by Dragging Sayısal Alanları Sürükleyerek Fırçalayın - {count} file(s) in {folder} {note}. Show the package folder? {folder}{note} içindeki {count} dosyası/dosyaları. Paket klasörü gösterilsin mi? - {count} linked file(s) not found {count} bağlantılı dosya(lar) bulunamadı +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder} içinde {n} dosya {note}. Paket klasörü gösterilsin mi? +@plural {n} linked file not found|{n} linked files not found {n} bağlantılı dosya bulunamadı fonts not copied: {fonts} kopyalanmayan yazı tipleri: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? {count} bağlantılı görseller bu belgenin kaydedilmesinden bu yana değiştirildi. Yeni sürümler gösterilsin mi? - {count} linked image(s) changed on disk. Show the new versions? {count} bağlantılı görseller diskte değiştirildi. Yeni sürümler gösterilsin mi? - {count} more rules: Export writes every one. {count} daha fazla kural: Dışa aktarma her birini yazar. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} adsız nesneler dışarıda bırakıldı: bunlara ad verin veya panel menüsünde Adsız Nesneler'i açın. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} bağlantılı görsel bu belgenin kaydedilmesinden bu yana değiştirildi. Yeni sürümler gösterilsin mi? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} bağlantılı görsel diskte değiştirildi. Yeni sürümler gösterilsin mi? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} kural daha: Dışa aktarma her birini yazar. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} adsız nesne dışarıda bırakıldı: bunlara ad verin veya panel menüsünde Adsız Nesneler'i açın. {effect} is already applied {effect} zaten uygulandı {format} Options {format} Seçenekleri {kind} Gradient {kind} Degrade @@ -5548,10 +5550,10 @@ axis Y Axis Y ekseni Drop Artwork Çizimi Bırak @msg {key} must be [x, y] with finite coordinates {key}, sonlu koordinatlı [x, y] olmalı @msg ids must contain 1–10000 object ids ids 1–10000 nesne kimliği içermeli - Packaged {n} file(s) Paketlenmiş {n} dosyası/dosyaları - Packaged {n} file(s) in {folder} {folder} biçiminde paketlenmiş {n} dosyası/dosyaları - Packaged {n} file(s) {note} Paketlenmiş {n} dosyası/dosyaları {note} - {count} file(s) in {folder}. Show the package folder? {folder} içindeki {count} dosyası/dosyaları. Paket klasörü gösterilsin mi? +@plural Packaged {n} file|Packaged {n} files {n} dosya paketlendi +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} dosya {folder} klasörüne paketlendi +@plural Packaged {n} file {note}|Packaged {n} files {note} {n} dosya paketlendi {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {folder} içinde {n} dosya. Paket klasörü gösterilsin mi? Clockwise Saat yönünde Dither Titreme Fine noise hides banding in the gradient fill İnce gürültü, degrade dolgudaki bantları gizler diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 6942907990..dc4d1c4775 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -211,7 +211,7 @@ font-technology Variable Варіативні Apply Paragraph Style Застосувати стиль абзацу Apply SVG Filter… Застосувати фільтр SVG… Apply to All Застосувати до всіх - Apply to All ({count} more missing) Застосувати до всіх (ще {count} відсутні) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Застосувати до всіх (ще {n} відсутній)|Застосувати до всіх (ще {n} відсутні)|Застосувати до всіх (ще {n} відсутні) Arc Дуга Arc Lower… Дуга знизу… Arc Tool Інструмент «Дуга» @@ -2291,7 +2291,7 @@ file-filter Templates Шаблони Package Упакувати Package collects a saved document with its linked files and fonts. Упаковка збирає збережений документ із його пов’язаними файлами та шрифтами. Package created Пакет створено - Packaged {n} file(s) in {folder} {note} Упаковано файли: {n} {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Упаковано файли: {n} {folder} {note}|Упаковано файли: {n} {folder} {note}|Упаковано файли: {n} {folder} {note} Packaged {n} file(s){note} Упаковано файли: {n}{note} Package… Упакувати… Page Сторінка @@ -2615,9 +2615,11 @@ mark-style Japanese Японський Stop Зупинити Searching… Пошук… Not found Не знайдено - {folders} folder(s) and {files} file(s) searched Переглянуто папок: {folders}, файлів: {files} - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Пропущено папок: {count}, зокрема папки інших програм і системи та приховані папки - {count} folder(s) or file(s) couldn't be read Не вдалося прочитати папок або файлів: {count} + {folders} and {files} searched Переглянуто: {folders}, {files} +@plural {n} folder|{n} folders {n} папка|{n} папки|{n} папок +@plural {n} file|{n} files {n} файл|{n} файли|{n} файлів +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Пропущено папок: {n}, зокрема папки інших програм і системи та приховані папки|Пропущено папок: {n}, зокрема папки інших програм і системи та приховані папки|Пропущено папок: {n}, зокрема папки інших програм і системи та приховані папки +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Не вдалося прочитати папок або файлів: {n}|Не вдалося прочитати папок або файлів: {n}|Не вдалося прочитати папок або файлів: {n} The search stopped at its limit: search a smaller folder. Пошук зупинився на межі: виберіть меншу папку. Copy only fonts you own or are licensed to install. Копіюйте лише шрифти, які належать вам або які ви маєте право встановлювати за ліцензією. VectorCraft copies the fonts to {folder}. VectorCraft копіює шрифти в {folder}. @@ -3704,13 +3706,13 @@ effect Points Точки Zoom Tool Інструмент «Масштаб» Zoom with Mouse Wheel Масштабувати колесом миші Scrub Numeric Fields by Dragging Змінювати числові поля перетягуванням - {count} file(s) in {folder} {note}. Show the package folder? файлів: {count} {folder}{note}. Показати папку пакета? - {count} linked file(s) not found не знайдено пов’язаних файлів: {count} +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? файлів: {n} {folder} {note}. Показати папку пакета?|файлів: {n} {folder} {note}. Показати папку пакета?|файлів: {n} {folder} {note}. Показати папку пакета? +@plural {n} linked file not found|{n} linked files not found не знайдено пов’язаних файлів: {n}|не знайдено пов’язаних файлів: {n}|не знайдено пов’язаних файлів: {n} fonts not copied: {fonts} шрифти не скопійовано: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? пов’язані зображення ({count}) змінилися з моменту збереження цього документа. Показати нові версії? - {count} linked image(s) changed on disk. Show the new versions? пов’язані зображення ({count}) змінилися на диску. Показати нові версії? - {count} more rules: Export writes every one. ще правил: {count}: експорт записує все. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. пропущено об’єкти без імені: {count}: назвіть їх або увімкніть «Об’єкти без імені» у меню панелі. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? пов’язані зображення ({n}) змінилися з моменту збереження цього документа. Показати нові версії?|пов’язані зображення ({n}) змінилися з моменту збереження цього документа. Показати нові версії?|пов’язані зображення ({n}) змінилися з моменту збереження цього документа. Показати нові версії? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? пов’язані зображення ({n}) змінилися на диску. Показати нові версії?|пов’язані зображення ({n}) змінилися на диску. Показати нові версії?|пов’язані зображення ({n}) змінилися на диску. Показати нові версії? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. ще правил: {n}: експорт записує все.|ще правил: {n}: експорт записує все.|ще правил: {n}: експорт записує все. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. пропущено об’єкти без імені: {n}: назвіть їх або увімкніть «Об’єкти без імені» у меню панелі.|пропущено об’єкти без імені: {n}: назвіть їх або увімкніть «Об’єкти без імені» у меню панелі.|пропущено об’єкти без імені: {n}: назвіть їх або увімкніть «Об’єкти без імені» у меню панелі. {effect} is already applied {effect} вже застосований {format} Options параметри {format} {kind} Gradient градієнт {kind} @@ -5189,10 +5191,10 @@ axis Y Axis Вісь Y @msg Packaged {n} file(s) in {folder} Упаковано файли: {n} {folder} @msg Packaged {n} file(s) {note} Упаковано файли: {n} {note} @msg Packaged {n} file(s) Упаковано файли: {n} - Packaged {n} file(s) Упаковано файли: {n} - Packaged {n} file(s) in {folder} Упаковано файли: {n} {folder} - Packaged {n} file(s) {note} Упаковано файли: {n} {note} - {count} file(s) in {folder}. Show the package folder? файлів: {count} {folder}. Показати папку пакета? +@plural Packaged {n} file|Packaged {n} files Упаковано файли: {n}|Упаковано файли: {n}|Упаковано файли: {n} +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Упаковано файли: {n} {folder}|Упаковано файли: {n} {folder}|Упаковано файли: {n} {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Упаковано файли: {n} {note}|Упаковано файли: {n} {note}|Упаковано файли: {n} {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? файлів: {n} {folder}. Показати папку пакета?|файлів: {n} {folder}. Показати папку пакета?|файлів: {n} {folder}. Показати папку пакета? Clockwise За годинниковою стрілкою Dither Дизеринг Fine noise hides banding in the gradient fill Дрібний шум приховує смуги в градієнтній заливці diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 1c3c493879..90cc10d9a5 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -235,7 +235,7 @@ font-technology Variable Biến thiên Apply Paragraph Style Áp dụng kiểu đoạn văn Apply SVG Filter… Áp dụng bộ lọc SVG… Apply to All Áp dụng cho tất cả - Apply to All ({count} more missing) Áp dụng cho tất cả ({count} còn thiếu) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Áp dụng cho tất cả ({n} còn thiếu) Approximate path Đường dẫn xấp xỉ Arabic Ả Rập Arc Cung @@ -2562,7 +2562,7 @@ file-filter Templates Mẫu Package Gói Package collects a saved document with its linked files and fonts. Gói thu thập tài liệu đã lưu cùng tệp liên kết và phông chữ. Package created Đã tạo gói - Packaged {n} file(s) in {folder} {note} Đã đóng gói {n} tệp trong {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Đã đóng gói {n} tệp trong {folder} {note} Packaged {n} file(s){note} Đã đóng gói {n} tệp{note} Package… Gói… Page Trang @@ -4067,16 +4067,18 @@ mark-style Japanese Kiểu Nhật Zoom to Selection Thu phóng đến vùng chọn Zoom Tool Công cụ thu phóng Zoom with Mouse Wheel Thu phóng bằng con lăn chuột - {count} file(s) in {folder} {note}. Show the package folder? {count} tệp trong {folder}{note}. Hiện thư mục gói? - {count} folder(s) or file(s) couldn't be read {count} thư mục hoặc tệp không thể đọc được - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Đã bỏ qua {count} thư mục, chẳng hạn thư mục của ứng dụng khác, thư mục hệ thống và thư mục ẩn - {count} linked file(s) not found Không tìm thấy {count} tệp liên kết - {count} linked image(s) changed on disk. Show the new versions? {count} ảnh liên kết đã thay đổi trên đĩa. Hiện phiên bản mới? - {count} linked image(s) changed since this document was saved. Show the new versions? {count} ảnh liên kết đã thay đổi kể từ khi lưu tài liệu. Hiện phiên bản mới? - {count} more rules: Export writes every one. Còn {count} quy tắc nữa: Xuất sẽ ghi tất cả. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} đối tượng chưa đặt tên bị bỏ qua: hãy đặt tên hoặc bật Đối tượng chưa đặt tên trong menu bảng. +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} tệp trong {folder} {note}. Hiện thư mục gói? +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} thư mục hoặc tệp không thể đọc được +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Đã bỏ qua {n} thư mục, chẳng hạn thư mục của ứng dụng khác, thư mục hệ thống và thư mục ẩn +@plural {n} linked file not found|{n} linked files not found Không tìm thấy {n} tệp liên kết +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} ảnh liên kết đã thay đổi trên đĩa. Hiện phiên bản mới? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} ảnh liên kết đã thay đổi kể từ khi lưu tài liệu. Hiện phiên bản mới? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. Còn {n} quy tắc nữa: Xuất sẽ ghi tất cả. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} đối tượng chưa đặt tên bị bỏ qua: hãy đặt tên hoặc bật Đối tượng chưa đặt tên trong menu bảng. {effect} is already applied {effect} đã được áp dụng - {folders} folder(s) and {files} file(s) searched Đã tìm kiếm {folders} thư mục và {files} tệp + {folders} and {files} searched Đã tìm kiếm {folders} và {files} +@plural {n} folder|{n} folders {n} thư mục +@plural {n} file|{n} files {n} tệp {format} Options Tùy chọn {format} {kind} Gradient Chuyển sắc {kind} gradient-kind Radial Hướng tâm @@ -5191,10 +5193,10 @@ axis Y Axis Trục Y @msg Packaged {n} file(s) in {folder} Đã đóng gói {n} tệp trong {folder} @msg Packaged {n} file(s) {note} Đã đóng gói {n} tệp {note} @msg Packaged {n} file(s) Đã đóng gói {n} tệp - Packaged {n} file(s) Đã đóng gói {n} tệp - Packaged {n} file(s) in {folder} Đã đóng gói {n} tệp trong {folder} - Packaged {n} file(s) {note} Đã đóng gói {n} tệp {note} - {count} file(s) in {folder}. Show the package folder? {count} tệp trong {folder}. Hiện thư mục gói? +@plural Packaged {n} file|Packaged {n} files Đã đóng gói {n} tệp +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Đã đóng gói {n} tệp trong {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Đã đóng gói {n} tệp {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} tệp trong {folder}. Hiện thư mục gói? Clockwise Theo chiều kim đồng hồ Dither Dither Fine noise hides banding in the gradient fill Nhiễu mịn che dải màu trong vùng tô chuyển sắc diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index a85bc1a63a..7c930a444f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -162,7 +162,7 @@ Apply Paragraph Style 应用段落样式 Apply SVG Filter… 应用 SVG 滤镜… Apply to All 应用到全部 - Apply to All ({count} more missing) 全部应用 (另有 {count} 个缺失) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) 全部应用 (另有 {n} 个缺失) Arc 弧形 Arc Lower… 下弧形… Arc Tool 弧形工具 @@ -2169,7 +2169,7 @@ file-filter Templates 模板 Package 打包 Package collects a saved document with its linked files and fonts. 打包会将已存储的文件连同其链接文件与字体一并收集。 Package created 已创建打包 - Packaged {n} file(s) in {folder} {note} 已将 {n} 个文件打包于 {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} 已将 {n} 个文件打包于 {folder}{note} Packaged {n} file(s){note} 已打包 {n} 个文件{note} Package… 打包… Page 页面 @@ -2494,9 +2494,11 @@ font-script Japanese 汉字 Stop 停止 Searching… 正在搜索… Not found 未找到 - {folders} folder(s) and {files} file(s) searched 已搜索 {folders} 个文件夹、{files} 个文件 - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones 已跳过 {count} 个文件夹,例如其他应用程序和系统的文件夹,以及隐藏的文件夹 - {count} folder(s) or file(s) couldn't be read 有 {count} 个文件夹或文件无法读取 + {folders} and {files} searched 已搜索 {folders}、{files} +@plural {n} folder|{n} folders {n} 个文件夹 +@plural {n} file|{n} files {n} 个文件 +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones 已跳过 {n} 个文件夹,例如其他应用程序和系统的文件夹,以及隐藏的文件夹 +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read 有 {n} 个文件夹或文件无法读取 The search stopped at its limit: search a smaller folder. 搜索已达上限而停止:请搜索较小的文件夹。 Copy only fonts you own or are licensed to install. 只复制您拥有或已获得安装许可的字体。 VectorCraft copies the fonts to {folder}. VectorCraft 会将字体复制到 {folder}。 @@ -3377,7 +3379,7 @@ font-script Japanese 汉字 Update Link 更新链接 Update Links 更新链接 Update Changed Links 更新已更改的链接 - {count} linked image(s) changed on disk. Show the new versions? 有 {count} 个链接图像已在磁盘上更改。要显示新版本吗? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? 有 {n} 个链接图像已在磁盘上更改。要显示新版本吗? @msg Updated {_1} linked file(s) changed on disk 已更新 {_1} 个在磁盘上更改的链接文件 @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel 链接的图片在找到其文件之前显示文件中存储的低分辨率预览:请在“链接”面板中重新链接 @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise 框架高度不足以容纳所显示字体一行的区域文字已加高框架 ({_1}):否则文字不会显示 @@ -3551,12 +3553,12 @@ font-script Japanese 汉字 Zoom Tool 缩放工具 Zoom with Mouse Wheel 使用鼠标滚轮缩放 Scrub Numeric Fields by Dragging 拖动以调整数值字段 - {count} file(s) in {folder} {note}. Show the package folder? {folder} 中有 {count} 个文件{note}。要显示打包文件夹吗? - {count} linked file(s) not found 找不到 {count} 个链接文件 +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder} 中有 {n} 个文件{note}。要显示打包文件夹吗? +@plural {n} linked file not found|{n} linked files not found 找不到 {n} 个链接文件 fonts not copied: {fonts} 未复制的字体:{fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? 自存储此文档后,有 {count} 个链接图像已更改。要显示新版本吗? - {count} more rules: Export writes every one. 另有 {count} 条规则:导出时会全部写出。 - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 已略过 {count} 个未命名对象:请为它们命名,或在面板菜单中开启“未命名对象”。 +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? 自存储此文档后,有 {n} 个链接图像已更改。要显示新版本吗? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. 另有 {n} 条规则:导出时会全部写出。 +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 已略过 {n} 个未命名对象:请为它们命名,或在面板菜单中开启“未命名对象”。 {effect} is already applied 已应用 {effect} {format} Options {format} 选项 {kind} Gradient {kind}渐变 @@ -5433,10 +5435,10 @@ axis Y Axis Y 轴 @msg Packaged {n} file(s) in {folder} 已将 {n} 个文件打包到 {folder} @msg Packaged {n} file(s) {note} 已打包 {n} 个文件 {note} @msg Packaged {n} file(s) 已打包 {n} 个文件 - Packaged {n} file(s) 已打包 {n} 个文件 - Packaged {n} file(s) in {folder} 已将 {n} 个文件打包到 {folder} - Packaged {n} file(s) {note} 已打包 {n} 个文件 {note} - {count} file(s) in {folder}. Show the package folder? {folder} 中有 {count} 个文件。要显示打包文件夹吗? +@plural Packaged {n} file|Packaged {n} files 已打包 {n} 个文件 +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} 已将 {n} 个文件打包到 {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} 已打包 {n} 个文件 {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {folder} 中有 {n} 个文件。要显示打包文件夹吗? Clockwise 顺时针 Dither 仿色 Fine noise hides banding in the gradient fill 细微杂色可隐藏渐变填色中的色带 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 7fe82d929f..b3cfda873a 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -175,7 +175,7 @@ font-technology Variable 可變 Apply Paragraph Style 套用段落樣式 Apply SVG Filter… 套用 SVG 濾鏡… Apply to All 全部套用 - Apply to All ({count} more missing) 全部套用 (另有 {count} 個遺失) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) 全部套用 (另有 {n} 個遺失) Arc 弧形 Arc Lower… 下弧形… Arc Tool 弧形工具 @@ -3108,7 +3108,7 @@ file-filter Templates 範本 Package 封裝 Package collects a saved document with its linked files and fonts. 封裝會將已儲存的文件連同其連結檔案與字體一併收集。 Package created 已建立封裝 - Packaged {n} file(s) in {folder} {note} 已將 {n} 個檔案封裝於 {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} 已將 {n} 個檔案封裝於 {folder}{note} Packaged {n} file(s){note} 已封裝 {n} 個檔案{note} Package… 封裝… Page 頁面 @@ -3435,9 +3435,11 @@ font-script Japanese 漢字 Stop 停止 Searching… 搜尋中… Not found 找不到 - {folders} folder(s) and {files} file(s) searched 已搜尋 {folders} 個資料夾、{files} 個檔案 - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones 已略過 {count} 個資料夾,例如其他應用程式和系統的資料夾,以及隱藏的資料夾 - {count} folder(s) or file(s) couldn't be read 有 {count} 個資料夾或檔案無法讀取 + {folders} and {files} searched 已搜尋 {folders}、{files} +@plural {n} folder|{n} folders {n} 個資料夾 +@plural {n} file|{n} files {n} 個檔案 +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones 已略過 {n} 個資料夾,例如其他應用程式和系統的資料夾,以及隱藏的資料夾 +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read 有 {n} 個資料夾或檔案無法讀取 The search stopped at its limit: search a smaller folder. 搜尋已達上限而停止:請搜尋較小的資料夾。 Copy only fonts you own or are licensed to install. 只複製您擁有或已取得安裝授權的字體。 VectorCraft copies the fonts to {folder}. VectorCraft 會將字體複製到 {folder}。 @@ -4359,7 +4361,7 @@ font-script Japanese 漢字 Update Link 更新連結 Update Links 更新連結 Update Changed Links 更新已變更的連結 - {count} linked image(s) changed on disk. Show the new versions? 有 {count} 個連結影像已在磁碟上變更。要顯示新版本嗎? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? 有 {n} 個連結影像已在磁碟上變更。要顯示新版本嗎? @msg Updated {_1} linked file(s) changed on disk 已更新 {_1} 個在磁碟上變更的連結檔案 @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel 連結的圖片在找到其檔案之前顯示檔案中儲存的低解析度預覽:請在「連結」面板中重新連結 @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise 框架高度不足以容納所顯示字體一行的區域文字已加高框架 ({_1}):否則文字不會顯示 @@ -4533,12 +4535,12 @@ font-script Japanese 漢字 Zoom Tool 縮放工具 Zoom with Mouse Wheel 使用滑鼠滾輪縮放 Scrub Numeric Fields by Dragging 拖曳以調整數值欄位 - {count} file(s) in {folder} {note}. Show the package folder? {folder} 中有 {count} 個檔案{note}。要顯示封裝資料夾嗎? - {count} linked file(s) not found 找不到 {count} 個連結檔案 +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder} 中有 {n} 個檔案{note}。要顯示封裝資料夾嗎? +@plural {n} linked file not found|{n} linked files not found 找不到 {n} 個連結檔案 fonts not copied: {fonts} 未複製的字體:{fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? 自儲存此文件後,有 {count} 個連結影像已變更。要顯示新版本嗎? - {count} more rules: Export writes every one. 另有 {count} 條規則:匯出時會全部寫出。 - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 已略過 {count} 個未命名物件:請為它們命名,或在面板選單中開啟「未命名物件」。 +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? 自儲存此文件後,有 {n} 個連結影像已變更。要顯示新版本嗎? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. 另有 {n} 條規則:匯出時會全部寫出。 +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 已略過 {n} 個未命名物件:請為它們命名,或在面板選單中開啟「未命名物件」。 {effect} is already applied 已套用 {effect} {format} Options {format} 選項 {kind} Gradient {kind}漸層 @@ -5228,10 +5230,10 @@ axis Y Axis Y 軸 @msg Packaged {n} file(s) in {folder} 已將 {n} 個檔案封裝到 {folder} @msg Packaged {n} file(s) {note} 已封裝 {n} 個檔案 {note} @msg Packaged {n} file(s) 已封裝 {n} 個檔案 - Packaged {n} file(s) 已封裝 {n} 個檔案 - Packaged {n} file(s) in {folder} 已將 {n} 個檔案封裝到 {folder} - Packaged {n} file(s) {note} 已封裝 {n} 個檔案 {note} - {count} file(s) in {folder}. Show the package folder? {folder} 中有 {count} 個檔案。要顯示封裝資料夾嗎? +@plural Packaged {n} file|Packaged {n} files 已封裝 {n} 個檔案 +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} 已將 {n} 個檔案封裝到 {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} 已封裝 {n} 個檔案 {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {folder} 中有 {n} 個檔案。要顯示封裝資料夾嗎? Clockwise 順時針 Dither 仿色 Fine noise hides banding in the gradient fill 細微雜色可隱藏漸層填色中的色帶 diff --git a/crates/ui-egui/src/panels/css_properties.rs b/crates/ui-egui/src/panels/css_properties.rs index 5b0fe407a4..97e270e3c8 100644 --- a/crates/ui-egui/src/panels/css_properties.rs +++ b/crates/ui-egui/src/panels/css_properties.rs @@ -129,12 +129,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); }); let notes = (shown.more > 0) - .then(|| crate::i18n::fmt(tl!("{count} more rules: Export writes every one."), &[("count", &shown.more.to_string())])) + .then(|| crate::i18n::tn(shown.more as u64, "{n} more rule: Export writes it.", "{n} more rules: Export writes every one.")) .into_iter() .chain((shown.skipped > 0).then(|| { - crate::i18n::fmt( - tl!("{count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu."), - &[("count", &shown.skipped.to_string())], + crate::i18n::tn( + shown.skipped, + "{n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.", + "{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu.", ) })) .chain(shown.warnings.iter().map(|w| sentence(w))); diff --git a/crates/ui-egui/src/panels/tests_css_properties.rs b/crates/ui-egui/src/panels/tests_css_properties.rs index 1034daeb33..a23f108eb2 100644 --- a/crates/ui-egui/src/panels/tests_css_properties.rs +++ b/crates/ui-egui/src/panels/tests_css_properties.rs @@ -61,6 +61,33 @@ fn generate_css_shows_the_document_while_nothing_is_selected() { assert!(text.contains(".rectangle {") && text.contains(".ellipse {") && text.contains("border-radius: 50%;"), "{text}"); } +/// The note on unnamed objects left out uses the form the language's plural rule picks for the +/// count. +#[test] +fn the_unnamed_objects_note_uses_each_count_form() { + let note = |code: &str, n: u64| { + let (mut app, _) = app(); + for i in 1..n { + app.run("shape.rectangle", json!({"x": 10 + 40 * i, "y": 50, "width": 30, "height": 20})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + crate::i18n::set_current(crate::i18n::Lang::from_code(code).unwrap()); + let text = painted_text(&mut app, |app, ui| { + set_pstate(ui.ctx(), OPTIONS, CssOptions { unnamed: false, ..CssOptions::default() }); + show(app, ui); + }); + crate::i18n::set_current(crate::i18n::Lang::EN); + text + }; + let text = note("en", 1); + assert!(text.contains("1 unnamed object left out: name it,"), "{text}"); + for (n, want) in [(1, "Vynechán 1 nepojmenovaný objekt."), (2, "Vynechány 2 nepojmenované objekty."), (5, "Vynecháno 5 nepojmenovaných objektů.")] + { + let text = note("cs", n); + assert!(text.contains(want), "{n}: {text}"); + } +} + #[test] fn the_panel_menu_lists_the_actions_and_options() { let (mut app, _) = app(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0634080f47..af17606c0e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -587,6 +587,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Czech render-site labels: desktop/web file filters, diagnostics, suggested preset names and contributor tooltips/plurals now use catalog lookups; gradients have Czech adjective agreement and printer marks have a separate context (PDF/Print and Summary). Search, Home, toolbar/panel tooltips and Preferences already look up their labels. Every complete catalog has rows for these labels and for the Roman and Japanese printer mark styles. Evidence: `i18n::tests::czech_render_site_follow_up`, `i18n::tests::complete_catalogs_translate_render_site_labels`, `dialogs::tests_modal::printer_mark_labels_are_distinct_from_language_names`; see [localization-parity.md](localization-parity.md). - The History panel, Edit › Undo and Edit › Redo translate the names of the steps that apply or redefine a character or paragraph style and of the step that redefines a graphic style: each such step keeps its template (`Apply {name}`, `Redefine {name}`, `Redefine Graphic Style “{name}”`) and the style's name, every complete catalog has a row for each template, and the panel and the menu show the style's name as the document holds it, except the Normal styles' names, which they show in the interface language (`steps_named_after_a_style_list_the_template_around_the_name`, `undo_and_redo_name_a_style_step_around_the_style_name`). - Localised UI: menus (in-window and native), panels, dialogs, toolbar and Preferences read from per-language catalogs (`crates/ui-egui/src/i18n`, see `docs/development.md`); Traditional Chinese (Taiwan), Simplified Chinese (mainland), Japanese, Korean, Vietnamese, German, Spanish, French, Italian, Polish, Brazilian Portuguese, Russian, Ukrainian, Georgian and Catalan ship complete, and Czech covers every menu label (and more), with system-locale detection on macOS, Windows, Linux and the web (the browser's languages, or `?lang=`), a Language preference and, on macOS, a VectorCraft ▸ Language menu. Names are never translated (fonts and their styles, layers, artboards, saved presets, user libraries, custom workspaces, recent files, plug-ins). + The counts that Package's status and question, the folder search of Missing Fonts and Find Linked Files, the modified and missing linked file prompts and the CSS Properties panel's notes show use the interface language's plural forms instead of a fixed "(s)" form. Evidence: `the_missing_links_note_uses_each_count_form` in `crates/ui-egui/src/dialogs/tests_package.rs`, `the_modified_links_question_uses_each_count_form` in `crates/ui-egui/src/dialogs/missing_links.rs`, `search_counts_use_each_count_form` in `crates/ui-egui/src/dialogs/missing_fonts/tests.rs` and `the_unnamed_objects_note_uses_each_count_form` in `crates/ui-egui/src/panels/tests_css_properties.rs`. - Edit › Undo and Edit › Redo, in the in-window and native menus, name the step in the interface language as the History panel lists it (`panels::history::step_name`), so when the catalog has no plain row for a step named after an effect, such as Feather, the menu shows the translation of the effect's menu row without its ellipsis (`undo_and_redo_name_the_step_as_the_history_panel_does`). - The History panel translates the undo step names the engine, the tools and the shell write as literals: the untranslated report (`untranslated_report`) lists any a complete catalog lacks, and a step whose catalog row exists only with an ellipsis (such as an effect's menu name) shows that row without the ellipsis. - The History panel menu has Step Backward and Step Forward, which run Edit › Undo and Edit › Redo and are disabled when there is no step to undo or redo, and Set History Limit…, which opens Preferences at Performance, where History States is set. Not done: a new document from the selected state. From 89ca9d9a255cfa54aa99fbd11f66c6de328e2aa6 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 30 Oct 2026 21:16:48 -0700 Subject: [PATCH 147/260] Batch: keep an existing artboard file of a one-artboard Separate Artboards save A save in the native, template or .ai formats with separateArtboards writes an artboard file even when the document has one artboard, so an existing file with that name now gives the data set the next free suffix too. --- crates/engine/src/cmd/fileio/action_batch.rs | 89 ++++++++++++++------ docs/mcp.md | 7 +- 2 files changed, 66 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 1caa98db7d..e11b6adcd6 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -292,8 +292,9 @@ struct DatasetOutput { joiner: &'static str, } -/// Lists step output extensions and reserves artboard file names when the document has multiple artboards. -/// Per-artboard names count for vectorcraft, template, AI and AIT saves and SVG, SVGZ, EPS, raster, DXF, EMF, WMF and AI exports. +/// Lists step output extensions and reserves artboard file names for saves with any artboard or +/// exports with multiple artboards. Per-artboard names count for vectorcraft, template, AI and AIT +/// saves and SVG, SVGZ, EPS, raster, DXF, EMF, WMF and AI exports. #[cfg(not(target_arch = "wasm32"))] fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document) -> Vec<DatasetOutput> { let mut outputs = Vec::new(); @@ -314,31 +315,31 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document) -> if safe_extension(&ext) { let format_id = format.and_then(super::format).map(|f| f.id).unwrap_or("vectorcraft"); let is_save = matches!(id, "document.save" | "file.save" | "file.saveAs"); - let artboards = doc.artboards.len() > 1 - && if is_save { - matches!(format_id, "vectorcraft" | "template" | "ai" | "ait") - } else { - id == "document.export" - && matches!( - format_id, - "svg" - | "svgz" - | "eps" - | "png" - | "jpg" - | "webp" - | "gif" - | "png8" - | "tiff" - | "bmp" - | "tga" - | "psd" - | "dxf" - | "emf" - | "wmf" - | "ai" - ) - }; + let artboards = if is_save { + !doc.artboards.is_empty() && matches!(format_id, "vectorcraft" | "template" | "ai" | "ait") + } else { + doc.artboards.len() > 1 + && id == "document.export" + && matches!( + format_id, + "svg" + | "svgz" + | "eps" + | "png" + | "jpg" + | "webp" + | "gif" + | "png8" + | "tiff" + | "bmp" + | "tga" + | "psd" + | "dxf" + | "emf" + | "wmf" + | "ai" + ) + }; outputs.push(DatasetOutput { ext, artboards, joiner: if format_id == "eps" { "_" } else { "-" } }); } } @@ -952,6 +953,40 @@ mod tests { ); } + #[test] + fn batch_single_artboard_save_keeps_existing_artboard_file() { + let source = tmp("choice-single-artboard-source"); + let dest = tmp("choice-single-artboard-dest"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 1})).unwrap(); + s.execute( + "document.save", + &json!({ + "path": source.join("source.vectorcraft").to_string_lossy(), + "separateArtboards": true + }), + ) + .unwrap(); + assert!(source.join("source-Artboard-1.vectorcraft").exists()); + + let existing = dest.join("Alpha-Artboard-1.vectorcraft"); + std::fs::write(&existing, b"keep").unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.save", "params": {"separateArtboards": true}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(existing).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-2-Artboard-1.vectorcraft", "Alpha-2.vectorcraft", "Alpha-Artboard-1.vectorcraft"]); + } + #[test] fn batch_pdf_export_ignores_artboard_named_file() { let dest = tmp("choice-pdf-artboard-name"); diff --git a/docs/mcp.md b/docs/mcp.md index f904715027..a03d5db9f8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2971,9 +2971,10 @@ destination and overridden Save/Export paths use the chosen stem with the output set name under Data Set Name falls back to the document stem plus its three-digit ordinal. Batch writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds the next free `-2`, `-3` suffix to a stem already used in the batch (compared without case). An output already in a destination folder -gets the next free suffix only when the batch may read and write that folder before it starts. When a step can write -one file per artboard and the document has several artboards, a file with one of those artboard file names for the -stem counts too. Under Data Set Name, VectorCraft makes Windows device names safe (`CON` becomes `CON-`). This is +gets the next free suffix only when the batch may read and write that folder before it starts. A save in VectorCraft, +template, AI or AIT format counts artboard file names when the document has any artboard; a per-artboard export +counts them when the document has several artboards. +Under Data Set Name, VectorCraft makes Windows device names safe (`CON` becomes `CON-`). This is VectorCraft's naming behavior. Caps: 500 files or data sets, 8 folder levels, 256 steps. An action recorded in the Actions panel leaves the artboard out, and its steps of these commands get the artboard that is active when the action plays. A press with the Selection, From 28014a9fed3243ec1a780774704fb3d4d32360b0 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 01:11:36 -0700 Subject: [PATCH 148/260] i18n: French one-item count forms keep the no-break space before ? and : --- crates/ui-egui/src/i18n/fr.tsv | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 29cb4e6d1c..a93869adf7 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3676,13 +3676,13 @@ font-technology Variable Variables Zoom Tool Outil Zoom Zoom with Mouse Wheel Zoom avec la molette de la souris Scrub Numeric Fields by Dragging Modifier les champs numériques en faisant glisser -@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fichier dans {folder} {note}. Afficher le dossier de l’assemblage ?|{n} fichiers dans {folder} {note}. Afficher le dossier de l’assemblage ? +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fichier dans {folder} {note}. Afficher le dossier de l’assemblage ?|{n} fichiers dans {folder} {note}. Afficher le dossier de l’assemblage ? @plural {n} linked file not found|{n} linked files not found {n} fichier lié introuvable|{n} fichiers liés introuvables fonts not copied: {fonts} polices non copiées : {fonts} -@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} image liée modifiée depuis l’enregistrement de ce document. Afficher la nouvelle version ?|{n} images liées modifiées depuis l’enregistrement de ce document. Afficher les nouvelles versions ? -@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} image liée modifiée sur le disque. Afficher la nouvelle version ?|{n} images liées modifiées sur le disque. Afficher les nouvelles versions ? -@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} règle de plus : Exporter l’écrit.|{n} règles de plus : Exporter les écrit toutes. -@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} objet sans nom omis : nommez-le ou activez Objets sans nom dans le menu du panneau.|{n} objets sans nom omis : nommez-les ou activez Objets sans nom dans le menu du panneau. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} image liée modifiée depuis l’enregistrement de ce document. Afficher la nouvelle version ?|{n} images liées modifiées depuis l’enregistrement de ce document. Afficher les nouvelles versions ? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} image liée modifiée sur le disque. Afficher la nouvelle version ?|{n} images liées modifiées sur le disque. Afficher les nouvelles versions ? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} règle de plus : Exporter l’écrit.|{n} règles de plus : Exporter les écrit toutes. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} objet sans nom omis : nommez-le ou activez Objets sans nom dans le menu du panneau.|{n} objets sans nom omis : nommez-les ou activez Objets sans nom dans le menu du panneau. {effect} is already applied {effect} est déjà appliqué {format} Options Options {format} {kind} Gradient Dégradé {kind} @@ -5597,7 +5597,7 @@ axis Y Axis Axe Y @plural Packaged {n} file|Packaged {n} files {n} fichier assemblé|{n} fichiers assemblés @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} fichier assemblé dans {folder}|{n} fichiers assemblés dans {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} {n} fichier assemblé {note}|{n} fichiers assemblés {note} -@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} fichier dans {folder}. Afficher le dossier de l’assemblage ?|{n} fichiers dans {folder}. Afficher le dossier de l’assemblage ? +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} fichier dans {folder}. Afficher le dossier de l’assemblage ?|{n} fichiers dans {folder}. Afficher le dossier de l’assemblage ? Clockwise Sens horaire Dither Simulation Fine noise hides banding in the gradient fill Un bruit fin masque les bandes du fond en dégradé From 62401182e6919c60b8859ad68a917fc3bd403fea Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 02:08:33 -0700 Subject: [PATCH 149/260] i18n: an English package status is translated after a language switch, in each language's plural form MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The package status now says "file" or "files", and the catalogs' `@msg` rows for it still matched only the old "file(s)" text, so a status written in English stayed in English after a switch to another language. - Catalogs take a new `@msgplural` row: the English one|other forms as the source and the language's plural forms as the translation. The `{n}` value picks the form, so Czech shows "Zabaleny 3 soubory" for 3 files and "Zabaleno 5 souborů" for 5. - Every catalog replaces its four package status rows with `@msgplural` rows. The row for a status with a note finds the note by its opening parenthesis, so a folder name with spaces stays whole. - `package_status` builds the status line for the folder and the web download. --- crates/ui-egui/src/dialogs/package.rs | 31 ++++++++--------- crates/ui-egui/src/dialogs/tests_package.rs | 34 +++++++++++++++++++ crates/ui-egui/src/i18n.rs | 7 +++- crates/ui-egui/src/i18n/bg.tsv | 8 ++--- crates/ui-egui/src/i18n/bs.tsv | 8 ++--- crates/ui-egui/src/i18n/ca.tsv | 8 ++--- crates/ui-egui/src/i18n/catalog.rs | 37 +++++++++++++++------ crates/ui-egui/src/i18n/cs.tsv | 8 ++--- crates/ui-egui/src/i18n/da.tsv | 8 ++--- crates/ui-egui/src/i18n/de.tsv | 8 ++--- crates/ui-egui/src/i18n/el.tsv | 8 ++--- crates/ui-egui/src/i18n/es.tsv | 8 ++--- crates/ui-egui/src/i18n/fi.tsv | 8 ++--- crates/ui-egui/src/i18n/fr.tsv | 8 ++--- crates/ui-egui/src/i18n/hu.tsv | 8 ++--- crates/ui-egui/src/i18n/id.tsv | 8 ++--- crates/ui-egui/src/i18n/it.tsv | 8 ++--- crates/ui-egui/src/i18n/ja.tsv | 8 ++--- crates/ui-egui/src/i18n/ka.tsv | 8 ++--- crates/ui-egui/src/i18n/ko.tsv | 8 ++--- crates/ui-egui/src/i18n/nl.tsv | 8 ++--- crates/ui-egui/src/i18n/pl.tsv | 8 ++--- crates/ui-egui/src/i18n/pt-br.tsv | 8 ++--- crates/ui-egui/src/i18n/ru.tsv | 8 ++--- crates/ui-egui/src/i18n/sv.tsv | 8 ++--- crates/ui-egui/src/i18n/tests.rs | 19 ++++++++++- crates/ui-egui/src/i18n/tr.tsv | 8 ++--- crates/ui-egui/src/i18n/uk.tsv | 8 ++--- crates/ui-egui/src/i18n/vi.tsv | 8 ++--- crates/ui-egui/src/i18n/zh-hans.tsv | 8 ++--- crates/ui-egui/src/i18n/zh-hant.tsv | 8 ++--- 31 files changed, 205 insertions(+), 131 deletions(-) diff --git a/crates/ui-egui/src/dialogs/package.rs b/crates/ui-egui/src/dialogs/package.rs index 9c2b3deb97..5b49be69eb 100644 --- a/crates/ui-egui/src/dialogs/package.rs +++ b/crates/ui-egui/src/dialogs/package.rs @@ -160,24 +160,11 @@ fn packaged(app: &mut VectorcraftApp, r: Result<Value, String>, web: bool, later let (name, data) = (r["name"].as_str().unwrap_or("package.zip"), r["dataBase64"].as_str().unwrap_or_default()); let bytes = vectorcraft_format::base64_decode(data).ok_or("the package came back damaged")?; io::write_named(app, None, name, &bytes)?; - let status = if shown_note.is_empty() { - crate::i18n::tn(n, "Packaged {n} file", "Packaged {n} files") - } else { - crate::i18n::fmt(&crate::i18n::tn(n, "Packaged {n} file {note}", "Packaged {n} files {note}"), &[("note", &shown_note)]) - }; - app.status(status); + app.status(package_status(n, None, &shown_note)); return Ok(r); } let folder = r["folder"].as_str().unwrap_or_default().to_string(); - let status = if shown_note.is_empty() { - crate::i18n::fmt(&crate::i18n::tn(n, "Packaged {n} file in {folder}", "Packaged {n} files in {folder}"), &[("folder", &folder)]) - } else { - crate::i18n::fmt( - &crate::i18n::tn(n, "Packaged {n} file in {folder} {note}", "Packaged {n} files in {folder} {note}"), - &[("folder", &folder), ("note", &shown_note)], - ) - }; - app.status(status); + app.status(package_status(n, Some(&folder), &shown_note)); let detail = if shown_note.is_empty() { crate::i18n::fmt( &crate::i18n::tn(n, "{n} file in {folder}. Show the package folder?", "{n} files in {folder}. Show the package folder?"), @@ -195,6 +182,20 @@ fn packaged(app: &mut VectorcraftApp, r: Result<Value, String>, web: bool, later Ok(r) } +/// The status bar's line for a package of `n` files written to `folder` (`None`: the web's +/// download), followed by `note` from [`package_status_note`] when it isn't empty. Each catalog +/// also has `@msgplural` rows for the English line, shown after a language switch; they find the note +/// after the folder by its opening `(`, so a folder name with spaces stays whole. +pub(super) fn package_status(n: u64, folder: Option<&str>, note: &str) -> String { + let (one, other) = match (folder.is_some(), note.is_empty()) { + (false, true) => ("Packaged {n} file", "Packaged {n} files"), + (false, false) => ("Packaged {n} file {note}", "Packaged {n} files {note}"), + (true, true) => ("Packaged {n} file in {folder}", "Packaged {n} files in {folder}"), + (true, false) => ("Packaged {n} file in {folder} {note}", "Packaged {n} files in {folder} {note}"), + }; + crate::i18n::fmt(&crate::i18n::tn(n, one, other), &[("folder", folder.unwrap_or_default()), ("note", note)]) +} + /// Parenthetical notes after the folder path in a package status (`(2 linked files not found)` …), /// joined with spaces and without a leading space (#3494). pub(super) fn package_status_note(missing: usize, fonts: &str) -> String { diff --git a/crates/ui-egui/src/dialogs/tests_package.rs b/crates/ui-egui/src/dialogs/tests_package.rs index 22c5e2a357..91d95d922a 100644 --- a/crates/ui-egui/src/dialogs/tests_package.rs +++ b/crates/ui-egui/src/dialogs/tests_package.rs @@ -302,6 +302,40 @@ fn the_missing_links_note_uses_each_count_form() { assert_eq!(note("cs", 5), "(Nenalezeno 5 propojených souborů)"); } +/// A package status written in English, for one file or several, with or without a folder and a +/// note, is translated by every catalog when the status bar shows it after a language switch, in +/// the form the language's plural rule picks for the count, and a folder whose name has a space +/// keeps its whole name. +#[test] +fn an_english_package_status_is_translated_after_a_language_switch() { + use crate::i18n::{Lang, message}; + let mut statuses = vec![]; + for n in [1, 3] { + for folder in [None, Some("/out/card Folder")] { + for note in ["", "(fonts not copied: Mono)"] { + statuses.push(package::package_status(n, folder, note)); + } + } + } + assert!(statuses.contains(&"Packaged 1 file in /out/card Folder".to_string()), "{statuses:?}"); + assert!(statuses.contains(&"Packaged 3 files".to_string()), "{statuses:?}"); + for lang in Lang::all().filter(|l| l.code() != "en") { + for s in &statuses { + let shown = message(lang, s); + assert!(!shown.starts_with("Packaged"), "{}: {shown}", lang.code()); + // A space in the folder's name stays in the path, with or without a note. + assert_eq!(s.contains("/out/card Folder"), shown.contains("/out/card Folder"), "{}: {shown}", lang.code()); + } + } + let cs = Lang::from_code("cs").unwrap(); + assert_eq!(message(cs, "Packaged 1 file in /out"), "Zabalen 1 soubor do /out"); + assert_eq!(message(cs, "Packaged 3 files in /out"), "Zabaleny 3 soubory do /out"); + assert_eq!(message(cs, "Packaged 5 files in /out"), "Zabaleno 5 souborů do /out"); + let de = Lang::from_code("de").unwrap(); + assert_eq!(message(de, "Packaged 1 file"), "1 Datei verpackt"); + assert_eq!(message(de, "Packaged 3 files in /out"), "3 Dateien in /out verpackt"); +} + #[test] fn package_status_without_notes_has_no_extra_spaces() { let dir = Folder::new("spaces"); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index af85867d85..dee009b768 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -23,6 +23,8 @@ //! message itself stays English (the control channel, MCP and tests read it); `@msg` catalog //! rows hold whole messages or templates such as `Couldn't open {name}: {e}`, and the values in //! the placeholders are translated in turn (the reason after `: {e}` is often a message too). +//! A `@msgplural` row is a template with a count: its source holds the English `one|other` +//! forms, its translation the language's plural forms, and the `{n}` value picks the form. mod catalog; @@ -651,7 +653,10 @@ pub fn message(lang: Lang, s: &str) -> String { } fn message_at(lang: Lang, s: &str, depth: usize) -> String { - let Some((template, caps)) = lang.catalog().message(s) else { return s.to_string() }; + let Some((forms, caps)) = lang.catalog().message_forms(s) else { return s.to_string() }; + let count = caps.iter().find(|(k, _)| *k == "n").and_then(|(_, v)| v.parse::<u64>().ok()); + let form = count.map_or(forms.len().saturating_sub(1), |n| (lang.0.plural)(n).min(forms.len().saturating_sub(1))); + let Some(template) = forms.get(form) else { return s.to_string() }; let values: Vec<(&str, String)> = caps.into_iter().map(|(k, v)| (k, if depth > 1 { message_at(lang, v, depth - 1) } else { v.to_string() })).collect(); let args: Vec<(&str, &str)> = values.iter().map(|(k, v)| (*k, v.as_str())).collect(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index fd7a177514..0afca3ee6d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3833,7 +3833,7 @@ axis Both И двете @msg PDF settings are not an object Настройките за PDF не са обект @msg PDF security settings are not an object Настройките за сигурност на PDF не са обект @msg PDF writer error: {0} Грешка на PDF записа: {0} -@msg Packaged {n} file(s) in {folder} {note} Пакетирани са {n} файла в {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Пакетиран е {n} файл в {folder} ({note}|Пакетирани са {n} файла в {folder} ({note} @msg Packaged {n} file(s){note} Пакетирани са {n} файла{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Прегледът в браузър изисква настолното приложение (уеб версията изтегля файловете вместо това) @msg Release Guides: no guides Освобождаване на водачи: няма водачи @@ -5504,9 +5504,9 @@ theme Appearance Външен вид Slope: Наклон: axis X Axis X ос axis Y Axis Y ос -@msg Packaged {n} file(s) in {folder} Пакетирани са {n} файла в {folder} -@msg Packaged {n} file(s) {note} Пакетирани са {n} файла {note} -@msg Packaged {n} file(s) Пакетирани са {n} файла +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Пакетиран е {n} файл в {folder}|Пакетирани са {n} файла в {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Пакетиран е {n} файл {note}|Пакетирани са {n} файла {note} +@msgplural Packaged {n} file|Packaged {n} files Пакетиран е {n} файл|Пакетирани са {n} файла @plural Packaged {n} file|Packaged {n} files Пакетиран е {n} файл|Пакетирани са {n} файла @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Пакетиран е {n} файл в {folder}|Пакетирани са {n} файла в {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} Пакетиран е {n} файл {note}|Пакетирани са {n} файла {note} diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 0ff4eeeb64..9ce6565b97 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4199,7 +4199,7 @@ imageTrace Outline Obris @msg PDF settings are not an object PDF postavke nisu objekat @msg PDF security settings are not an object PDF sigurnosne postavke nisu objekat @msg PDF writer error: {0} greška PDF zapisivača: {0} -@msg Packaged {n} file(s) in {folder} {note} Upakovano datoteka u {folder}: {n} {note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Upakovano datoteka u {folder}: {n} ({note} @msg Packaged {n} file(s){note} Upakovano datoteka: {n}{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Pregledaj u pregledniku zahtijeva desktop aplikaciju (web umjesto toga preuzima datoteke) @msg Release Guides: no guides Oslobodi vodilice: nema vodilica @@ -5524,9 +5524,9 @@ mark-style Japanese Japanski Slope: Nagib: axis X Axis X osa axis Y Axis Y osa -@msg Packaged {n} file(s) in {folder} Upakovano datoteka u {folder}: {n} -@msg Packaged {n} file(s) {note} Upakovano datoteka: {n} {note} -@msg Packaged {n} file(s) Upakovano datoteka: {n} +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Upakovano datoteka u {folder}: {n} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Upakovano datoteka: {n} {note} +@msgplural Packaged {n} file|Packaged {n} files Upakovano datoteka: {n} @plural Packaged {n} file|Packaged {n} files Upakovano datoteka: {n}|Upakovano datoteka: {n}|Upakovano datoteka: {n} @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Upakovano datoteka u {folder}: {n}|Upakovano datoteka u {folder}: {n}|Upakovano datoteka u {folder}: {n} @plural Packaged {n} file {note}|Packaged {n} files {note} Upakovano datoteka: {n} {note}|Upakovano datoteka: {n} {note}|Upakovano datoteka: {n} {note} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 04608e692c..f6e37996d2 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5258,10 +5258,10 @@ @msg Opened with {_1} note(s): {_2} Obert amb {_1} nota(es): {_2} @msg Opened {url} Obert {url} @msg Outline Stroke: no stroked paths selected Contorneja el traç: no hi ha cap traçat amb traç seleccionat -@msg Packaged {n} file(s) Empaquetat {n} fitxer(s) -@msg Packaged {n} file(s) in {folder} Empaquetats {n} fitxer(s) a {folder} -@msg Packaged {n} file(s) in {folder} {note} Empaquetats {n} fitxer(s) a {folder} {note} -@msg Packaged {n} file(s) {note} Empaquetats {n} fitxer(s) {note} +@msgplural Packaged {n} file|Packaged {n} files S’ha empaquetat {n} fitxer|S’han empaquetat {n} fitxers +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} S’ha empaquetat {n} fitxer a {folder}|S’han empaquetat {n} fitxers a {folder} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} S’ha empaquetat {n} fitxer a {folder} ({note}|S’han empaquetat {n} fitxers a {folder} ({note} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} S’ha empaquetat {n} fitxer {note}|S’han empaquetat {n} fitxers {note} @msg Packaged {n} file(s){note} Empaquetats {n} fitxer(s){note} @msg Packaging {_1} Empaquetant {_1} @msg page size {w} × {h} mida de pàgina {w} × {h} diff --git a/crates/ui-egui/src/i18n/catalog.rs b/crates/ui-egui/src/i18n/catalog.rs index a79ce351a2..1be460212a 100644 --- a/crates/ui-egui/src/i18n/catalog.rs +++ b/crates/ui-egui/src/i18n/catalog.rs @@ -15,7 +15,8 @@ pub struct Catalog { plurals: HashMap<String, Vec<String>>, /// status and error messages without placeholders (`@msg`): English → translation messages: HashMap<String, String>, - /// status and error messages with `{name}` placeholders (`@msg`), most specific first + /// status and error messages with `{name}` placeholders (`@msg`, and each English form of a + /// `@msgplural` row), most specific first templates: Vec<Template>, } @@ -26,22 +27,26 @@ enum Piece { Hole(String), } -/// A message template (`Couldn't open {name}: {e}`) and its translation. +/// A message template (`Couldn't open {name}: {e}`) and its translation: one form for `@msg`, +/// the plural forms for `@msgplural`. #[derive(Debug)] struct Template { pieces: Vec<Piece>, /// Bytes of literal text: a template with more of it is the more specific match. literal: usize, - translation: String, + forms: Vec<String>, } +/// The placeholder values of a matched message template: placeholder name and value. +pub type Captures<'p, 'a> = Vec<(&'p str, &'a str)>; + /// Messages longer than this are shown as they are (template matching backtracks). const MAX_MESSAGE_LEN: usize = 2000; impl Template { /// `None` for a template that can't be matched reliably: no literal text, or two placeholders /// in a row (where one ends and the next begins is unknowable). - fn parse(source: &str, translation: String) -> Option<Template> { + fn parse(source: &str, forms: Vec<String>) -> Option<Template> { let mut pieces = Vec::new(); let mut rest = source; while let Some(a) = rest.find('{') { @@ -59,7 +64,7 @@ impl Template { pieces.push(Piece::Text(rest.to_string())); } let literal = pieces.iter().map(|p| if let Piece::Text(t) = p { t.len() } else { 0 }).sum(); - (literal > 0).then_some(Template { pieces, literal, translation }) + (literal > 0).then_some(Template { pieces, literal, forms }) } /// The placeholder values if `s` is an instance of this template. @@ -162,11 +167,15 @@ impl Catalog { } "@msg" => { if src.contains('{') { - c.templates.extend(Template::parse(&src, tr)); + c.templates.extend(Template::parse(&src, vec![tr])); } else { c.messages.insert(src, tr); } } + "@msgplural" => { + let forms: Vec<String> = tr.split('|').map(str::to_string).collect(); + c.templates.extend(src.split('|').filter_map(|english| Template::parse(english, forms.clone()))); + } _ => { c.contextual.insert(format!("{ctx}\u{1}{src}"), tr); } @@ -189,17 +198,25 @@ impl Catalog { self.ids.get(id).map(String::as_str) } + /// [`Catalog::message_forms`] with the first form of the translation. + #[cfg(test)] + pub fn message<'a>(&self, s: &'a str) -> Option<(&str, Captures<'_, 'a>)> { + self.message_forms(s).and_then(|(forms, caps)| Some((forms.first()?.as_str(), caps))) + } + /// A status or error message: an exact `@msg` entry, else the first template it is an instance /// of, with the placeholder values filled in. The values are returned for the caller to - /// translate (a reason after `…: {e}` is often a message of its own). - pub fn message<'a>(&self, s: &'a str) -> Option<(&str, Vec<(&str, &'a str)>)> { + /// translate (a reason after `…: {e}` is often a message of its own). The translation has one + /// form for an `@msg` row and the plural forms of a `@msgplural` row, of which the caller picks + /// one by the `{n}` value. + pub fn message_forms<'a>(&self, s: &'a str) -> Option<(&[String], Captures<'_, 'a>)> { if let Some(tr) = self.messages.get(s) { - return Some((tr.as_str(), Vec::new())); + return Some((std::slice::from_ref(tr), Vec::new())); } if s.len() > MAX_MESSAGE_LEN { return None; } - self.templates.iter().find_map(|t| t.captures(s).map(|caps| (t.translation.as_str(), caps))) + self.templates.iter().find_map(|t| t.captures(s).map(|caps| (t.forms.as_slice(), caps))) } /// The plural form `index` of the message whose English forms are `one|other`. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 28929b1cf8..40e788750e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4236,7 +4236,7 @@ imageTrace Outline Obrys @msg PDF settings are not an object nastavení PDF nejsou objekt @msg PDF security settings are not an object nastavení zabezpečení PDF nejsou objekt @msg PDF writer error: {0} chyba zápisu PDF: {0} -@msg Packaged {n} file(s) in {folder} {note} Zabaleno souborů: {n} do {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Zabalen {n} soubor do {folder} ({note}|Zabaleny {n} soubory do {folder} ({note}|Zabaleno {n} souborů do {folder} ({note} @msg Packaged {n} file(s){note} Zabaleno souborů: {n}{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Náhled v prohlížeči vyžaduje desktopovou aplikaci (webová verze místo toho stahuje soubory) @msg Release Guides: no guides Uvolnit vodítka: žádná vodítka @@ -5593,9 +5593,9 @@ mark-style Japanese Japonské Slope: Sklon: axis X Axis osa X axis Y Axis osa Y -@msg Packaged {n} file(s) in {folder} Zabaleno souborů: {n} do {folder} -@msg Packaged {n} file(s) {note} Zabaleno souborů: {n} {note} -@msg Packaged {n} file(s) Zabaleno souborů: {n} +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Zabalen {n} soubor do {folder}|Zabaleny {n} soubory do {folder}|Zabaleno {n} souborů do {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Zabalen {n} soubor {note}|Zabaleny {n} soubory {note}|Zabaleno {n} souborů {note} +@msgplural Packaged {n} file|Packaged {n} files Zabalen {n} soubor|Zabaleny {n} soubory|Zabaleno {n} souborů @plural Packaged {n} file|Packaged {n} files Zabalen {n} soubor|Zabaleny {n} soubory|Zabaleno {n} souborů @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Zabalen {n} soubor do {folder}|Zabaleny {n} soubory do {folder}|Zabaleno {n} souborů do {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} Zabalen {n} soubor {note}|Zabaleny {n} soubory {note}|Zabaleno {n} souborů {note} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index cd1eb284af..25cc8640d2 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3953,7 +3953,7 @@ imageTrace Outline Kontur @msg PDF settings are not an object PDF-indstillinger er ikke et objekt @msg PDF security settings are not an object PDF-sikkerhedsindstillinger er ikke et objekt @msg PDF writer error: {0} PDF-skriverfejl: {0} -@msg Packaged {n} file(s) in {folder} {note} Pakkede {n} fil(er) i {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Pakkede {n} fil i {folder} ({note}|Pakkede {n} filer i {folder} ({note} @msg Packaged {n} file(s){note} Pakkede {n} fil(er){note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Forhåndsvisning i browser kræver skrivebordsappen (webversionen downloader filer i stedet) @msg Release Guides: no guides Frigiv hjælpelinjer: ingen hjælpelinjer @@ -5519,9 +5519,9 @@ swatch Bright Violet Kraftig violet Slope: Hældning: axis X Axis X-akse axis Y Axis Y-akse -@msg Packaged {n} file(s) in {folder} Pakkede {n} fil(er) i {folder} -@msg Packaged {n} file(s) {note} Pakkede {n} fil(er) {note} -@msg Packaged {n} file(s) Pakkede {n} fil(er) +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Pakkede {n} fil i {folder}|Pakkede {n} filer i {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Pakkede {n} fil {note}|Pakkede {n} filer {note} +@msgplural Packaged {n} file|Packaged {n} files Pakkede {n} fil|Pakkede {n} filer @plural Packaged {n} file|Packaged {n} files Pakkede {n} fil|Pakkede {n} filer @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Pakkede {n} fil i {folder}|Pakkede {n} filer i {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} Pakkede {n} fil {note}|Pakkede {n} filer {note} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 00b281ec71..378b15fcf8 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3848,7 +3848,7 @@ theme Appearance Erscheinungsbild @msg PDF settings are not an object die PDF-Einstellungen sind kein Objekt @msg PDF security settings are not an object die PDF-Sicherheitseinstellungen sind kein Objekt @msg PDF writer error: {0} Fehler beim Schreiben der PDF-Datei: {0} -@msg Packaged {n} file(s) in {folder} {note} {n} Datei(en) in {folder} verpackt{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} {n} Datei in {folder} verpackt ({note}|{n} Dateien in {folder} verpackt ({note} @msg Packaged {n} file(s){note} {n} Datei(en) verpackt{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) „Vorschau im Browser“ erfordert die Desktop-App (im Web werden stattdessen Dateien heruntergeladen) @msg Release Guides: no guides Hilfslinien zurückwandeln: keine Hilfslinien @@ -5174,9 +5174,9 @@ effect Soft Weich Slope: Steigung: axis X Axis X-Achse axis Y Axis Y-Achse -@msg Packaged {n} file(s) in {folder} {n} Datei(en) in {folder} verpackt -@msg Packaged {n} file(s) {note} {n} Datei(en) verpackt {note} -@msg Packaged {n} file(s) {n} Datei(en) verpackt +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} Datei in {folder} verpackt|{n} Dateien in {folder} verpackt +@msgplural Packaged {n} file {note}|Packaged {n} files {note} {n} Datei verpackt {note}|{n} Dateien verpackt {note} +@msgplural Packaged {n} file|Packaged {n} files {n} Datei verpackt|{n} Dateien verpackt @plural Packaged {n} file|Packaged {n} files {n} Datei verpackt|{n} Dateien verpackt @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} Datei in {folder} verpackt|{n} Dateien in {folder} verpackt @plural Packaged {n} file {note}|Packaged {n} files {note} {n} Datei verpackt {note}|{n} Dateien verpackt {note} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 2ff75d2053..c62f82eaab 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2161,7 +2161,7 @@ axis Both Και τα δύο @msg PDF settings are not an object Οι ρυθμίσεις PDF δεν είναι αντικείμενο @msg PDF security settings are not an object Οι ρυθμίσεις ασφαλείας PDF δεν είναι αντικείμενο @msg PDF writer error: {0} Σφάλμα εγγραφής PDF: {0} -@msg Packaged {n} file(s) in {folder} {note} Συσκευάστηκαν {n} αρχεία στον φάκελο {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Συσκευάστηκε {n} αρχείο στον φάκελο {folder} ({note}|Συσκευάστηκαν {n} αρχεία στον φάκελο {folder} ({note} @msg Packaged {n} file(s){note} Συσκευάστηκαν {n} αρχεία{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Η προεπισκόπηση σε πρόγραμμα περιήγησης απαιτεί την εφαρμογή υπολογιστή (η έκδοση ιστού πραγματοποιεί λήψη αρχείων) @msg Release Guides: no guides Αποδέσμευση οδηγών: δεν υπάρχουν οδηγοί @@ -5545,9 +5545,9 @@ effect Points Σημεία Slope: Κλίση: axis X Axis Άξονας X axis Y Axis Άξονας Y -@msg Packaged {n} file(s) in {folder} Συσκευάστηκαν {n} αρχεία στον φάκελο {folder} -@msg Packaged {n} file(s) {note} Συσκευάστηκαν {n} αρχεία {note} -@msg Packaged {n} file(s) Συσκευάστηκαν {n} αρχεία +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Συσκευάστηκε {n} αρχείο στον φάκελο {folder}|Συσκευάστηκαν {n} αρχεία στον φάκελο {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Συσκευάστηκε {n} αρχείο {note}|Συσκευάστηκαν {n} αρχεία {note} +@msgplural Packaged {n} file|Packaged {n} files Συσκευάστηκε {n} αρχείο|Συσκευάστηκαν {n} αρχεία @plural Packaged {n} file|Packaged {n} files Συσκευάστηκε {n} αρχείο|Συσκευάστηκαν {n} αρχεία @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Συσκευάστηκε {n} αρχείο στον φάκελο {folder}|Συσκευάστηκαν {n} αρχεία στον φάκελο {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} Συσκευάστηκε {n} αρχείο {note}|Συσκευάστηκαν {n} αρχεία {note} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 693173a181..dd8fbcc8ce 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3928,7 +3928,7 @@ axis Both Ambos @msg PDF settings are not an object los ajustes de PDF no son un objeto @msg PDF security settings are not an object los ajustes de seguridad de PDF no son un objeto @msg PDF writer error: {0} error del escritor de PDF: {0} -@msg Packaged {n} file(s) in {folder} {note} Se empaquetaron {n} archivo(s) en {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Se empaquetó {n} archivo en {folder} ({note}|Se empaquetaron {n} archivos en {folder} ({note} @msg Packaged {n} file(s){note} Se empaquetaron {n} archivo(s){note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Previsualizar en el navegador requiere la aplicación de escritorio (la versión web descarga los archivos) @msg Release Guides: no guides Soltar guías: no hay guías @@ -5535,9 +5535,9 @@ mark-style Japanese Japonesas Slope: Pendiente: axis X Axis Eje X axis Y Axis Eje Y -@msg Packaged {n} file(s) in {folder} Se empaquetaron {n} archivo(s) en {folder} -@msg Packaged {n} file(s) {note} Se empaquetaron {n} archivo(s) {note} -@msg Packaged {n} file(s) Se empaquetaron {n} archivo(s) +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Se empaquetó {n} archivo en {folder}|Se empaquetaron {n} archivos en {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Se empaquetó {n} archivo {note}|Se empaquetaron {n} archivos {note} +@msgplural Packaged {n} file|Packaged {n} files Se empaquetó {n} archivo|Se empaquetaron {n} archivos @plural Packaged {n} file|Packaged {n} files Se empaquetó {n} archivo|Se empaquetaron {n} archivos @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Se empaquetó {n} archivo en {folder}|Se empaquetaron {n} archivos en {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} Se empaquetó {n} archivo {note}|Se empaquetaron {n} archivos {note} diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 2d86cc5f7f..242f01eb1b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4151,7 +4151,7 @@ imageTrace Outline Ääriviiva @msg PDF settings are not an object PDF-asetukset eivät ole objekti @msg PDF security settings are not an object PDF-suojausasetukset eivät ole objekti @msg PDF writer error: {0} PDF-kirjoittimen virhe: {0} -@msg Packaged {n} file(s) in {folder} {note} Paketoitiin {n} tiedosto(a) kansioon {folder} {note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Paketoitiin {n} tiedosto kansioon {folder} ({note}|Paketoitiin {n} tiedostoa kansioon {folder} ({note} @msg Packaged {n} file(s){note} Paketoitiin {n} tiedosto(a){note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Esikatselu selaimessa vaatii työpöytäsovelluksen (verkkoversio lataa tiedostot sen sijaan) @msg Release Guides: no guides Vapauta apuviivat: ei apuviivoja @@ -5624,9 +5624,9 @@ swatch Bright Violet Kirkas violetti Slope: Kaltevuus: axis X Axis X-akseli axis Y Axis Y-akseli -@msg Packaged {n} file(s) in {folder} Paketoitiin {n} tiedosto(a) kansioon {folder} -@msg Packaged {n} file(s) {note} Paketoitiin {n} tiedosto(a) {note} -@msg Packaged {n} file(s) Paketoitiin {n} tiedosto(a) +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Paketoitiin {n} tiedosto kansioon {folder}|Paketoitiin {n} tiedostoa kansioon {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Paketoitiin {n} tiedosto {note}|Paketoitiin {n} tiedostoa {note} +@msgplural Packaged {n} file|Packaged {n} files Paketoitiin {n} tiedosto|Paketoitiin {n} tiedostoa @plural Packaged {n} file|Packaged {n} files Paketoitiin {n} tiedosto|Paketoitiin {n} tiedostoa @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Paketoitiin {n} tiedosto kansioon {folder}|Paketoitiin {n} tiedostoa kansioon {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} Paketoitiin {n} tiedosto {note}|Paketoitiin {n} tiedostoa {note} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index a93869adf7..247848ee4e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3924,7 +3924,7 @@ axis Both Les deux @msg PDF settings are not an object Les paramètres PDF ne sont pas un objet @msg PDF security settings are not an object Les paramètres de sécurité PDF ne sont pas un objet @msg PDF writer error: {0} Erreur du générateur PDF : {0} -@msg Packaged {n} file(s) in {folder} {note} {n} fichier(s) assemblé(s) dans {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} {n} fichier assemblé dans {folder} ({note}|{n} fichiers assemblés dans {folder} ({note} @msg Packaged {n} file(s){note} {n} fichier(s) assemblé(s){note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Aperçu dans le navigateur nécessite l’application de bureau (la version web télécharge les fichiers à la place) @msg Release Guides: no guides Annuler les repères : aucun repère @@ -5591,9 +5591,9 @@ theme Appearance Apparence Slope: Pente : axis X Axis Axe X axis Y Axis Axe Y -@msg Packaged {n} file(s) in {folder} {n} fichier(s) assemblé(s) dans {folder} -@msg Packaged {n} file(s) {note} {n} fichier(s) assemblé(s) {note} -@msg Packaged {n} file(s) {n} fichier(s) assemblé(s) +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} fichier assemblé dans {folder}|{n} fichiers assemblés dans {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} {n} fichier assemblé {note}|{n} fichiers assemblés {note} +@msgplural Packaged {n} file|Packaged {n} files {n} fichier assemblé|{n} fichiers assemblés @plural Packaged {n} file|Packaged {n} files {n} fichier assemblé|{n} fichiers assemblés @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} fichier assemblé dans {folder}|{n} fichiers assemblés dans {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} {n} fichier assemblé {note}|{n} fichiers assemblés {note} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 74a25582c0..94c29d9006 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4955,7 +4955,7 @@ imageTrace Outline Körvonal @msg Opened with {_1} note(s): {_2} Megnyitva; megjegyzések: {_1}: {_2} @msg Opened {url} Megnyitva: {url} @msg Outline Stroke: no stroked paths selected Körvonal útvonallá alakítása: nincs kijelölt körvonalas útvonal -@msg Packaged {n} file(s) in {folder} {note} Becsomagolt fájlok: {n}, mappa: {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Becsomagolt fájlok: {n}, mappa: {folder} ({note} @msg Packaged {n} file(s){note} Becsomagolt fájlok: {n}{note} @msg page size {w} × {h} oldalméret: {w} × {h} @msg page {0} does not exist (the PDF has {1}) nincs ilyen oldal: {0} (a PDF oldalszáma: {1}) @@ -5579,9 +5579,9 @@ imageTrace Outline Körvonal Slope: Lejtés: axis X Axis X tengely axis Y Axis Y tengely -@msg Packaged {n} file(s) in {folder} Becsomagolt fájlok: {n}, mappa: {folder} -@msg Packaged {n} file(s) {note} Becsomagolt fájlok: {n} {note} -@msg Packaged {n} file(s) Becsomagolt fájlok: {n} +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Becsomagolt fájlok: {n}, mappa: {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Becsomagolt fájlok: {n} {note} +@msgplural Packaged {n} file|Packaged {n} files Becsomagolt fájlok: {n} @plural Packaged {n} file|Packaged {n} files Becsomagolt fájlok: {n} @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Becsomagolt fájlok: {n}, mappa: {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} Becsomagolt fájlok: {n} {note} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index f8bee41744..6b1167464b 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3953,7 +3953,7 @@ imageTrace Outline Kontur @msg PDF settings are not an object Pengaturan PDF bukan objek @msg PDF security settings are not an object Pengaturan keamanan PDF bukan objek @msg PDF writer error: {0} Kesalahan penulis PDF: {0} -@msg Packaged {n} file(s) in {folder} {note} Berhasil mengemas {n} file di {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Berhasil mengemas {n} file di {folder} ({note} @msg Packaged {n} file(s){note} Berhasil mengemas {n} file{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Pratinjau di Peramban memerlukan aplikasi desktop (versi web mengunduh file sebagai gantinya) @msg Release Guides: no guides Lepaskan panduan: tidak ada panduan @@ -5519,9 +5519,9 @@ swatch Bright Violet Violet cerah Slope: Kemiringan: axis X Axis Sumbu X axis Y Axis Sumbu Y -@msg Packaged {n} file(s) in {folder} Berhasil mengemas {n} file di {folder} -@msg Packaged {n} file(s) {note} Berhasil mengemas {n} file {note} -@msg Packaged {n} file(s) Berhasil mengemas {n} file +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Berhasil mengemas {n} file di {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Berhasil mengemas {n} file {note} +@msgplural Packaged {n} file|Packaged {n} files Berhasil mengemas {n} file @plural Packaged {n} file|Packaged {n} files Berhasil mengemas {n} file @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Berhasil mengemas {n} file di {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} Berhasil mengemas {n} file {note} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5fd0ed4b79..7ca999d56b 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3968,7 +3968,7 @@ axis Both Entrambi @msg PDF settings are not an object Le impostazioni PDF non sono un oggetto @msg PDF security settings are not an object Le impostazioni di sicurezza PDF non sono un oggetto @msg PDF writer error: {0} Errore del generatore PDF: {0} -@msg Packaged {n} file(s) in {folder} {note} Pacchetto creato con {n} file in {folder} {note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Pacchetto creato con {n} file in {folder} ({note} @msg Packaged {n} file(s){note} Pacchetto creato con {n} file{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Anteprima nel browser richiede l'app desktop (sul web i file vengono invece scaricati) @msg Release Guides: no guides Rilascia guide: nessuna guida @@ -5208,9 +5208,9 @@ lighting Light Luce Slope: Pendenza: axis X Axis Asse X axis Y Axis Asse Y -@msg Packaged {n} file(s) in {folder} Pacchetto creato con {n} file in {folder} -@msg Packaged {n} file(s) {note} Pacchetto creato con {n} file {note} -@msg Packaged {n} file(s) Pacchetto creato con {n} file +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Pacchetto creato con {n} file in {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Pacchetto creato con {n} file {note} +@msgplural Packaged {n} file|Packaged {n} files Pacchetto creato con {n} file @plural Packaged {n} file|Packaged {n} files Pacchetto creato con {n} file|Pacchetto creato con {n} file @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Pacchetto creato con {n} file in {folder}|Pacchetto creato con {n} file in {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} Pacchetto creato con {n} file {note}|Pacchetto creato con {n} file {note} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 57715d1363..cec459c4b1 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4459,7 +4459,7 @@ swatch Bright Violet ビビッドバイオレット @msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} 個のリンク画像がディスク上で変更されました: 「リンクを更新」で新しいバージョンを表示できます @msg Updated {_1} linked file(s) changed on disk ディスク上で変更された {_1} 個のリンクファイルを更新しました @msg pick a colour, gradient or pattern to save as a swatch スウォッチとして保存するカラー、グラデーション、またはパターンを選択してください -@msg Packaged {n} file(s) in {folder} {note} {n} 個のファイルを {folder} にパッケージしました{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} {n} 個のファイルを {folder} にパッケージしました({note} @msg Packaged {n} file(s){note} {n} 個のファイルをパッケージしました{note} @msg choose a location for the package パッケージの保存場所を選択してください @msg missing `folder` `folder` が指定されていません @@ -5274,9 +5274,9 @@ lighting Light ライト Slope: 勾配: axis X Axis X 軸 axis Y Axis Y 軸 -@msg Packaged {n} file(s) in {folder} {n} 個のファイルを {folder} にパッケージしました -@msg Packaged {n} file(s) {note} {n} 個のファイルをパッケージしました {note} -@msg Packaged {n} file(s) {n} 個のファイルをパッケージしました +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} 個のファイルを {folder} にパッケージしました +@msgplural Packaged {n} file {note}|Packaged {n} files {note} {n} 個のファイルをパッケージしました {note} +@msgplural Packaged {n} file|Packaged {n} files {n} 個のファイルをパッケージしました @plural Packaged {n} file|Packaged {n} files {n} 個のファイルをパッケージしました @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} 個のファイルを {folder} にパッケージしました @plural Packaged {n} file {note}|Packaged {n} files {note} {n} 個のファイルをパッケージしました {note} diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 423d50a0af..a8664eca33 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3723,7 +3723,7 @@ font-technology Variable ცვლადი @msg PDF settings are not an object PDF-ის პარამეტრები ობიექტი არ არის @msg PDF security settings are not an object PDF-ის უსაფრთხოების პარამეტრები ობიექტი არ არის @msg PDF writer error: {0} PDF-ის ჩამწერის შეცდომა: {0} -@msg Packaged {n} file(s) in {folder} {note} შეფუთულია ფაილი ({n}) საქაღალდეში {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} შეფუთულია ფაილი ({n}) საქაღალდეში {folder} ({note} @msg Packaged {n} file(s){note} შეფუთულია ფაილი ({n}){note} @msg Preview in Browser needs the desktop app (the web downloads files instead) ბრაუზერში წინასწარ ნახვას დესკტოპის აპი სჭირდება (ვებში ფაილები ჩამოიტვირთება) @msg Release Guides: no guides დამხმარე ხაზების მოხსნა: დამხმარე ხაზები არ არის @@ -5505,9 +5505,9 @@ imageTrace Outline კონტური Slope: დახრა: axis X Axis X ღერძი axis Y Axis Y ღერძი -@msg Packaged {n} file(s) in {folder} შეფუთულია ფაილი ({n}) საქაღალდეში {folder} -@msg Packaged {n} file(s) {note} შეფუთულია ფაილი ({n}) {note} -@msg Packaged {n} file(s) შეფუთულია ფაილი ({n}) +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} შეფუთულია ფაილი ({n}) საქაღალდეში {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} შეფუთულია ფაილი ({n}) {note} +@msgplural Packaged {n} file|Packaged {n} files შეფუთულია ფაილი ({n}) @plural Packaged {n} file|Packaged {n} files შეფუთულია ფაილი ({n}) @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} შეფუთულია ფაილი ({n}) საქაღალდეში {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} შეფუთულია ფაილი ({n}) {note} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 9be4625826..0b47ed20a0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4387,7 +4387,7 @@ theme Appearance 외관 @msg {_1} linked image(s) changed on disk: Update Links shows the new versions 링크된 이미지 {_1}개가 디스크에서 바뀌었습니다: 링크 업데이트를 하면 새 버전이 표시됩니다 @msg Updated {_1} linked file(s) changed on disk 디스크에서 바뀐 링크된 파일 {_1}개를 업데이트했습니다 @msg pick a colour, gradient or pattern to save as a swatch 견본으로 저장할 색상, 그레이디언트 또는 패턴을 선택하세요 -@msg Packaged {n} file(s) in {folder} {note} {folder}에 파일 {n}개를 패키지했습니다{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} {folder}에 파일 {n}개를 패키지했습니다({note} @msg Packaged {n} file(s){note} 파일 {n}개를 패키지했습니다{note} @msg choose a location for the package 패키지 위치를 선택하세요 @msg missing `folder` `folder`가 없습니다 @@ -5171,9 +5171,9 @@ lighting Light 광원 Slope: 기울기: axis X Axis X축 axis Y Axis Y축 -@msg Packaged {n} file(s) in {folder} {folder}에 파일 {n}개를 패키지했습니다 -@msg Packaged {n} file(s) {note} 파일 {n}개를 패키지했습니다 {note} -@msg Packaged {n} file(s) 파일 {n}개를 패키지했습니다 +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} {folder}에 파일 {n}개를 패키지했습니다 +@msgplural Packaged {n} file {note}|Packaged {n} files {note} 파일 {n}개를 패키지했습니다 {note} +@msgplural Packaged {n} file|Packaged {n} files 파일 {n}개를 패키지했습니다 @plural Packaged {n} file|Packaged {n} files 파일 {n}개를 패키지했습니다 @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {folder}에 파일 {n}개를 패키지했습니다 @plural Packaged {n} file {note}|Packaged {n} files {note} 파일 {n}개를 패키지했습니다 {note} diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 1a12b403ef..c8df690252 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3967,7 +3967,7 @@ imageTrace Outline Contour @msg PDF settings are not an object PDF-instellingen zijn geen object @msg PDF security settings are not an object PDF-beveiligingsinstellingen zijn geen object @msg PDF writer error: {0} PDF-schrijffout: {0} -@msg Packaged {n} file(s) in {folder} {note} {n} bestand(en) verpakt in {folder} {note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} {n} bestand verpakt in {folder} ({note}|{n} bestanden verpakt in {folder} ({note} @msg Packaged {n} file(s){note} {n} bestand(en) verpakt{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Voorvertoning in browser heeft de desktop-app nodig (het web downloadt in plaats daarvan bestanden) @msg Release Guides: no guides Hulplijnen vrijgeven: geen hulplijnen @@ -5563,9 +5563,9 @@ swatch Bright Violet Felviolet Slope: Helling: axis X Axis X-as axis Y Axis Y-as -@msg Packaged {n} file(s) in {folder} {n} bestand(en) verpakt in {folder} -@msg Packaged {n} file(s) {note} {n} bestand(en) verpakt {note} -@msg Packaged {n} file(s) {n} bestand(en) verpakt +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} bestand verpakt in {folder}|{n} bestanden verpakt in {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} {n} bestand verpakt {note}|{n} bestanden verpakt {note} +@msgplural Packaged {n} file|Packaged {n} files {n} bestand verpakt|{n} bestanden verpakt @plural Packaged {n} file|Packaged {n} files {n} bestand verpakt|{n} bestanden verpakt @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} bestand verpakt in {folder}|{n} bestanden verpakt in {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} {n} bestand verpakt {note}|{n} bestanden verpakt {note} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 1113eddd45..da672c7d7c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4060,7 +4060,7 @@ imageTrace Outline Kontur @msg PDF settings are not an object Ustawienia PDF nie są obiektem @msg PDF security settings are not an object Ustawienia zabezpieczeń PDF nie są obiektem @msg PDF writer error: {0} Błąd zapisu PDF: {0} -@msg Packaged {n} file(s) in {folder} {note} Spakowane pliki: {n} w {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Spakowane pliki: {n} w {folder} ({note} @msg Packaged {n} file(s){note} Spakowane pliki: {n}{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Podgląd w przeglądarce wymaga aplikacji desktopowej (wersja webowa zamiast tego pobiera pliki) @msg Release Guides: no guides Uwolnij linie pomocnicze: brak linii pomocniczych @@ -5447,9 +5447,9 @@ mark-style Japanese Japońskie Slope: Nachylenie: axis X Axis Oś X axis Y Axis Oś Y -@msg Packaged {n} file(s) in {folder} Spakowane pliki: {n} w {folder} -@msg Packaged {n} file(s) {note} Spakowane pliki: {n} {note} -@msg Packaged {n} file(s) Spakowane pliki: {n} +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Spakowane pliki: {n} w {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Spakowane pliki: {n} {note} +@msgplural Packaged {n} file|Packaged {n} files Spakowane pliki: {n} @plural Packaged {n} file|Packaged {n} files Spakowane pliki: {n}|Spakowane pliki: {n}|Spakowane pliki: {n} @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Spakowane pliki: {n} w {folder}|Spakowane pliki: {n} w {folder}|Spakowane pliki: {n} w {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} Spakowane pliki: {n} {note}|Spakowane pliki: {n} {note}|Spakowane pliki: {n} {note} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 129533e078..7a2e021713 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3514,7 +3514,7 @@ axis Both Ambos @msg PDF settings are not an object as configurações de PDF não são um objeto @msg PDF security settings are not an object as configurações de segurança de PDF não são um objeto @msg PDF writer error: {0} Erro do gravador de PDF: {0} -@msg Packaged {n} file(s) in {folder} {note} {n} arquivo(s) empacotado(s) em {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} {n} arquivo empacotado em {folder} ({note}|{n} arquivos empacotados em {folder} ({note} @msg Packaged {n} file(s){note} {n} arquivo(s) empacotado(s){note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Visualizar no navegador exige o aplicativo para desktop (na web, os arquivos são baixados) @msg Release Guides: no guides Liberar guias: não há guias @@ -5510,9 +5510,9 @@ mark-style Japanese Japonesas Slope: Inclinação: axis X Axis Eixo X axis Y Axis Eixo Y -@msg Packaged {n} file(s) in {folder} {n} arquivo(s) empacotado(s) em {folder} -@msg Packaged {n} file(s) {note} {n} arquivo(s) empacotado(s) {note} -@msg Packaged {n} file(s) {n} arquivo(s) empacotado(s) +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} arquivo empacotado em {folder}|{n} arquivos empacotados em {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} {n} arquivo empacotado {note}|{n} arquivos empacotados {note} +@msgplural Packaged {n} file|Packaged {n} files {n} arquivo empacotado|{n} arquivos empacotados @plural Packaged {n} file|Packaged {n} files {n} arquivo empacotado|{n} arquivos empacotados @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} arquivo empacotado em {folder}|{n} arquivos empacotados em {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} {n} arquivo empacotado {note}|{n} arquivos empacotados {note} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a735dbb079..be1152ca95 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3964,7 +3964,7 @@ axis Both Оба @msg PDF settings are not an object параметры PDF не являются объектом @msg PDF security settings are not an object параметры безопасности PDF не являются объектом @msg PDF writer error: {0} ошибка записи PDF: {0} -@msg Packaged {n} file(s) in {folder} {note} Упаковано файлов: {n} в {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Упаковано файлов: {n} в {folder} ({note} @msg Packaged {n} file(s){note} Упаковано файлов: {n}{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Просмотр в браузере требует настольного приложения (web-версия скачивает файлы) @msg Release Guides: no guides Освобождение направляющих: нет направляющих @@ -5204,9 +5204,9 @@ lighting Light Свет Slope: Уклон: axis X Axis Ось X axis Y Axis Ось Y -@msg Packaged {n} file(s) in {folder} Упаковано файлов: {n} в {folder} -@msg Packaged {n} file(s) {note} Упаковано файлов: {n} {note} -@msg Packaged {n} file(s) Упаковано файлов: {n} +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Упаковано файлов: {n} в {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Упаковано файлов: {n} {note} +@msgplural Packaged {n} file|Packaged {n} files Упаковано файлов: {n} @plural Packaged {n} file|Packaged {n} files Упаковано файлов: {n}|Упаковано файлов: {n}|Упаковано файлов: {n} @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Упаковано файлов: {n} в {folder}|Упаковано файлов: {n} в {folder}|Упаковано файлов: {n} в {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} Упаковано файлов: {n} {note}|Упаковано файлов: {n} {note}|Упаковано файлов: {n} {note} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 20d412a5ec..f29ac25925 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3845,7 +3845,7 @@ axis Both Båda @msg PDF settings are not an object PDF-inställningarna är inte ett objekt @msg PDF security settings are not an object PDF-säkerhetsinställningarna är inte ett objekt @msg PDF writer error: {0} fel i PDF-skrivaren: {0} -@msg Packaged {n} file(s) in {folder} {note} Paketerade {n} fil(er) i {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Paketerade {n} fil i {folder} ({note}|Paketerade {n} filer i {folder} ({note} @msg Packaged {n} file(s){note} Paketerade {n} fil(er){note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Förhandsgranska i webbläsare kräver skrivbordsappen (webbversionen hämtar filer i stället) @msg Release Guides: no guides Släpp stödlinjer: inga stödlinjer @@ -5617,9 +5617,9 @@ font-script Japanese Japanska Slope: Lutning: axis X Axis X-axel axis Y Axis Y-axel -@msg Packaged {n} file(s) in {folder} Paketerade {n} fil(er) i {folder} -@msg Packaged {n} file(s) {note} Paketerade {n} fil(er) {note} -@msg Packaged {n} file(s) Paketerade {n} fil(er) +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Paketerade {n} fil i {folder}|Paketerade {n} filer i {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Paketerade {n} fil {note}|Paketerade {n} filer {note} +@msgplural Packaged {n} file|Packaged {n} files Paketerade {n} fil|Paketerade {n} filer @plural Packaged {n} file|Packaged {n} files Paketerade {n} fil|Paketerade {n} filer @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Paketerade {n} fil i {folder}|Paketerade {n} filer i {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} Paketerade {n} fil {note}|Paketerade {n} filer {note} diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 41456bf052..f1d4bc04f5 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -271,7 +271,7 @@ fn bundled_catalogs_are_consistent() { let mut seen = std::collections::HashSet::new(); for (ctx, src, tr) in &entries { assert!(seen.insert((ctx.clone(), src.clone())), "{}: duplicate {ctx:?} {src:?}", l.code); - if ctx == "@plural" { + if ctx == "@plural" || ctx == "@msgplural" { let one_other: Vec<&str> = src.split('|').collect(); assert_eq!(one_other.len(), 2, "{}: plural source must be `one|other`: {src:?}", l.code); for form in tr.split('|') { @@ -1500,6 +1500,23 @@ fn package_status_message_templates_parse() { assert!(Catalog::parse("@msg\tPackaged {n} file(s) in {folder}{note}\tbad\n").message("Packaged 1 file(s) in /a b").is_none()); } +/// A `@msgplural` row translates both English forms of a message with a count, and the count +/// picks the language's form. +#[test] +fn messages_with_a_count_take_the_plural_form() { + let c = Catalog::parse("@msgplural\tSaved {n} file|Saved {n} files\tone {n}|few {n}|many {n}\n"); + for s in ["Saved 1 file", "Saved 4 files"] { + let (forms, caps) = c.message_forms(s).unwrap(); + assert_eq!(forms, ["one {n}", "few {n}", "many {n}"], "{s}"); + assert_eq!(caps.len(), 1, "{s}"); + } + assert!(c.message_forms("Saved 1 files!").is_none()); + let cs = cs(); + assert_eq!(message(cs, "Packaged 1 file"), "Zabalen 1 soubor"); + assert_eq!(message(cs, "Packaged 4 files"), "Zabaleny 4 soubory"); + assert_eq!(message(cs, "Packaged 21 files"), "Zabaleno 21 souborů"); +} + /// The scan reads the message of an error made with one of the engine's [`ERROR_HELPERS`] or with /// an error enum's variant, `EngineError::Disabled`'s reason included: a literal or a `format!` /// string, on the call's line or wrapped over several lines, in the same template form as the diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ce569f47b5..68d84f44eb 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3735,7 +3735,7 @@ axis Both Her İkisi @msg PDF settings are not an object PDF ayarları bir nesne değildir @msg PDF security settings are not an object PDF güvenlik ayarları bir nesne değildir @msg PDF writer error: {0} PDF yazıcı hatası: {0} -@msg Packaged {n} file(s) in {folder} {note} {folder}{note} biçiminde paketlenmiş {n} dosyası/dosyaları +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} {n} dosya {folder} klasörüne paketlendi ({note} @msg Packaged {n} file(s){note} Paketlenmiş {n} dosyası/dosyaları{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Tarayıcıdaki önizleme için masaüstü uygulaması gerekir (bunun yerine web, dosyaları indirir) @msg Release Guides: no guides Sürüm Kılavuzları: kılavuz yok @@ -5543,9 +5543,9 @@ theme Appearance Görünüm axis X Axis X ekseni axis Y Axis Y ekseni -@msg Packaged {n} file(s) in {folder} {folder} biçiminde paketlenmiş {n} dosyası/dosyaları -@msg Packaged {n} file(s) {note} Paketlenmiş {n} dosyası/dosyaları {note} -@msg Packaged {n} file(s) Paketlenmiş {n} dosyası/dosyaları +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} dosya {folder} klasörüne paketlendi +@msgplural Packaged {n} file {note}|Packaged {n} files {note} {n} dosya paketlendi {note} +@msgplural Packaged {n} file|Packaged {n} files {n} dosya paketlendi # Artwork drag between document tabs. Drop Artwork Çizimi Bırak @msg {key} must be [x, y] with finite coordinates {key}, sonlu koordinatlı [x, y] olmalı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dc4d1c4775..133d91f98f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3952,7 +3952,7 @@ axis Both Обидві @msg PDF settings are not an object Параметри PDF не є об’єктом @msg PDF security settings are not an object Параметри безпеки PDF не є об’єктом @msg PDF writer error: {0} Помилка запису PDF: {0} -@msg Packaged {n} file(s) in {folder} {note} Упаковано файли: {n} {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Упаковано файли: {n} {folder} ({note} @msg Packaged {n} file(s){note} Упаковано файли: {n}{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Перегляд у браузері вимагає настільної програми (web-версія завантажує файли) @msg Release Guides: no guides Звільнення напрямних: немає напрямних @@ -5188,9 +5188,9 @@ lighting Light Світло Slope: Ухил: axis X Axis Вісь X axis Y Axis Вісь Y -@msg Packaged {n} file(s) in {folder} Упаковано файли: {n} {folder} -@msg Packaged {n} file(s) {note} Упаковано файли: {n} {note} -@msg Packaged {n} file(s) Упаковано файли: {n} +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Упаковано файли: {n} {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Упаковано файли: {n} {note} +@msgplural Packaged {n} file|Packaged {n} files Упаковано файли: {n} @plural Packaged {n} file|Packaged {n} files Упаковано файли: {n}|Упаковано файли: {n}|Упаковано файли: {n} @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Упаковано файли: {n} {folder}|Упаковано файли: {n} {folder}|Упаковано файли: {n} {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} Упаковано файли: {n} {note}|Упаковано файли: {n} {note}|Упаковано файли: {n} {note} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 90cc10d9a5..2bd707c34f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4606,7 +4606,7 @@ theme Appearance Giao diện @msg Opened with {_1} note(s): {_2} Đã mở với {_1} ghi chú: {_2} @msg Opened {url} Đã mở {url} @msg Outline Stroke: no stroked paths selected Đường bao nét: chưa chọn đường dẫn có nét -@msg Packaged {n} file(s) in {folder} {note} Đã đóng gói {n} tệp trong {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Đã đóng gói {n} tệp trong {folder} ({note} @msg Packaged {n} file(s){note} Đã đóng gói {n} tệp{note} @msg page size {w} × {h} kích thước trang {w} × {h} @msg page {0} does not exist (the PDF has {1}) trang {0} không tồn tại (PDF có {1} trang) @@ -5190,9 +5190,9 @@ theme Appearance Giao diện Slope: Độ dốc: axis X Axis Trục X axis Y Axis Trục Y -@msg Packaged {n} file(s) in {folder} Đã đóng gói {n} tệp trong {folder} -@msg Packaged {n} file(s) {note} Đã đóng gói {n} tệp {note} -@msg Packaged {n} file(s) Đã đóng gói {n} tệp +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Đã đóng gói {n} tệp trong {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Đã đóng gói {n} tệp {note} +@msgplural Packaged {n} file|Packaged {n} files Đã đóng gói {n} tệp @plural Packaged {n} file|Packaged {n} files Đã đóng gói {n} tệp @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Đã đóng gói {n} tệp trong {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} Đã đóng gói {n} tệp {note} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 7c930a444f..631cd8a7c3 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4179,7 +4179,7 @@ imageTrace Outline 轮廓 @msg {undecoded} image(s) couldn't be decoded and show as crossed boxes 无法解码 {undecoded} 张图像:它们显示为打叉的方框 @msg {_1} linked image(s) changed on disk: Update Links shows the new versions 有 {_1} 个链接图像已在磁盘上更改:“更新链接”可显示新版本 @msg pick a colour, gradient or pattern to save as a swatch 请选取要保存为色板的颜色、渐变或图案 -@msg Packaged {n} file(s) in {folder} {note} 已将 {n} 个文件打包到 {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} 已将 {n} 个文件打包到 {folder}({note} @msg Packaged {n} file(s){note} 已打包 {n} 个文件{note} @msg choose a location for the package 请为打包选择位置 @msg missing `folder` 缺少 `folder` @@ -5432,9 +5432,9 @@ lighting Light 光源 Slope: 斜率: axis X Axis X 轴 axis Y Axis Y 轴 -@msg Packaged {n} file(s) in {folder} 已将 {n} 个文件打包到 {folder} -@msg Packaged {n} file(s) {note} 已打包 {n} 个文件 {note} -@msg Packaged {n} file(s) 已打包 {n} 个文件 +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} 已将 {n} 个文件打包到 {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} 已打包 {n} 个文件 {note} +@msgplural Packaged {n} file|Packaged {n} files 已打包 {n} 个文件 @plural Packaged {n} file|Packaged {n} files 已打包 {n} 个文件 @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} 已将 {n} 个文件打包到 {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} 已打包 {n} 个文件 {note} diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b3cfda873a..df2948e472 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2114,7 +2114,7 @@ file-filter Templates 範本 @msg {undecoded} image(s) couldn't be decoded and show as crossed boxes 無法解碼 {undecoded} 張影像:它們顯示為打叉的方框 @msg {_1} linked image(s) changed on disk: Update Links shows the new versions 有 {_1} 個連結影像已在磁碟上變更:「更新連結」可顯示新版本 @msg pick a colour, gradient or pattern to save as a swatch 請挑選要儲存為色票的顏色、漸層或圖樣 -@msg Packaged {n} file(s) in {folder} {note} 已將 {n} 個檔案封裝到 {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} 已將 {n} 個檔案封裝到 {folder}({note} @msg Packaged {n} file(s){note} 已封裝 {n} 個檔案{note} @msg choose a location for the package 請選擇封裝的位置 @msg missing `folder` 未提供 `folder` @@ -5227,9 +5227,9 @@ lighting Light 光源 Slope: 斜率: axis X Axis X 軸 axis Y Axis Y 軸 -@msg Packaged {n} file(s) in {folder} 已將 {n} 個檔案封裝到 {folder} -@msg Packaged {n} file(s) {note} 已封裝 {n} 個檔案 {note} -@msg Packaged {n} file(s) 已封裝 {n} 個檔案 +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} 已將 {n} 個檔案封裝到 {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} 已封裝 {n} 個檔案 {note} +@msgplural Packaged {n} file|Packaged {n} files 已封裝 {n} 個檔案 @plural Packaged {n} file|Packaged {n} files 已封裝 {n} 個檔案 @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} 已將 {n} 個檔案封裝到 {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} 已封裝 {n} 個檔案 {note} From 6f8e0294ff1b1212beaa11cb9feaa307d663fe36 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 02:48:46 -0700 Subject: [PATCH 150/260] i18n: a package status with a note names the folder last, so a folder name with parentheses keeps it whole after a language switch A package status with a note, such as "Packaged 1 file in /out/card (draft) (fonts not copied: Mono)", was translated after a language switch as if the folder ended at its first " (", so German showed "1 Datei in /out/card verpackt (draft) ...". The English status now puts the note before the folder ("Packaged 1 file (fonts not copied: Mono) in /out/card (draft)"), and each catalog's @msgplural row for it reads the folder as the rest of the line after ") in ". --- crates/ui-egui/src/dialogs/package.rs | 11 ++++--- crates/ui-egui/src/dialogs/tests_package.rs | 34 +++++++++++++++------ crates/ui-egui/src/i18n/bg.tsv | 4 +-- crates/ui-egui/src/i18n/bs.tsv | 4 +-- crates/ui-egui/src/i18n/ca.tsv | 4 +-- crates/ui-egui/src/i18n/cs.tsv | 4 +-- crates/ui-egui/src/i18n/da.tsv | 4 +-- crates/ui-egui/src/i18n/de.tsv | 4 +-- crates/ui-egui/src/i18n/el.tsv | 4 +-- crates/ui-egui/src/i18n/es.tsv | 4 +-- crates/ui-egui/src/i18n/fi.tsv | 4 +-- crates/ui-egui/src/i18n/fr.tsv | 4 +-- crates/ui-egui/src/i18n/hu.tsv | 4 +-- crates/ui-egui/src/i18n/id.tsv | 4 +-- crates/ui-egui/src/i18n/it.tsv | 4 +-- crates/ui-egui/src/i18n/ja.tsv | 4 +-- crates/ui-egui/src/i18n/ka.tsv | 4 +-- crates/ui-egui/src/i18n/ko.tsv | 4 +-- crates/ui-egui/src/i18n/nl.tsv | 4 +-- crates/ui-egui/src/i18n/pl.tsv | 4 +-- crates/ui-egui/src/i18n/pt-br.tsv | 4 +-- crates/ui-egui/src/i18n/ru.tsv | 4 +-- crates/ui-egui/src/i18n/sv.tsv | 4 +-- crates/ui-egui/src/i18n/tr.tsv | 4 +-- crates/ui-egui/src/i18n/uk.tsv | 4 +-- crates/ui-egui/src/i18n/vi.tsv | 4 +-- crates/ui-egui/src/i18n/zh-hans.tsv | 4 +-- crates/ui-egui/src/i18n/zh-hant.tsv | 4 +-- 28 files changed, 82 insertions(+), 67 deletions(-) diff --git a/crates/ui-egui/src/dialogs/package.rs b/crates/ui-egui/src/dialogs/package.rs index 5b49be69eb..2cc994be40 100644 --- a/crates/ui-egui/src/dialogs/package.rs +++ b/crates/ui-egui/src/dialogs/package.rs @@ -183,20 +183,21 @@ fn packaged(app: &mut VectorcraftApp, r: Result<Value, String>, web: bool, later } /// The status bar's line for a package of `n` files written to `folder` (`None`: the web's -/// download), followed by `note` from [`package_status_note`] when it isn't empty. Each catalog -/// also has `@msgplural` rows for the English line, shown after a language switch; they find the note -/// after the folder by its opening `(`, so a folder name with spaces stays whole. +/// download), with `note` from [`package_status_note`] when it isn't empty. With a note and a +/// folder, the note comes before the folder and the folder ends the line. Each catalog also has +/// `@msgplural` rows for the English line, shown after a language switch; the folder takes the rest +/// of the line after `) in `, so a folder name with spaces or parentheses stays whole. pub(super) fn package_status(n: u64, folder: Option<&str>, note: &str) -> String { let (one, other) = match (folder.is_some(), note.is_empty()) { (false, true) => ("Packaged {n} file", "Packaged {n} files"), (false, false) => ("Packaged {n} file {note}", "Packaged {n} files {note}"), (true, true) => ("Packaged {n} file in {folder}", "Packaged {n} files in {folder}"), - (true, false) => ("Packaged {n} file in {folder} {note}", "Packaged {n} files in {folder} {note}"), + (true, false) => ("Packaged {n} file {note} in {folder}", "Packaged {n} files {note} in {folder}"), }; crate::i18n::fmt(&crate::i18n::tn(n, one, other), &[("folder", folder.unwrap_or_default()), ("note", note)]) } -/// Parenthetical notes after the folder path in a package status (`(2 linked files not found)` …), +/// Parenthetical notes in a package status (`(2 linked files not found)` …), /// joined with spaces and without a leading space (#3494). pub(super) fn package_status_note(missing: usize, fonts: &str) -> String { let mut parts = Vec::new(); diff --git a/crates/ui-egui/src/dialogs/tests_package.rs b/crates/ui-egui/src/dialogs/tests_package.rs index 91d95d922a..816c6641d3 100644 --- a/crates/ui-egui/src/dialogs/tests_package.rs +++ b/crates/ui-egui/src/dialogs/tests_package.rs @@ -304,29 +304,43 @@ fn the_missing_links_note_uses_each_count_form() { /// A package status written in English, for one file or several, with or without a folder and a /// note, is translated by every catalog when the status bar shows it after a language switch, in -/// the form the language's plural rule picks for the count, and a folder whose name has a space -/// keeps its whole name. +/// the form the language's plural rule picks for the count, and a folder whose name has a space or +/// parentheses keeps its whole name, next to one note or two. #[test] fn an_english_package_status_is_translated_after_a_language_switch() { use crate::i18n::{Lang, message}; + let folders = [None, Some("/out/card Folder"), Some("/out/card (draft) v2")]; + let notes = ["", "(fonts not copied: Mono)", "(1 linked file not found) (fonts not copied: Mono)"]; let mut statuses = vec![]; for n in [1, 3] { - for folder in [None, Some("/out/card Folder")] { - for note in ["", "(fonts not copied: Mono)"] { - statuses.push(package::package_status(n, folder, note)); + for folder in folders { + for note in notes { + statuses.push((package::package_status(n, folder, note), folder, note)); } } } - assert!(statuses.contains(&"Packaged 1 file in /out/card Folder".to_string()), "{statuses:?}"); - assert!(statuses.contains(&"Packaged 3 files".to_string()), "{statuses:?}"); + let english: Vec<&str> = statuses.iter().map(|(s, ..)| s.as_str()).collect(); + assert!(english.contains(&"Packaged 1 file in /out/card Folder"), "{english:?}"); + assert!(english.contains(&"Packaged 1 file (fonts not copied: Mono) in /out/card (draft) v2"), "{english:?}"); + assert!(english.contains(&"Packaged 3 files"), "{english:?}"); for lang in Lang::all().filter(|l| l.code() != "en") { - for s in &statuses { + for (s, folder, note) in &statuses { let shown = message(lang, s); assert!(!shown.starts_with("Packaged"), "{}: {shown}", lang.code()); - // A space in the folder's name stays in the path, with or without a note. - assert_eq!(s.contains("/out/card Folder"), shown.contains("/out/card Folder"), "{}: {shown}", lang.code()); + // The folder stays whole in the translated line, and the note's font is still named. + assert!(folder.is_none_or(|f| shown.contains(f)), "{}: {shown}", lang.code()); + assert_eq!(note.contains("Mono"), shown.contains("Mono"), "{}: {shown}", lang.code()); } } + let de = Lang::from_code("de").unwrap(); + assert_eq!( + message(de, &package::package_status(1, Some("/out/card (draft)"), "(fonts not copied: Mono)")), + "1 Datei in /out/card (draft) verpackt (fonts not copied: Mono)" + ); + assert_eq!( + message(de, &package::package_status(3, Some("/out/card (draft)"), "(1 linked file not found) (fonts not copied: Mono)")), + "3 Dateien in /out/card (draft) verpackt (1 linked file not found) (fonts not copied: Mono)" + ); let cs = Lang::from_code("cs").unwrap(); assert_eq!(message(cs, "Packaged 1 file in /out"), "Zabalen 1 soubor do /out"); assert_eq!(message(cs, "Packaged 3 files in /out"), "Zabaleny 3 soubory do /out"); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 0afca3ee6d..83697b7f32 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2217,7 +2217,7 @@ font-technology Variable Променливи Package Пакет Package collects a saved document with its linked files and fonts. Пакетът събира запазен документ заедно с неговите свързани файлове и шрифтове. Package created Пакетът е създаден -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Пакетиран е {n} файл в {folder} {note}|Пакетирани са {n} файла в {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} Пакетиран е {n} файл в {folder} {note}|Пакетирани са {n} файла в {folder} {note} Packaged {n} file(s){note} Пакетирани са {n} файла{note} Package… Пакет… Page Страница @@ -3833,7 +3833,7 @@ axis Both И двете @msg PDF settings are not an object Настройките за PDF не са обект @msg PDF security settings are not an object Настройките за сигурност на PDF не са обект @msg PDF writer error: {0} Грешка на PDF записа: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Пакетиран е {n} файл в {folder} ({note}|Пакетирани са {n} файла в {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Пакетиран е {n} файл в {folder} ({note})|Пакетирани са {n} файла в {folder} ({note}) @msg Packaged {n} file(s){note} Пакетирани са {n} файла{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Прегледът в браузър изисква настолното приложение (уеб версията изтегля файловете вместо това) @msg Release Guides: no guides Освобождаване на водачи: няма водачи diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9ce6565b97..3a737414db 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2429,7 +2429,7 @@ lighting Light Svjetlo Fonts whose licence doesn't allow embedding are not copied. Fontovi čija licenca ne dozvoljava ugrađivanje ne kopiraju se. Package collects a saved document with its linked files and fonts. Paket prikuplja sačuvani dokument s njegovim povezanim datotekama i fontovima. Package created Paket je kreiran -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Upakovano datoteka u {folder}: {n} {note}|Upakovano datoteka u {folder}: {n} {note}|Upakovano datoteka u {folder}: {n} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} Upakovano datoteka u {folder}: {n} {note}|Upakovano datoteka u {folder}: {n} {note}|Upakovano datoteka u {folder}: {n} {note} Packaged {n} file(s){note} Upakovano datoteka: {n}{note} Relink Linked Files to the Document Ponovo poveži povezane datoteke s dokumentom Save the document first? Prvo sačuvati dokument? @@ -4199,7 +4199,7 @@ imageTrace Outline Obris @msg PDF settings are not an object PDF postavke nisu objekat @msg PDF security settings are not an object PDF sigurnosne postavke nisu objekat @msg PDF writer error: {0} greška PDF zapisivača: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Upakovano datoteka u {folder}: {n} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Upakovano datoteka u {folder}: {n} ({note}) @msg Packaged {n} file(s){note} Upakovano datoteka: {n}{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Pregledaj u pregledniku zahtijeva desktop aplikaciju (web umjesto toga preuzima datoteke) @msg Release Guides: no guides Oslobodi vodilice: nema vodilica diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f6e37996d2..c04ca4698a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2814,7 +2814,7 @@ Package created Empaquetatge creat @plural Packaged {n} file|Packaged {n} files S’ha empaquetat {n} fitxer|S’han empaquetat {n} fitxers @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} S’ha empaquetat {n} fitxer a {folder}|S’han empaquetat {n} fitxers a {folder} -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} S’ha empaquetat {n} fitxer a {folder} {note}|S’han empaquetat {n} fitxers a {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} S’ha empaquetat {n} fitxer a {folder} {note}|S’han empaquetat {n} fitxers a {folder} {note} @plural Packaged {n} file {note}|Packaged {n} files {note} S’ha empaquetat {n} fitxer {note}|S’han empaquetat {n} fitxers {note} Packaged {n} file(s){note} S’han empaquetat {n} fitxers{note} Package… Empaqueta… @@ -5260,7 +5260,7 @@ @msg Outline Stroke: no stroked paths selected Contorneja el traç: no hi ha cap traçat amb traç seleccionat @msgplural Packaged {n} file|Packaged {n} files S’ha empaquetat {n} fitxer|S’han empaquetat {n} fitxers @msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} S’ha empaquetat {n} fitxer a {folder}|S’han empaquetat {n} fitxers a {folder} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} S’ha empaquetat {n} fitxer a {folder} ({note}|S’han empaquetat {n} fitxers a {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} S’ha empaquetat {n} fitxer a {folder} ({note})|S’han empaquetat {n} fitxers a {folder} ({note}) @msgplural Packaged {n} file {note}|Packaged {n} files {note} S’ha empaquetat {n} fitxer {note}|S’han empaquetat {n} fitxers {note} @msg Packaged {n} file(s){note} Empaquetats {n} fitxer(s){note} @msg Packaging {_1} Empaquetant {_1} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 40e788750e..558384bb23 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2456,7 +2456,7 @@ lighting Light Světlo Fonts whose licence doesn't allow embedding are not copied. Písma, jejichž licence nepovoluje vkládání, se nekopírují. Package collects a saved document with its linked files and fonts. Sbalení shromáždí uložený dokument s jeho propojenými soubory a písmy. Package created Balíček vytvořen -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Zabalen {n} soubor do {folder} {note}|Zabaleny {n} soubory do {folder} {note}|Zabaleno {n} souborů do {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} Zabalen {n} soubor do {folder} {note}|Zabaleny {n} soubory do {folder} {note}|Zabaleno {n} souborů do {folder} {note} Packaged {n} file(s){note} Zabaleno souborů: {n}{note} Relink Linked Files to the Document Znovu propojit propojené soubory s dokumentem Save the document first? Nejprve uložit dokument? @@ -4236,7 +4236,7 @@ imageTrace Outline Obrys @msg PDF settings are not an object nastavení PDF nejsou objekt @msg PDF security settings are not an object nastavení zabezpečení PDF nejsou objekt @msg PDF writer error: {0} chyba zápisu PDF: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Zabalen {n} soubor do {folder} ({note}|Zabaleny {n} soubory do {folder} ({note}|Zabaleno {n} souborů do {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Zabalen {n} soubor do {folder} ({note})|Zabaleny {n} soubory do {folder} ({note})|Zabaleno {n} souborů do {folder} ({note}) @msg Packaged {n} file(s){note} Zabaleno souborů: {n}{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Náhled v prohlížeči vyžaduje desktopovou aplikaci (webová verze místo toho stahuje soubory) @msg Release Guides: no guides Uvolnit vodítka: žádná vodítka diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 25cc8640d2..4914683cc4 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2249,7 +2249,7 @@ lighting Light Lys Fonts whose licence doesn't allow embedding are not copied. Skrifttyper, hvis licens ikke tillader indlejring, kopieres ikke. Package collects a saved document with its linked files and fonts. Pakning samler et gemt dokument med dets linkede filer og skrifttyper. Package created Pakke oprettet -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Pakkede {n} fil i {folder} {note}|Pakkede {n} filer i {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} Pakkede {n} fil i {folder} {note}|Pakkede {n} filer i {folder} {note} Packaged {n} file(s){note} Pakkede {n} fil(er){note} Relink Linked Files to the Document Genopret link til dokumentets linkede filer Save the document first? Gem dokumentet først? @@ -3953,7 +3953,7 @@ imageTrace Outline Kontur @msg PDF settings are not an object PDF-indstillinger er ikke et objekt @msg PDF security settings are not an object PDF-sikkerhedsindstillinger er ikke et objekt @msg PDF writer error: {0} PDF-skriverfejl: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Pakkede {n} fil i {folder} ({note}|Pakkede {n} filer i {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Pakkede {n} fil i {folder} ({note})|Pakkede {n} filer i {folder} ({note}) @msg Packaged {n} file(s){note} Pakkede {n} fil(er){note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Forhåndsvisning i browser kræver skrivebordsappen (webversionen downloader filer i stedet) @msg Release Guides: no guides Frigiv hjælpelinjer: ingen hjælpelinjer diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 378b15fcf8..aa374c33be 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2230,7 +2230,7 @@ file-filter Templates Vorlagen Package Verpacken Package collects a saved document with its linked files and fonts. „Verpacken“ sammelt ein gespeichertes Dokument mit seinen verknüpften Dateien und Schriften. Package created Paket erstellt -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} Datei in {folder} verpackt {note}|{n} Dateien in {folder} verpackt {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} {n} Datei in {folder} verpackt {note}|{n} Dateien in {folder} verpackt {note} Packaged {n} file(s){note} {n} Datei(en) verpackt{note} Package… Verpacken… Page Seite @@ -3848,7 +3848,7 @@ theme Appearance Erscheinungsbild @msg PDF settings are not an object die PDF-Einstellungen sind kein Objekt @msg PDF security settings are not an object die PDF-Sicherheitseinstellungen sind kein Objekt @msg PDF writer error: {0} Fehler beim Schreiben der PDF-Datei: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} {n} Datei in {folder} verpackt ({note}|{n} Dateien in {folder} verpackt ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} {n} Datei in {folder} verpackt ({note})|{n} Dateien in {folder} verpackt ({note}) @msg Packaged {n} file(s){note} {n} Datei(en) verpackt{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) „Vorschau im Browser“ erfordert die Desktop-App (im Web werden stattdessen Dateien heruntergeladen) @msg Release Guides: no guides Hilfslinien zurückwandeln: keine Hilfslinien diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index c62f82eaab..f1758e7a4f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2161,7 +2161,7 @@ axis Both Και τα δύο @msg PDF settings are not an object Οι ρυθμίσεις PDF δεν είναι αντικείμενο @msg PDF security settings are not an object Οι ρυθμίσεις ασφαλείας PDF δεν είναι αντικείμενο @msg PDF writer error: {0} Σφάλμα εγγραφής PDF: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Συσκευάστηκε {n} αρχείο στον φάκελο {folder} ({note}|Συσκευάστηκαν {n} αρχεία στον φάκελο {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Συσκευάστηκε {n} αρχείο στον φάκελο {folder} ({note})|Συσκευάστηκαν {n} αρχεία στον φάκελο {folder} ({note}) @msg Packaged {n} file(s){note} Συσκευάστηκαν {n} αρχεία{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Η προεπισκόπηση σε πρόγραμμα περιήγησης απαιτεί την εφαρμογή υπολογιστή (η έκδοση ιστού πραγματοποιεί λήψη αρχείων) @msg Release Guides: no guides Αποδέσμευση οδηγών: δεν υπάρχουν οδηγοί @@ -2928,7 +2928,7 @@ theme Appearance Εμφάνιση Override Character Color Παράκαμψη χρώματος χαρακτήρων Package collects a saved document with its linked files and fonts. Η συσκευασία συγκεντρώνει ένα αποθηκευμένο έγγραφο μαζί με συνδεδεμένα αρχεία και γραμματοσειρές. Package created Η συσκευασία δημιουργήθηκε -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Συσκευάστηκε {n} αρχείο στον φάκελο {folder} {note}|Συσκευάστηκαν {n} αρχεία στον φάκελο {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} Συσκευάστηκε {n} αρχείο στον φάκελο {folder} {note}|Συσκευάστηκαν {n} αρχεία στον φάκελο {folder} {note} Packaged {n} file(s){note} Συσκευάστηκαν {n} αρχεία{note} Page Σελίδα Page information Πληροφορίες σελίδας diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index dd8fbcc8ce..bc7ddaf56c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2272,7 +2272,7 @@ font-technology Variable Variables Package Empaquetar Package collects a saved document with its linked files and fonts. Empaquetar reúne un documento guardado con sus archivos vinculados y fuentes. Package created Paquete creado -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Se empaquetó {n} archivo en {folder} {note}|Se empaquetaron {n} archivos en {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} Se empaquetó {n} archivo en {folder} {note}|Se empaquetaron {n} archivos en {folder} {note} Packaged {n} file(s){note} Se empaquetaron {n} archivo(s){note} Package… Empaquetar… Page Página @@ -3928,7 +3928,7 @@ axis Both Ambos @msg PDF settings are not an object los ajustes de PDF no son un objeto @msg PDF security settings are not an object los ajustes de seguridad de PDF no son un objeto @msg PDF writer error: {0} error del escritor de PDF: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Se empaquetó {n} archivo en {folder} ({note}|Se empaquetaron {n} archivos en {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Se empaquetó {n} archivo en {folder} ({note})|Se empaquetaron {n} archivos en {folder} ({note}) @msg Packaged {n} file(s){note} Se empaquetaron {n} archivo(s){note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Previsualizar en el navegador requiere la aplicación de escritorio (la versión web descarga los archivos) @msg Release Guides: no guides Soltar guías: no hay guías diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 242f01eb1b..1d6fd7c02c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2401,7 +2401,7 @@ lighting Light Valo Fonts whose licence doesn't allow embedding are not copied. Fontteja, joiden lisenssi ei salli upottamista, ei kopioida. Package collects a saved document with its linked files and fonts. Paketointi kokoaa tallennetun asiakirjan sekä sen linkitetyt tiedostot ja fontit. Package created Paketti luotu -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Paketoitiin {n} tiedosto kansioon {folder} {note}|Paketoitiin {n} tiedostoa kansioon {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} Paketoitiin {n} tiedosto kansioon {folder} {note}|Paketoitiin {n} tiedostoa kansioon {folder} {note} Packaged {n} file(s){note} Paketoitu {n} tiedosto(a){note} Relink Linked Files to the Document Linkitä linkitetyt tiedostot uudelleen asiakirjaan Save the document first? Tallennetaanko asiakirja ensin? @@ -4151,7 +4151,7 @@ imageTrace Outline Ääriviiva @msg PDF settings are not an object PDF-asetukset eivät ole objekti @msg PDF security settings are not an object PDF-suojausasetukset eivät ole objekti @msg PDF writer error: {0} PDF-kirjoittimen virhe: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Paketoitiin {n} tiedosto kansioon {folder} ({note}|Paketoitiin {n} tiedostoa kansioon {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Paketoitiin {n} tiedosto kansioon {folder} ({note})|Paketoitiin {n} tiedostoa kansioon {folder} ({note}) @msg Packaged {n} file(s){note} Paketoitiin {n} tiedosto(a){note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Esikatselu selaimessa vaatii työpöytäsovelluksen (verkkoversio lataa tiedostot sen sijaan) @msg Release Guides: no guides Vapauta apuviivat: ei apuviivoja diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 247848ee4e..e1aa7309f6 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2270,7 +2270,7 @@ font-technology Variable Variables Package Assembler Package collects a saved document with its linked files and fonts. Assembler rassemble un document enregistré avec ses fichiers liés et ses polices. Package created Assemblage créé -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} fichier assemblé dans {folder} {note}|{n} fichiers assemblés dans {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} {n} fichier assemblé dans {folder} {note}|{n} fichiers assemblés dans {folder} {note} Packaged {n} file(s){note} {n} fichier(s) assemblé(s){note} Package… Assembler… Page Page @@ -3924,7 +3924,7 @@ axis Both Les deux @msg PDF settings are not an object Les paramètres PDF ne sont pas un objet @msg PDF security settings are not an object Les paramètres de sécurité PDF ne sont pas un objet @msg PDF writer error: {0} Erreur du générateur PDF : {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} {n} fichier assemblé dans {folder} ({note}|{n} fichiers assemblés dans {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} {n} fichier assemblé dans {folder} ({note})|{n} fichiers assemblés dans {folder} ({note}) @msg Packaged {n} file(s){note} {n} fichier(s) assemblé(s){note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Aperçu dans le navigateur nécessite l’application de bureau (la version web télécharge les fichiers à la place) @msg Release Guides: no guides Annuler les repères : aucun repère diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 94c29d9006..10be9ac87f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2754,7 +2754,7 @@ file-filter Templates Sablonok Package Csomagolás Package collects a saved document with its linked files and fonts. A csomagolás egy mentett dokumentumot a csatolt fájljaival és betűtípusaival együtt gyűjt össze. Package created A csomag elkészült -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Becsomagolt fájlok: {n}, mappa: {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} Becsomagolt fájlok: {n}, mappa: {folder} {note} Packaged {n} file(s){note} Becsomagolt fájlok: {n}{note} Package… Csomagolás… Page Oldal @@ -4955,7 +4955,7 @@ imageTrace Outline Körvonal @msg Opened with {_1} note(s): {_2} Megnyitva; megjegyzések: {_1}: {_2} @msg Opened {url} Megnyitva: {url} @msg Outline Stroke: no stroked paths selected Körvonal útvonallá alakítása: nincs kijelölt körvonalas útvonal -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Becsomagolt fájlok: {n}, mappa: {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Becsomagolt fájlok: {n}, mappa: {folder} ({note}) @msg Packaged {n} file(s){note} Becsomagolt fájlok: {n}{note} @msg page size {w} × {h} oldalméret: {w} × {h} @msg page {0} does not exist (the PDF has {1}) nincs ilyen oldal: {0} (a PDF oldalszáma: {1}) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 6b1167464b..53927a0206 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2249,7 +2249,7 @@ lighting Light Cahaya Fonts whose licence doesn't allow embedding are not copied. Font yang lisensinya tidak mengizinkan penyematan tidak disalin. Package collects a saved document with its linked files and fonts. Package mengumpulkan dokumen tersimpan beserta file dan font yang tertaut. Package created Paket dibuat -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} file dipaketkan dalam {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} {n} file dipaketkan dalam {folder} {note} Packaged {n} file(s){note} {n} file dipaketkan{note} Relink Linked Files to the Document Tautkan ulang file tertaut ke dokumen Save the document first? Simpan dokumen terlebih dahulu? @@ -3953,7 +3953,7 @@ imageTrace Outline Kontur @msg PDF settings are not an object Pengaturan PDF bukan objek @msg PDF security settings are not an object Pengaturan keamanan PDF bukan objek @msg PDF writer error: {0} Kesalahan penulis PDF: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Berhasil mengemas {n} file di {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Berhasil mengemas {n} file di {folder} ({note}) @msg Packaged {n} file(s){note} Berhasil mengemas {n} file{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Pratinjau di Peramban memerlukan aplikasi desktop (versi web mengunduh file sebagai gantinya) @msg Release Guides: no guides Lepaskan panduan: tidak ada panduan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 7ca999d56b..d48cb24f5f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2299,7 +2299,7 @@ file-filter Templates Modelli Package Crea pacchetto Package collects a saved document with its linked files and fonts. Il comando Crea pacchetto raccoglie un documento salvato insieme ai file collegati e ai font. Package created Pacchetto creato -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Pacchetto creato con {n} file in {folder} {note}|Pacchetto creato con {n} file in {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} Pacchetto creato con {n} file in {folder} {note}|Pacchetto creato con {n} file in {folder} {note} Packaged {n} file(s){note} Pacchetto creato con {n} file{note} Package… Crea pacchetto… Page Pagina @@ -3968,7 +3968,7 @@ axis Both Entrambi @msg PDF settings are not an object Le impostazioni PDF non sono un oggetto @msg PDF security settings are not an object Le impostazioni di sicurezza PDF non sono un oggetto @msg PDF writer error: {0} Errore del generatore PDF: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Pacchetto creato con {n} file in {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Pacchetto creato con {n} file in {folder} ({note}) @msg Packaged {n} file(s){note} Pacchetto creato con {n} file{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Anteprima nel browser richiede l'app desktop (sul web i file vengono invece scaricati) @msg Release Guides: no guides Rilascia guide: nessuna guida diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index cec459c4b1..cd1d86f4d5 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3585,7 +3585,7 @@ file-filter Templates テンプレート Output Black 出力ブラック Output White 出力ホワイト Output › Mode 出力 › モード -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {folder} に {n} 個のファイルをパッケージしました{note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} {folder} に {n} 個のファイルをパッケージしました{note} Packaged {n} file(s){note} {n} 個のファイルをパッケージしました{note} Page information ページ情報 Paragraph Style 段落スタイル @@ -4459,7 +4459,7 @@ swatch Bright Violet ビビッドバイオレット @msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} 個のリンク画像がディスク上で変更されました: 「リンクを更新」で新しいバージョンを表示できます @msg Updated {_1} linked file(s) changed on disk ディスク上で変更された {_1} 個のリンクファイルを更新しました @msg pick a colour, gradient or pattern to save as a swatch スウォッチとして保存するカラー、グラデーション、またはパターンを選択してください -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} {n} 個のファイルを {folder} にパッケージしました({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} {n} 個のファイルを {folder} にパッケージしました({note}) @msg Packaged {n} file(s){note} {n} 個のファイルをパッケージしました{note} @msg choose a location for the package パッケージの保存場所を選択してください @msg missing `folder` `folder` が指定されていません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a8664eca33..798b57b0b0 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2145,7 +2145,7 @@ lighting Light სინათლე Fonts whose licence doesn't allow embedding are not copied. შრიფტები, რომელთა ლიცენზია ჩაშენების უფლებას არ იძლევა, არ კოპირდება. Package collects a saved document with its linked files and fonts. შეფუთვა აგროვებს შენახულ დოკუმენტს მის დაკავშირებულ ფაილებთან და შრიფტებთან ერთად. Package created შეფუთვა შეიქმნა -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} შეიფუთა ფაილები: {n}, ადგილი: {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} შეიფუთა ფაილები: {n}, ადგილი: {folder} {note} Packaged {n} file(s){note} შეიფუთა ფაილები: {n}{note} Relink Linked Files to the Document დაკავშირებული ფაილების დოკუმენტთან ხელახლა დაკავშირება Save the document first? ჯერ შევინახოთ დოკუმენტი? @@ -3723,7 +3723,7 @@ font-technology Variable ცვლადი @msg PDF settings are not an object PDF-ის პარამეტრები ობიექტი არ არის @msg PDF security settings are not an object PDF-ის უსაფრთხოების პარამეტრები ობიექტი არ არის @msg PDF writer error: {0} PDF-ის ჩამწერის შეცდომა: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} შეფუთულია ფაილი ({n}) საქაღალდეში {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} შეფუთულია ფაილი ({n}) საქაღალდეში {folder} ({note}) @msg Packaged {n} file(s){note} შეფუთულია ფაილი ({n}){note} @msg Preview in Browser needs the desktop app (the web downloads files instead) ბრაუზერში წინასწარ ნახვას დესკტოპის აპი სჭირდება (ვებში ფაილები ჩამოიტვირთება) @msg Release Guides: no guides დამხმარე ხაზების მოხსნა: დამხმარე ხაზები არ არის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 0b47ed20a0..38eb0dad0b 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3574,7 +3574,7 @@ file-filter Templates 템플릿 Output Black 출력 검정 Output White 출력 흰색 Output › Mode 출력 › 모드 -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {folder}에 파일 {n}개를 패키지했습니다 {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} {folder}에 파일 {n}개를 패키지했습니다 {note} Packaged {n} file(s){note} 파일 {n}개를 패키지했습니다{note} Page information 페이지 정보 Paragraph Style 단락 스타일 @@ -4387,7 +4387,7 @@ theme Appearance 외관 @msg {_1} linked image(s) changed on disk: Update Links shows the new versions 링크된 이미지 {_1}개가 디스크에서 바뀌었습니다: 링크 업데이트를 하면 새 버전이 표시됩니다 @msg Updated {_1} linked file(s) changed on disk 디스크에서 바뀐 링크된 파일 {_1}개를 업데이트했습니다 @msg pick a colour, gradient or pattern to save as a swatch 견본으로 저장할 색상, 그레이디언트 또는 패턴을 선택하세요 -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} {folder}에 파일 {n}개를 패키지했습니다({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} {folder}에 파일 {n}개를 패키지했습니다({note}) @msg Packaged {n} file(s){note} 파일 {n}개를 패키지했습니다{note} @msg choose a location for the package 패키지 위치를 선택하세요 @msg missing `folder` `folder`가 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c8df690252..2a56400a2a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2263,7 +2263,7 @@ lighting Light Licht Fonts whose licence doesn't allow embedding are not copied. Lettertypen waarvan de licentie insluiten niet toestaat, worden niet gekopieerd. Package collects a saved document with its linked files and fonts. Verpakken verzamelt een opgeslagen document met zijn gekoppelde bestanden en lettertypen. Package created Pakket gemaakt -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} bestand verpakt in {folder} {note}|{n} bestanden verpakt in {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} {n} bestand verpakt in {folder} {note}|{n} bestanden verpakt in {folder} {note} Packaged {n} file(s){note} {n} bestand(en) verpakt{note} Relink Linked Files to the Document Gekoppelde bestanden opnieuw koppelen aan het document Save the document first? Wil je het document eerst opslaan? @@ -3967,7 +3967,7 @@ imageTrace Outline Contour @msg PDF settings are not an object PDF-instellingen zijn geen object @msg PDF security settings are not an object PDF-beveiligingsinstellingen zijn geen object @msg PDF writer error: {0} PDF-schrijffout: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} {n} bestand verpakt in {folder} ({note}|{n} bestanden verpakt in {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} {n} bestand verpakt in {folder} ({note})|{n} bestanden verpakt in {folder} ({note}) @msg Packaged {n} file(s){note} {n} bestand(en) verpakt{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Voorvertoning in browser heeft de desktop-app nodig (het web downloadt in plaats daarvan bestanden) @msg Release Guides: no guides Hulplijnen vrijgeven: geen hulplijnen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index da672c7d7c..1b8e322eb8 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2371,7 +2371,7 @@ lighting Light Światło Fonts whose licence doesn't allow embedding are not copied. Czcionki, których licencja nie zezwala na osadzanie, nie są kopiowane. Package collects a saved document with its linked files and fonts. Pakowanie zbiera zapisany dokument wraz z połączonymi plikami i czcionkami. Package created Utworzono pakiet -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Spakowane pliki: {n} w {folder} {note}|Spakowane pliki: {n} w {folder} {note}|Spakowane pliki: {n} w {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} Spakowane pliki: {n} w {folder} {note}|Spakowane pliki: {n} w {folder} {note}|Spakowane pliki: {n} w {folder} {note} Packaged {n} file(s){note} Spakowane pliki: {n}{note} Relink Linked Files to the Document Połącz ponownie połączone pliki z dokumentem Save the document first? Najpierw zapisać dokument? @@ -4060,7 +4060,7 @@ imageTrace Outline Kontur @msg PDF settings are not an object Ustawienia PDF nie są obiektem @msg PDF security settings are not an object Ustawienia zabezpieczeń PDF nie są obiektem @msg PDF writer error: {0} Błąd zapisu PDF: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Spakowane pliki: {n} w {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Spakowane pliki: {n} w {folder} ({note}) @msg Packaged {n} file(s){note} Spakowane pliki: {n}{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Podgląd w przeglądarce wymaga aplikacji desktopowej (wersja webowa zamiast tego pobiera pliki) @msg Release Guides: no guides Uwolnij linie pomocnicze: brak linii pomocniczych diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 7a2e021713..f64b2436d9 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3514,7 +3514,7 @@ axis Both Ambos @msg PDF settings are not an object as configurações de PDF não são um objeto @msg PDF security settings are not an object as configurações de segurança de PDF não são um objeto @msg PDF writer error: {0} Erro do gravador de PDF: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} {n} arquivo empacotado em {folder} ({note}|{n} arquivos empacotados em {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} {n} arquivo empacotado em {folder} ({note})|{n} arquivos empacotados em {folder} ({note}) @msg Packaged {n} file(s){note} {n} arquivo(s) empacotado(s){note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Visualizar no navegador exige o aplicativo para desktop (na web, os arquivos são baixados) @msg Release Guides: no guides Liberar guias: não há guias @@ -4590,7 +4590,7 @@ axis Both Ambos Output Black Preto de Saída Output White Branco de Saída Output › Mode Saída › Modo -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} arquivo empacotado em {folder} {note}|{n} arquivos empacotados em {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} {n} arquivo empacotado em {folder} {note}|{n} arquivos empacotados em {folder} {note} Packaged {n} file(s){note} {n} arquivo(s) empacotado(s){note} Page information Informações da página Paragraph Style Estilo de Parágrafo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index be1152ca95..816096e51f 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2295,7 +2295,7 @@ file-filter Templates Шаблоны Package Упаковать Package collects a saved document with its linked files and fonts. Упаковка собирает сохранённый документ с его связанными файлами и шрифтами. Package created Пакет создан -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Упаковано файлов: {n} в {folder} {note}|Упаковано файлов: {n} в {folder} {note}|Упаковано файлов: {n} в {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} Упаковано файлов: {n} в {folder} {note}|Упаковано файлов: {n} в {folder} {note}|Упаковано файлов: {n} в {folder} {note} Packaged {n} file(s){note} Упаковано файлов: {n}{note} Package… Упаковать… Page Страница @@ -3964,7 +3964,7 @@ axis Both Оба @msg PDF settings are not an object параметры PDF не являются объектом @msg PDF security settings are not an object параметры безопасности PDF не являются объектом @msg PDF writer error: {0} ошибка записи PDF: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Упаковано файлов: {n} в {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Упаковано файлов: {n} в {folder} ({note}) @msg Packaged {n} file(s){note} Упаковано файлов: {n}{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Просмотр в браузере требует настольного приложения (web-версия скачивает файлы) @msg Release Guides: no guides Освобождение направляющих: нет направляющих diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index f29ac25925..46e4bd8445 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2217,7 +2217,7 @@ font-technology Variable Variabla Package Paketera Package collects a saved document with its linked files and fonts. Paketera samlar ett sparat dokument med dess länkade filer och typsnitt. Package created Paketet har skapats -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Paketerade {n} fil i {folder} {note}|Paketerade {n} filer i {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} Paketerade {n} fil i {folder} {note}|Paketerade {n} filer i {folder} {note} Packaged {n} file(s){note} Paketerade {n} fil(er){note} Package… Paketera… Page Sida @@ -3845,7 +3845,7 @@ axis Both Båda @msg PDF settings are not an object PDF-inställningarna är inte ett objekt @msg PDF security settings are not an object PDF-säkerhetsinställningarna är inte ett objekt @msg PDF writer error: {0} fel i PDF-skrivaren: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Paketerade {n} fil i {folder} ({note}|Paketerade {n} filer i {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Paketerade {n} fil i {folder} ({note})|Paketerade {n} filer i {folder} ({note}) @msg Packaged {n} file(s){note} Paketerade {n} fil(er){note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Förhandsgranska i webbläsare kräver skrivbordsappen (webbversionen hämtar filer i stället) @msg Release Guides: no guides Släpp stödlinjer: inga stödlinjer diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 68d84f44eb..1c2feb846a 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2095,7 +2095,7 @@ shape Open Açık Package Paket Package collects a saved document with its linked files and fonts. Paket, kayıtlı bir belgeyi bağlantılı dosyaları ve yazı tipleriyle birlikte toplar. Package created Paket oluşturuldu -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} dosya {folder} klasörüne paketlendi {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} {n} dosya {folder} klasörüne paketlendi {note} Packaged {n} file(s){note} Paketlenmiş {n} dosyası/dosyaları{note} Package… Paket… Page Sayfa @@ -3735,7 +3735,7 @@ axis Both Her İkisi @msg PDF settings are not an object PDF ayarları bir nesne değildir @msg PDF security settings are not an object PDF güvenlik ayarları bir nesne değildir @msg PDF writer error: {0} PDF yazıcı hatası: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} {n} dosya {folder} klasörüne paketlendi ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} {n} dosya {folder} klasörüne paketlendi ({note}) @msg Packaged {n} file(s){note} Paketlenmiş {n} dosyası/dosyaları{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Tarayıcıdaki önizleme için masaüstü uygulaması gerekir (bunun yerine web, dosyaları indirir) @msg Release Guides: no guides Sürüm Kılavuzları: kılavuz yok diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 133d91f98f..05f4ffe480 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2291,7 +2291,7 @@ file-filter Templates Шаблони Package Упакувати Package collects a saved document with its linked files and fonts. Упаковка збирає збережений документ із його пов’язаними файлами та шрифтами. Package created Пакет створено -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Упаковано файли: {n} {folder} {note}|Упаковано файли: {n} {folder} {note}|Упаковано файли: {n} {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} Упаковано файли: {n} {folder} {note}|Упаковано файли: {n} {folder} {note}|Упаковано файли: {n} {folder} {note} Packaged {n} file(s){note} Упаковано файли: {n}{note} Package… Упакувати… Page Сторінка @@ -3952,7 +3952,7 @@ axis Both Обидві @msg PDF settings are not an object Параметри PDF не є об’єктом @msg PDF security settings are not an object Параметри безпеки PDF не є об’єктом @msg PDF writer error: {0} Помилка запису PDF: {0} -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Упаковано файли: {n} {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Упаковано файли: {n} {folder} ({note}) @msg Packaged {n} file(s){note} Упаковано файли: {n}{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Перегляд у браузері вимагає настільної програми (web-версія завантажує файли) @msg Release Guides: no guides Звільнення напрямних: немає напрямних diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 2bd707c34f..b2744f443a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2562,7 +2562,7 @@ file-filter Templates Mẫu Package Gói Package collects a saved document with its linked files and fonts. Gói thu thập tài liệu đã lưu cùng tệp liên kết và phông chữ. Package created Đã tạo gói -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Đã đóng gói {n} tệp trong {folder} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} Đã đóng gói {n} tệp trong {folder} {note} Packaged {n} file(s){note} Đã đóng gói {n} tệp{note} Package… Gói… Page Trang @@ -4606,7 +4606,7 @@ theme Appearance Giao diện @msg Opened with {_1} note(s): {_2} Đã mở với {_1} ghi chú: {_2} @msg Opened {url} Đã mở {url} @msg Outline Stroke: no stroked paths selected Đường bao nét: chưa chọn đường dẫn có nét -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Đã đóng gói {n} tệp trong {folder} ({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Đã đóng gói {n} tệp trong {folder} ({note}) @msg Packaged {n} file(s){note} Đã đóng gói {n} tệp{note} @msg page size {w} × {h} kích thước trang {w} × {h} @msg page {0} does not exist (the PDF has {1}) trang {0} không tồn tại (PDF có {1} trang) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 631cd8a7c3..cfea6e224d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2169,7 +2169,7 @@ file-filter Templates 模板 Package 打包 Package collects a saved document with its linked files and fonts. 打包会将已存储的文件连同其链接文件与字体一并收集。 Package created 已创建打包 -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} 已将 {n} 个文件打包于 {folder}{note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} 已将 {n} 个文件打包于 {folder}{note} Packaged {n} file(s){note} 已打包 {n} 个文件{note} Package… 打包… Page 页面 @@ -4179,7 +4179,7 @@ imageTrace Outline 轮廓 @msg {undecoded} image(s) couldn't be decoded and show as crossed boxes 无法解码 {undecoded} 张图像:它们显示为打叉的方框 @msg {_1} linked image(s) changed on disk: Update Links shows the new versions 有 {_1} 个链接图像已在磁盘上更改:“更新链接”可显示新版本 @msg pick a colour, gradient or pattern to save as a swatch 请选取要保存为色板的颜色、渐变或图案 -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} 已将 {n} 个文件打包到 {folder}({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} 已将 {n} 个文件打包到 {folder}({note}) @msg Packaged {n} file(s){note} 已打包 {n} 个文件{note} @msg choose a location for the package 请为打包选择位置 @msg missing `folder` 缺少 `folder` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index df2948e472..0605652e52 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2114,7 +2114,7 @@ file-filter Templates 範本 @msg {undecoded} image(s) couldn't be decoded and show as crossed boxes 無法解碼 {undecoded} 張影像:它們顯示為打叉的方框 @msg {_1} linked image(s) changed on disk: Update Links shows the new versions 有 {_1} 個連結影像已在磁碟上變更:「更新連結」可顯示新版本 @msg pick a colour, gradient or pattern to save as a swatch 請挑選要儲存為色票的顏色、漸層或圖樣 -@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} 已將 {n} 個檔案封裝到 {folder}({note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} 已將 {n} 個檔案封裝到 {folder}({note}) @msg Packaged {n} file(s){note} 已封裝 {n} 個檔案{note} @msg choose a location for the package 請選擇封裝的位置 @msg missing `folder` 未提供 `folder` @@ -3108,7 +3108,7 @@ file-filter Templates 範本 Package 封裝 Package collects a saved document with its linked files and fonts. 封裝會將已儲存的文件連同其連結檔案與字體一併收集。 Package created 已建立封裝 -@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} 已將 {n} 個檔案封裝於 {folder}{note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} 已將 {n} 個檔案封裝於 {folder}{note} Packaged {n} file(s){note} 已封裝 {n} 個檔案{note} Package… 封裝… Page 頁面 From 5a5a7b9ce8c2d359047d380881b338b2abde5e86 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 08:09:04 -0700 Subject: [PATCH 151/260] Mesh tool: a click on a mesh's edge from just outside adds the lines there A Mesh tool click within the hit tolerance outside a gradient mesh hit the mesh, but object.mesh.addLine looked for the point inside the outline only and failed with "point is outside the mesh". The same click on a path's edge made a 1x1 mesh without the line. - GradientMesh::locate_within takes a tolerance: a point outside the mesh within it of the outline gives the nearest point of the edge. - object.mesh.addLine and object.mesh.create take an optional `tolerance` (0 by default), and the Mesh tool sends its hit tolerance. --- crates/doc/src/live.rs | 16 +++++++++++++++- crates/doc/src/live/mesh.rs | 16 ++++++++++++---- crates/engine/src/cmd/live/commands.rs | 4 ++-- crates/engine/src/cmd/live/mesh.rs | 9 ++++++--- crates/engine/src/tests/live.rs | 26 ++++++++++++++++++++++++++ crates/tools/src/meshblend.rs | 13 +++++++++---- crates/tools/src/meshedit.rs | 2 +- 7 files changed, 71 insertions(+), 15 deletions(-) diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 1b234c2122..85949436b9 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -237,13 +237,27 @@ mod tests { fn mesh_insert_and_remove_lines() { let mut m = GradientMesh::for_path(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); - let i = m.add_lines_at(Point::new(30.0, 60.0)).unwrap(); + let i = m.add_lines_at(Point::new(30.0, 60.0), 0.0).unwrap(); assert_eq!((m.rows, m.cols), (2, 2)); assert!(m.points[i].p.distance(Point::new(30.0, 60.0)) < 0.5, "{:?}", m.points[i].p); assert!(m.remove_point_lines(i)); assert_eq!((m.rows, m.cols), (1, 1)); } + /// A point outside the mesh within the tolerance locates the nearest point of its edge. + #[test] + fn mesh_locate_within_reaches_the_edge() { + let m = GradientMesh::for_path(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), 2, 2, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); + let p = Point::new(102.0, 30.0); + assert_eq!(m.locate(p), None); + assert_eq!(m.locate_within(p, 1.0), None); + let (r, c, u, v) = m.locate_within(p, 3.0).unwrap(); + assert_eq!((r, c), (0, 1)); + let q = m.eval(r, c, u, v); + assert!(q.distance(Point::new(100.0, 30.0)) < 0.5, "{q:?}"); + assert_eq!(m.locate_within(Point::new(30.0, 60.0), 3.0), m.locate(Point::new(30.0, 60.0))); + } + /// Corners all in CMYK mix in CMYK (the inks halfway), not in RGB. #[test] fn a_cmyk_mesh_mixes_its_inks() { diff --git a/crates/doc/src/live/mesh.rs b/crates/doc/src/live/mesh.rs index f72dd548cc..b4e74e7111 100644 --- a/crates/doc/src/live/mesh.rs +++ b/crates/doc/src/live/mesh.rs @@ -592,11 +592,18 @@ impl GradientMesh { /// Which patch and local (u, v) contains `p` (sampled search; `None` outside the mesh). pub fn locate(&self, p: Point) -> Option<(usize, usize, f64, f64)> { + self.locate_within(p, 0.0) + } + + /// As [`Self::locate`], and for a point outside the mesh within `tol` of its outline, the + /// patch and local (u, v) of the nearest point of the mesh's edge. + pub fn locate_within(&self, p: Point, tol: f64) -> Option<(usize, usize, f64, f64)> { + use vectorcraft_geom::kurbo::ParamCurveNearest; if !self.is_valid() { return None; } let bp = self.outline().to_bezpath(); - if bp.winding(p) == 0 { + if bp.winding(p) == 0 && !(tol > 0.0 && bp.segments().any(|s| s.nearest(p, 1e-9).distance_sq <= tol * tol)) { return None; } const N: usize = 16; @@ -721,9 +728,10 @@ impl GradientMesh { self.cols += 1; } - /// Mesh tool click: add a row and a column through `p` (inside the mesh). Returns the new point index. - pub fn add_lines_at(&mut self, p: Point) -> Option<usize> { - let (r, c, u, v) = self.locate(p)?; + /// Mesh tool click: add a row and a column through `p` (inside the mesh, or outside within + /// `tol` of its edge, through the nearest point of the edge). Returns the new point index. + pub fn add_lines_at(&mut self, p: Point, tol: f64) -> Option<usize> { + let (r, c, u, v) = self.locate_within(p, tol)?; let mut rr = r; let mut cc = c; let row_new = v > 0.02 && v < 0.98; diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index aec4e32d00..5f438c8f5b 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -236,7 +236,7 @@ pub fn specs() -> Vec<CommandSpec> { "Create Gradient Mesh…", ["Object"], None, - "{ids?, rows?: n (4), cols?: n (4), appearance?: flat|center|edge, highlight?: % (100), at?: [x,y], columns?: as cols} convert filled paths into gradient meshes in their fill colour (a gradient fill: the colour it paints at each point), lightened per `appearance` (with `at`: 1×1 mesh plus lines through that point); an embedded image becomes a mesh over its rectangle (its transform kept) whose points take the average colour and opacity of the picture around them (a linked image is refused: embed it first) → {ids, index?}", + "{ids?, rows?: n (4), cols?: n (4), appearance?: flat|center|edge, highlight?: % (100), at?: [x,y], tolerance?: pt (0), columns?: as cols} convert filled paths into gradient meshes in their fill colour (a gradient fill: the colour it paints at each point), lightened per `appearance` (with `at`: 1×1 mesh plus lines through that point, or through the nearest point of the edge when `at` is outside within `tolerance`); an embedded image becomes a mesh over its rectangle (its transform kept) whose points take the average colour and opacity of the picture around them (a linked image is refused: embed it first) → {ids, index?}", has_selection, mesh_create ), @@ -272,7 +272,7 @@ pub fn specs() -> Vec<CommandSpec> { "Add Mesh Line", [], None, - "{id, x, y, color?, keepModel?: bool (as paint.setFill)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope → {index}", + "{id, x, y, color?, keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge → {index}", has_doc, mesh_add_line ), diff --git a/crates/engine/src/cmd/live/mesh.rs b/crates/engine/src/cmd/live/mesh.rs index 602e2e3e96..bdba2b037a 100644 --- a/crates/engine/src/cmd/live/mesh.rs +++ b/crates/engine/src/cmd/live/mesh.rs @@ -16,8 +16,9 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> { Some(a) => MeshAppearance::parse(a).ok_or_else(|| bad(C, "appearance must be flat|center|edge"))?, None => MeshAppearance::Flat, }; - check_numbers(p, &["highlight"], C)?; + check_numbers(p, &["highlight", "tolerance"], C)?; let highlight = f64_or(p, "highlight", 100.0).clamp(0.0, 100.0); + let tol = f64_or(p, "tolerance", 0.0).max(0.0); let at = match p.get("at") { None | Some(Value::Null) => None, Some(v) => Some(finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, "`at` must be [x, y]"))?), @@ -58,7 +59,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> { }; let Some(mut m) = m else { continue }; if let Some(q) = at { - index = m.add_lines_at(q); + index = m.add_lines_at(q, tol); } let mut mn = Node::new(n.id, NodeKind::Mesh(m)); mn.name = n.name.clone(); @@ -273,9 +274,11 @@ pub(super) fn mesh_add_line(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "object.mesh.addLine"; let q = Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?); crate::cmd::paint::check_keep_model(p, C)?; + check_numbers(p, &["tolerance"], C)?; + let tol = f64_or(p, "tolerance", 0.0).max(0.0); let color = p.get("color").and_then(color_value).map(|c| crate::cmd::paint::new_color(s, p, c)); let index = with_mesh(s, p, C, "Add Mesh Line", true, |m| { - let i = m.add_lines_at(q).ok_or_else(|| bad(C, "point is outside the mesh"))?; + let i = m.add_lines_at(q, tol).ok_or_else(|| bad(C, "point is outside the mesh"))?; if let Some(c) = color { m.points[i].color = c; } diff --git a/crates/engine/src/tests/live.rs b/crates/engine/src/tests/live.rs index a3b9f132b5..b46e5b0d0f 100644 --- a/crates/engine/src/tests/live.rs +++ b/crates/engine/src/tests/live.rs @@ -927,6 +927,32 @@ fn mesh_add_line_and_delete_point() { assert!(s.execute("object.mesh.deletePoint", &json!({"id": a.0, "index": 0})).is_err(), "corner lines can't go"); } +/// A Mesh tool click that hits a mesh's edge from just outside it adds a mesh line at the +/// nearest point of the edge; `tolerance` gives `object.mesh.addLine` the same reach. +#[test] +fn mesh_add_line_on_the_edge_from_just_outside() { + use crate::tooling::ViewInfo; + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + sel(&mut s, &[a]); + s.execute("object.mesh.create", &json!({"rows": 1, "cols": 1})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("mesh", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 99.0, 160.0), v).unwrap(); + } + let m = mesh_of(&s, a); + assert_eq!((m.rows, m.cols), (2, 1), "a row through the left edge"); + assert!(m.points.iter().any(|q| q.p.distance(Point::new(100.0, 160.0)) < 0.5), "{:?}", m.points.iter().map(|q| q.p).collect::<Vec<_>>()); + let r = s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 140, "y": 202, "tolerance": 3})).unwrap(); + let m = mesh_of(&s, a); + assert_eq!((m.rows, m.cols), (2, 2), "a column through the bottom edge"); + assert!(m.points[r["index"].as_u64().unwrap() as usize].p.distance(Point::new(140.0, 200.0)) < 0.5); + assert!(s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 140, "y": 202})).is_err(), "no tolerance: outside"); + assert!(s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 140, "y": 210, "tolerance": 3})).is_err(), "past the tolerance"); +} + /// A mesh point `index`, and `rows`, `cols` or `columns` for Create Gradient Mesh, that is not a /// whole number is an error that changes nothing; 4.0 names point 4. #[test] diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index 68c1e41327..0790407d2a 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -232,10 +232,12 @@ impl Tool for MeshTool { (Paint::Solid { color, .. }, false) => Some(crate::params::color_json(color)), _ => None, }; + // A click that hits an edge from just outside adds the lines at the edge. + let tol = cx.hit_options().tol; for id in [leaf, top] { match cx.doc.node(id).map(|n| &n.kind) { Some(NodeKind::Mesh(_)) => { - let mut params = json!({"id": id.0, "x": p.x, "y": p.y}); + let mut params = json!({"id": id.0, "x": p.x, "y": p.y, "tolerance": tol}); if let Some(c) = &color { params["color"] = c.clone(); params["keepModel"] = json!(true); @@ -243,10 +245,10 @@ impl Tool for MeshTool { return vec![Action::Exec("object.mesh.addLine".into(), params)]; } Some(NodeKind::Envelope { .. }) if cx.doc.node(id).and_then(grid_of).is_some() => { - return vec![Action::Exec("object.mesh.addLine".into(), json!({"id": id.0, "x": p.x, "y": p.y}))]; + return vec![Action::Exec("object.mesh.addLine".into(), json!({"id": id.0, "x": p.x, "y": p.y, "tolerance": tol}))]; } Some(NodeKind::Path { guide: false, .. }) | Some(NodeKind::Compound { .. }) => { - return vec![Action::Exec("object.mesh.create".into(), json!({"ids": [id.0], "at": [p.x, p.y]}))]; + return vec![Action::Exec("object.mesh.create".into(), json!({"ids": [id.0], "at": [p.x, p.y], "tolerance": tol}))]; } _ => {} } @@ -490,6 +492,9 @@ mod tests { let c = cx(&d, &s, &p); let mut t = create("mesh").unwrap(); let acts = t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 160.0)); - assert_eq!(acts, vec![Action::Exec("object.mesh.create".into(), json!({"ids": [a.0], "at": [150.0, 160.0]}))]); + assert_eq!( + acts, + vec![Action::Exec("object.mesh.create".into(), json!({"ids": [a.0], "at": [150.0, 160.0], "tolerance": c.hit_options().tol}))] + ); } } diff --git a/crates/tools/src/meshedit.rs b/crates/tools/src/meshedit.rs index b3904efe41..e0ef779fb5 100644 --- a/crates/tools/src/meshedit.rs +++ b/crates/tools/src/meshedit.rs @@ -360,7 +360,7 @@ mod tests { // Inside the envelope: a new row and column. assert_eq!( t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 160.0)), - vec![Action::Exec("object.mesh.addLine".into(), json!({"id": e.0, "x": 150.0, "y": 160.0}))] + vec![Action::Exec("object.mesh.addLine".into(), json!({"id": e.0, "x": 150.0, "y": 160.0, "tolerance": c.hit_options().tol}))] ); } From c1205c4017fcfc54d20afd5d8e1b547143a7225e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 09:09:26 -0700 Subject: [PATCH 152/260] Mesh: a point outside the mesh locates on the nearest boundary edge locate_within maps a point outside the outline to the nearest point of the outer edges, so a patch folded past the outline does not take an edge click as an interior one. --- crates/doc/src/live.rs | 3 ++- crates/doc/src/live/mesh.rs | 29 ++++++++++++++++++++++++++--- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 85949436b9..304b7fede4 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -253,8 +253,9 @@ mod tests { assert_eq!(m.locate_within(p, 1.0), None); let (r, c, u, v) = m.locate_within(p, 3.0).unwrap(); assert_eq!((r, c), (0, 1)); + assert_eq!(u, 1.0, "on the right edge"); let q = m.eval(r, c, u, v); - assert!(q.distance(Point::new(100.0, 30.0)) < 0.5, "{q:?}"); + assert!(q.distance(Point::new(100.0, 30.0)) < 1e-6, "{q:?}"); assert_eq!(m.locate_within(Point::new(30.0, 60.0), 3.0), m.locate(Point::new(30.0, 60.0))); } diff --git a/crates/doc/src/live/mesh.rs b/crates/doc/src/live/mesh.rs index b4e74e7111..7fac277d3c 100644 --- a/crates/doc/src/live/mesh.rs +++ b/crates/doc/src/live/mesh.rs @@ -598,13 +598,12 @@ impl GradientMesh { /// As [`Self::locate`], and for a point outside the mesh within `tol` of its outline, the /// patch and local (u, v) of the nearest point of the mesh's edge. pub fn locate_within(&self, p: Point, tol: f64) -> Option<(usize, usize, f64, f64)> { - use vectorcraft_geom::kurbo::ParamCurveNearest; if !self.is_valid() { return None; } let bp = self.outline().to_bezpath(); - if bp.winding(p) == 0 && !(tol > 0.0 && bp.segments().any(|s| s.nearest(p, 1e-9).distance_sq <= tol * tol)) { - return None; + if bp.winding(p) == 0 { + return self.nearest_edge(p).filter(|e| e.0 <= tol * tol).map(|(_, r, c, u, v)| (r, c, u, v)); } const N: usize = 16; let mut best = (f64::INFINITY, 0, 0, 0.0, 0.0); @@ -641,6 +640,30 @@ impl GradientMesh { Some((r, c, u, v)) } + /// The point of the mesh's outer edge nearest `p`: its squared distance from `p`, and its + /// boundary patch and local (u, v). + fn nearest_edge(&self, p: Point) -> Option<(f64, usize, usize, f64, f64)> { + use vectorcraft_geom::kurbo::ParamCurveNearest; + let (rows, cols) = (self.rows as usize, self.cols as usize); + let mut best: Option<(f64, usize, usize, f64, f64)> = None; + let mut take = |e: CubicBez, at: (usize, usize, Option<f64>, Option<f64>)| { + let n = e.nearest(p, 1e-9); + if best.is_none_or(|b| n.distance_sq < b.0) { + let (r, c, u, v) = at; + best = Some((n.distance_sq, r, c, u.unwrap_or(n.t), v.unwrap_or(n.t))); + } + }; + for c in 0..cols { + take(self.edge_u(0, c), (0, c, None, Some(0.0))); + take(self.edge_u(rows, c), (rows - 1, c, None, Some(1.0))); + } + for r in 0..rows { + take(self.edge_v(r, 0), (r, 0, Some(0.0), None)); + take(self.edge_v(r, cols), (r, cols - 1, Some(1.0), None)); + } + best + } + /// Index of the mesh point within `tol` of `p`. pub fn point_near(&self, p: Point, tol: f64) -> Option<usize> { self.points From c6644c15cb8eb6510cbb1c17f663ea7f6c38a1c1 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 03:00:05 -0700 Subject: [PATCH 153/260] i18n: French linked-image count forms keep the no-break space before ? --- crates/ui-egui/src/i18n/fr.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e1aa7309f6..3e23421335 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3680,7 +3680,7 @@ font-technology Variable Variables @plural {n} linked file not found|{n} linked files not found {n} fichier lié introuvable|{n} fichiers liés introuvables fonts not copied: {fonts} polices non copiées : {fonts} @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} image liée modifiée depuis l’enregistrement de ce document. Afficher la nouvelle version ?|{n} images liées modifiées depuis l’enregistrement de ce document. Afficher les nouvelles versions ? -@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} image liée modifiée sur le disque. Afficher la nouvelle version ?|{n} images liées modifiées sur le disque. Afficher les nouvelles versions ? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} image liée modifiée sur le disque. Afficher la nouvelle version ?|{n} images liées modifiées sur le disque. Afficher les nouvelles versions ? @plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} règle de plus : Exporter l’écrit.|{n} règles de plus : Exporter les écrit toutes. @plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} objet sans nom omis : nommez-le ou activez Objets sans nom dans le menu du panneau.|{n} objets sans nom omis : nommez-les ou activez Objets sans nom dans le menu du panneau. {effect} is already applied {effect} est déjà appliqué From fc820cc066fcd4030af852206f9c0cb48b6de3d9 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 10:22:05 -0700 Subject: [PATCH 154/260] Mesh: no edge search for a lookup without tolerance --- crates/doc/src/live/mesh.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/doc/src/live/mesh.rs b/crates/doc/src/live/mesh.rs index 7fac277d3c..e6ba1656f1 100644 --- a/crates/doc/src/live/mesh.rs +++ b/crates/doc/src/live/mesh.rs @@ -603,6 +603,9 @@ impl GradientMesh { } let bp = self.outline().to_bezpath(); if bp.winding(p) == 0 { + if tol.is_nan() || tol <= 0.0 { + return None; + } return self.nearest_edge(p).filter(|e| e.0 <= tol * tol).map(|(_, r, c, u, v)| (r, c, u, v)); } const N: usize = 16; From 34563945a127dc2adf43e343a5b99fd671cc6cee Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 18:21:10 +0100 Subject: [PATCH 155/260] Replace non-finite type values in DocSetup::keep_in_range Found while testing crates/doc/src/setup.rs:308-316 (keep_in_range) Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- crates/doc/src/setup.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index ca08eca4a4..4ab8553298 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -308,9 +308,19 @@ impl DocSetup { pub fn keep_in_range(&mut self) { self.bleed = bleed_in_range(self.bleed); for m in [&mut self.superscript, &mut self.subscript] { + // `clamp` passes NaN through, so a non-finite value falls back to the default first. + if !m.size.is_finite() { + m.size = ScriptMetrics::DEFAULT.size; + } + if !m.position.is_finite() { + m.position = ScriptMetrics::DEFAULT.position; + } m.size = m.size.clamp(1.0, MAX_SCRIPT); m.position = m.position.clamp(-MAX_SCRIPT, MAX_SCRIPT); } + if !self.small_caps_size.is_finite() { + self.small_caps_size = DocSetup::default().small_caps_size; + } self.small_caps_size = self.small_caps_size.clamp(1.0, MAX_SMALL_CAPS); } } @@ -353,6 +363,20 @@ mod tests { assert!(s.has_bleed() && !DocSetup::default().has_bleed()); } + #[test] + fn keep_in_range_replaces_non_finite_type_values() { + let mut s = DocSetup::default(); + s.superscript.size = f64::NAN; + s.superscript.position = f64::INFINITY; + s.subscript.size = f64::NEG_INFINITY; + s.subscript.position = f64::NAN; + s.small_caps_size = f64::NAN; + s.keep_in_range(); + for v in [s.superscript.size, s.superscript.position, s.subscript.size, s.subscript.position, s.small_caps_size] { + assert!(v.is_finite(), "{v}"); + } + } + #[test] fn presets_and_defaults() { let d = DocSetup::default(); From d2418d6e7a5090f4f6393c531b19874e3d045531 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 09:47:00 -0700 Subject: [PATCH 156/260] Accessibility: Tab no longer stops on window, dialog, panel-grip and ruler drag regions Regions that only the pointer uses were made with Sense::drag() or Sense::click_and_drag(), which egui makes focusable, so Tab stopped on each of them and no key acted there. They now sense drags (and clicks where they use them) without taking the keyboard focus: the custom title bar's background and the window's resize zones, the band that moves a dialog, the Tools panel's grip, a flyout's and a floating strip's tear-off bar, the isolation bar's background, and the rulers and their origin box. Their pointer behavior is unchanged, and the grip and tear-off bars keep their screen-reader names. Each region has a test that tabs through its UI and fails without the change. --- crates/ui-egui/src/canvas/grid.rs | 8 +++-- crates/ui-egui/src/chrome/tabs.rs | 3 +- crates/ui-egui/src/chrome/tests.rs | 29 ++++++++++++++++ crates/ui-egui/src/dialogs/modal.rs | 5 +-- crates/ui-egui/src/dialogs/tests_modal.rs | 23 +++++++++++++ crates/ui-egui/src/tests/ruler_origin.rs | 14 ++++++++ crates/ui-egui/src/titlebar.rs | 21 ++++++++++-- crates/ui-egui/src/toolbar.rs | 6 ++-- crates/ui-egui/src/toolbar/tests.rs | 41 +++++++++++++++++++++++ crates/ui-egui/src/widgets.rs | 13 +++++++ docs/target-app-parity.md | 1 + 11 files changed, 154 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 1a978a4c7e..5b8b3435c3 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -185,8 +185,9 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c // Preferences ▸ Units ▸ General does ([`crate::menus::ruler_menu_body`]). let mut unit_clicked = None; for (r, vertical, id) in [(top, false, "ruler-top"), (left, true, "ruler-left")] { - // Click-and-drag so the same widget drags out guides (left) and opens the unit menu (right). - let resp = ui.interact(r, egui::Id::unique(id), Sense::click_and_drag()); + // Clicks and drags so the same widget drags out guides (left) and opens the unit menu + // (right). Not focusable (`click_and_drag` is): no key acts on a ruler, so Tab skips it. + let resp = ui.interact(r, egui::Id::unique(id), Sense::CLICK | Sense::DRAG); resp.context_menu(|ui| crate::menus::ruler_menu_body(app, ui, &mut unit_clicked)); let kind = if resp.drag_stopped() { PointerKind::Up @@ -212,7 +213,8 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c app.status(e.to_string()); } } - let corner = ui.interact(corner, egui::Id::unique("ruler-corner"), Sense::click_and_drag()); + // Not focusable either: no key acts on the box. + let corner = ui.interact(corner, egui::Id::unique("ruler-corner"), Sense::CLICK | Sense::DRAG); corner.context_menu(|ui| crate::menus::ruler_menu_body(app, ui, &mut unit_clicked)); if let Some((id, p)) = unit_clicked { crate::menus::invoke(app, &id, p); diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 06d2964a7c..99ca027cb2 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -178,7 +178,8 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { crumbs.push(Crumb { id: None, is_layer: false, name: pn.clone() }); } let bar = egui::Rect::from_min_size(area.min, vec2(area.width(), 24.0)); - ui.interact(bar, ui.scope_id().with("iso-bar"), Sense::click_and_drag()); + // Keeps the pointer off the canvas; not focusable (`click_and_drag` is), so Tab skips it. + ui.interact(bar, ui.scope_id().with("iso-bar"), Sense::CLICK | Sense::DRAG); ui.painter().rect_filled(bar, 0.0, t.panel); let back = egui::Rect::from_min_size(bar.min + vec2(6.0, 3.0), vec2(18.0, 18.0)); let bresp = ui.interact(back, ui.scope_id().with("iso-back"), Sense::click()); diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 798777d7ea..e021354af6 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -973,6 +973,35 @@ fn isolation_bar_navigation_and_back_button_steps_up() { assert_eq!(app.session.active().unwrap().isolation, Some(NodeId(g2))); } +/// Tab goes to the isolation bar's back button and breadcrumbs and does not stop on the bar +/// behind them, which only keeps the pointer off the canvas. +#[test] +fn tab_skips_the_isolation_bars_background() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let a = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("shape.rectangle", json!({"x": 50, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + app.run("object.isolate", json!({"id": a})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 700.0)); + let mut frame = |events: Vec<egui::Event>| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| { + super::isolation_bar(&mut app, ui, screen); + }); + out.textures_delta.clear(); + }; + frame(vec![]); + let bar = egui::Rect::from_min_size(screen.min, egui::vec2(screen.width(), 24.0)); + let bar = ctx.viewport(|vp| vp.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).find(|w| w.rect == bar).map(|w| w.id)); + let bar = bar.expect("the isolation bar"); + let stops = crate::widgets::accessibility_tests::tab_stops(&ctx, 10, frame); + assert!(!stops.is_empty(), "Tab reaches the back button and the breadcrumbs"); + assert!(!stops.contains(&bar), "{stops:?}"); +} + /// The Control bar's Isolate Selected Object isolates a path inside a group that Direct /// Selection selected, and Exit Isolation Mode leaves with the path selected. Type, symbol /// instances, blends, two objects and an envelope's contents get no isolate button, and pattern diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index b585b2e145..0303db8c6f 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -57,7 +57,8 @@ pub(crate) fn drag_band(ui: &mut egui::Ui, bottom: f32) { // Last frame's rectangle: none while the window measures itself the first time it shows. let Some(outer) = ui.ctx().memory(|m| m.area_rect(id)) else { return }; let band = Rect::from_x_y_ranges(outer.x_range(), outer.top()..=bottom.max(outer.top())); - let r = ui.interact(band, handle(id), egui::Sense::drag()); + // Not focusable (`Sense::drag()` is): Tab goes through the dialog's controls, not the band. + let r = ui.interact(band, handle(id), egui::Sense::DRAG); if r.dragged() { ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); } else if r.hovered() { @@ -66,7 +67,7 @@ pub(crate) fn drag_band(ui: &mut egui::Ui, bottom: f32) { } /// The drag handle of window `id`. -fn handle(id: Id) -> Id { +pub(super) fn handle(id: Id) -> Id { id.with("modal-drag") } diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index 47b95b7ea5..80e403d83a 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -118,6 +118,29 @@ fn dialogs_move_by_their_heading_stay_on_screen_and_where_they_were_moved() { } } +/// Tab goes through a dialog's controls and does not stop on the band that moves the window. +#[test] +fn tab_skips_the_band_that_moves_a_dialog() { + let opens: [(&str, Open, egui::Id); 4] = [ + ("Offset Path", |app| crate::menus::invoke(app, "object.path.offsetPath", json!({})), egui::Id::unique(("dialog", "offsetPath"))), + ("New Document", open_new_document, egui::Id::unique(("dialog", "newDocument"))), + ("Preferences", |app| crate::prefs_dialog::open(app, None), egui::Id::unique("dialog-preferences")), + ("Keyboard Shortcuts", crate::shortcut_editor::open, egui::Id::unique("dialog-shortcuts")), + ]; + for (name, open, id) in opens { + let (ctx, mut app) = (ctx(), app_with_selection()); + open(&mut app); + settle(&ctx, &mut app); + let band = modal::handle(id); + assert!(ctx.read_response(band).is_some(), "{name}: the band is drawn"); + let stops = crate::widgets::accessibility_tests::tab_stops(&ctx, 30, |events| { + frame(&ctx, &mut app, events); + }); + assert!(!stops.is_empty(), "{name}: Tab reaches the dialog's controls"); + assert!(!stops.contains(&band), "{name}: {stops:?}"); + } +} + /// Open the dialog of a plug-in of `kind` (`effect` or `filter`) with `count` number settings over a /// selection, settle it and `check` it, given its window and heading. The other tests share the /// plug-in registry, and the plug-in is removed after. diff --git a/crates/ui-egui/src/tests/ruler_origin.rs b/crates/ui-egui/src/tests/ruler_origin.rs index 01054a0011..dd5a1fcc87 100644 --- a/crates/ui-egui/src/tests/ruler_origin.rs +++ b/crates/ui-egui/src/tests/ruler_origin.rs @@ -110,6 +110,20 @@ fn ruler_origin_double_click_resets_to_the_active_artboard() { assert_eq!(app.ruler_origin(), Point::new(125.0, 90.0)); } +/// Tab does not stop on the rulers or on the box where they meet, which only the pointer uses. +#[test] +fn tab_skips_the_rulers_and_their_origin_box() { + let mut app = app(); + let ctx = context(); + frame(&mut app, &ctx, vec![], canvas::show); + let rulers = ["ruler-top", "ruler-left", "ruler-corner"].map(egui::Id::unique); + assert!(rulers.iter().all(|&id| ctx.read_response(id).is_some()), "the rulers are drawn"); + let stops = crate::widgets::accessibility_tests::tab_stops(&ctx, 20, |events| { + frame(&mut app, &ctx, events, canvas::show); + }); + assert!(!stops.iter().any(|id| rulers.contains(id)), "{stops:?}"); +} + #[test] fn ruler_origin_cancelled_drags_do_not_modify_either_document() { #[derive(Debug, PartialEq)] diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/titlebar.rs index 8f4f4833bb..5f2a128760 100644 --- a/crates/ui-egui/src/titlebar.rs +++ b/crates/ui-egui/src/titlebar.rs @@ -45,7 +45,8 @@ fn toggle_maximize(ctx: &egui::Context) { /// maximize. Call it before laying out the bar so its widgets, registered later, take the clicks. pub fn drag_area(ui: &Ui, rect: Rect) { let ctx = ui.ctx(); - let resp = ui.interact(rect, Id::unique("titlebar-drag"), Sense::click_and_drag()); + // Not focusable (`click_and_drag` is): Tab goes through the bar's widgets, not its background. + let resp = ui.interact(rect, Id::unique("titlebar-drag"), Sense::CLICK | Sense::DRAG); // egui hands a drag that starts on a click-only widget (a menu title) to the drag-sensing // background below it, so remember whether the press itself landed on bare background. if ctx.input(|i| i.pointer.any_pressed()) { @@ -162,7 +163,8 @@ pub fn resize_zones(ui: &mut Ui) { let layer = LayerId::new(Order::Foreground, Id::unique("titlebar-resize")); let zui = ui.new_child(egui::UiBuilder::new().layer_id(layer).max_rect(w)); for (i, (r, dir, cursor)) in zones(w).into_iter().enumerate() { - let resp = zui.interact(r, Id::unique(("titlebar-resize", i)), Sense::drag()).on_hover_cursor(cursor); + // Not focusable (`Sense::drag()` is): Tab does not stop on the zones. + let resp = zui.interact(r, Id::unique(("titlebar-resize", i)), Sense::DRAG).on_hover_cursor(cursor); if resp.drag_started_by(PointerButton::Primary) { ctx.send_viewport_cmd(ViewportCommand::BeginResize(dir)); handed_to_os(&ctx); @@ -391,6 +393,21 @@ mod tests { assert_eq!(w.app.ui.status, "quit"); } + /// Tab goes through the bar's controls and does not stop on the bar's background or on the + /// resize zones, which only the pointer uses. + #[test] + fn tab_skips_the_bar_background_and_the_resize_zones() { + let mut w = Win::new(1000.0); + w.frame(vec![]); + let ctx = w.ctx.clone(); + let stops = crate::widgets::accessibility_tests::tab_stops(&ctx, 40, |events| { + w.frame(events); + }); + assert!(!stops.is_empty(), "Tab reaches the bar's controls"); + let regions: Vec<Id> = std::iter::once(Id::unique("titlebar-drag")).chain((0..8usize).map(|i| Id::unique(("titlebar-resize", i)))).collect(); + assert!(!stops.iter().any(|id| regions.contains(id)), "{stops:?}"); + } + #[test] fn a_move_or_resize_the_window_manager_finished_does_not_block_the_next_resize() { use ResizeDirection::*; diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 32c2ad971a..a766b6a45f 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -153,7 +153,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, cols: usize, floating: Option<egu egui::Rect::from_min_size(hdr.left_top() + vec2(3.0, 2.0), vec2(10.0, 10.0)), if hresp.hovered() { t.text_strong } else { t.text }, ); - let (grip, gresp) = ui.allocate_exact_size(vec2(ui.available_width(), 6.0), Sense::drag()); + // Not focusable (`Sense::drag()` is): only the pointer drags the grip, so Tab does not stop on it. + let (grip, gresp) = ui.allocate_exact_size(vec2(ui.available_width(), 6.0), Sense::DRAG); for k in 0..6 { ui.painter().line_segment( [pos2(grip.center().x - 9.0, grip.top() + 1.5 + k as f32 * 0.6), pos2(grip.center().x + 9.0, grip.top() + 1.5 + k as f32 * 0.6)], @@ -631,7 +632,8 @@ fn flyout_body(ui: &mut Ui, t: &Tokens, active: &str, tools: &[String], floating } else { bar }; - let resp = ui.interact(grip, bar_id(key), Sense::drag()); + // Not focusable (`Sense::drag()` is): only the pointer drags the bar, so Tab does not stop on it. + let resp = ui.interact(grip, bar_id(key), Sense::DRAG); let half = (grip.height() / 2.0 - 3.0).clamp(0.0, 9.0); for k in 0..3 { let x = grip.center().x - 2.0 + k as f32 * 2.0; diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index a1a29f7757..0feb1cabdb 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -995,3 +995,44 @@ fn screen_readers_name_a_flyouts_rows_and_a_floating_strips_buttons() { assert_eq!(role_and_state(&strip, "Put back in the toolbar"), (Role::Button, None)); assert_eq!(role_and_state(&strip, "Drag to move"), (Role::Button, None)); } + +/// Tab goes through the tool buttons and does not stop on the Tools panel's grip, a flyout's +/// tear-off bar or a floating strip's bar, which only the pointer drags. +#[test] +fn tab_skips_the_grip_and_the_tear_off_bars() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let group: Vec<String> = ["rectangle", "roundedRectangle", "ellipse"].map(String::from).to_vec(); + let tools: Vec<String> = ["polygon", "star"].map(String::from).to_vec(); + app.ui.floating_flyouts.push(crate::state::FloatingFlyout { tools, pos: [150.0, 600.0] }); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut time = 0.0; + let mut frame = |events: Vec<Event>| { + time += 0.05; + let screen_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(400.0, 1200.0))); + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), events, screen_rect, ..Default::default() }, |ui| { + app.ui.flyout = Some(0); + ui.data_mut(|d| d.insert_temp(egui::Id::unique("flyout-tools"), group.clone())); + show(&mut app, ui); + }); + out.textures_delta.clear(); + }; + frame(vec![]); + frame(vec![]); + // The grip: the 6 pt strip under the title bar that senses drags and no clicks. + let grip = ctx.viewport(|vp| { + vp.prev_pass + .widgets + .layers() + .flat_map(|(_, w)| w.iter()) + .find(|w| w.rect.height() == 6.0 && w.sense.senses_drag() && !w.sense.senses_click()) + .map(|w| w.id) + }); + let grip = grip.expect("the Tools panel's grip"); + let stops = crate::widgets::accessibility_tests::tab_stops(&ctx, 120, frame); + assert!(!stops.is_empty(), "Tab reaches the tool buttons"); + for (name, id) in [("the grip", grip), ("the flyout's bar", bar_id("rectangle")), ("the strip's bar", bar_id("polygon"))] { + assert!(!stops.contains(&id), "Tab stops on {name}: {stops:?}"); + } +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 30a6fa2b71..5b2773259d 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -117,6 +117,19 @@ pub(crate) mod accessibility_tests { nodes } + /// The widgets that `tabs` presses of Tab give the keyboard focus to, in order. `frame` runs + /// one frame of `ctx` with the events it is given. + pub(crate) fn tab_stops(ctx: &egui::Context, tabs: usize, mut frame: impl FnMut(Vec<egui::Event>)) -> Vec<egui::Id> { + let tab = egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let mut stops = vec![]; + for _ in 0..tabs { + frame(vec![tab.clone()]); + frame(vec![]); + stops.extend(ctx.memory(|m| m.focused())); + } + stops + } + /// The node of `tree` that screen readers name `label`. pub(crate) fn named<'a>(tree: &'a [Node], label: &str) -> &'a Node { tree.iter().find(|n| n.label() == Some(label)).unwrap_or_else(|| panic!("nothing is named {label:?}")) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index af17606c0e..2adeb29a5d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -580,6 +580,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With anchor points selected with Direct Selection, the contextual task bar offers Remove Anchor Points, Connect (`path.join`), Cut Path, Corner and Smooth (`path.convertAnchors` with `to` set to `corner` or `smooth`), the commands of the Control bar's anchor buttons. As in Illustrator, whose bar has items that delete the selected anchors, join selected end points, split the path at the selected anchors, and make the selected anchors corner or smooth points ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Not done: Simplify, which the bar offers only while no anchors are selected, and the bar's Smooth item that adjusts a path's curvature, a command the app doesn't have (Object › Path › Smooth). - Tool flyouts tear off: dragging or clicking the tear-off bar on a flyout's right side (or releasing the long press over it) floats its group as a strip of tool buttons, moved by the same bar and put back in the toolbar by the × at its top (`window.floatTools`). While a group floats, the presses that would open its flyout raise the strip instead. Floating strips are kept with the preferences and in user workspaces. Not done: turning a strip vertical, docking it. - Screen readers get a name for the Tools panel's tool buttons, flyout rows, floating strips and tear-off bars, and for the icon buttons, text buttons, toggles, checkboxes, radio buttons, tabs, chips, sliders, angle dials and combo boxes that panels and dialogs draw with `crates/ui-egui/src/widgets.rs`: the text, label or tool tip each one shows, or a name of its own where it shows none (the angle dial, the spinner, the preset arrow, the color wheel and the Reference Point's squares). The tool buttons, toggles, checkboxes, radio buttons, tabs and the Reference Point's nine squares also report whether they are on, an icon button that is lit, such as the chosen Align To button, reports that it is pressed, and the angle dial reports its angle. The status bar's First, Previous, Next and Last Artboard buttons have tool tips. + - Tab does not stop on the regions that only the pointer uses: the custom title bar's background and the window's resize zones, the band at the top of a dialog that moves it, the Tools panel's grip, a flyout's and a floating strip's tear-off bar, the isolation bar's background, and the rulers and the box where they meet. - These dialog sliders, each beside a number field, respond to the keyboard: those of the effect, tool option, brush and transform dialogs, the Perspective Grid, the 3D dialogs, and the flattener options, which the Flattener Preview panel also shows. A click, or Tab, gives a slider the keyboard focus, and an outline shows it. Then → and ↑ step the field's number up to the next whole number and ← and ↓ step it down to the next whole number, Shift with an arrow and Page Up and Page Down step it by ten, and Home and End set the slider's first and last value; no step goes past either end. Screen readers' increment and decrement actions step the slider as → and ← do. The Color panel's, Swatch Options', the Navigator's and the Character panel's sliders, and the Color Picker's channel slider, respond only to the pointer. The keys follow the WAI-ARIA slider pattern (<https://www.w3.org/WAI/ARIA/apg/patterns/slider/>); the reference app's help does not describe keys on a dialog's slider, so the step sizes are VectorCraft's own. - Screen readers get the value of the color and channel sliders that panels and dialogs draw (the Color panel, the Color Picker, Swatch Options, the Navigator's Zoom, the Character panel's variable font axes, the Perspective Grid and flattener options, and the sliders of the effect, tool option and transform dialogs): the number and text of the field beside each one, such as 128 for G or 50% for an opacity, with the slider's range, which extends to include a number past the slider's end. The harmony wheel's Brightness slider, which has no field, reports its brightness in percent. - Panels undock (#495): a dock tab, a panel icon or a popped-out panel's title dragged out of the dock floats that panel (in an OS window of its own on the desktop, #4135), and the strip right of the dock's tabs floats the whole tabbed group. A floating group moves by its title bar, a tab dragged out of it floats on its own, and dropped on another group's title bar or tabs it stacks with that group; dropped on a dock group's tabs, which light up under the pointer, its panels join that group, and on the group's upper or lower half they make a new group above or below it (`window.panel.dock {anchor, zone}`); dropped on the icon column they become icons there, the tabbed group's panels too (`window.panel.dock {icon: true}`); dropped anywhere else on the dock, which lights up, they go back where they live (the tabbed group or the icon column), as its × and the panel menus' Float Panel / Dock Panel do (`window.panel.float`, `window.panel.dock`). The Tools panel floats by its title bar and docks again on the window's left edge. Floating groups stack into sets: dropped on the upper or lower half of another group (a line shows where), a group joins it right above or below it, and the set's groups stack top to bottom, each showing one panel, moving together by the top group's title bar, whose × docks them all; a group dragged by its tab strip leaves the set (`window.panel.float {below, above}`). A double-click on a tab collapses a floating group to its tabs (`collapsed`), and a dock group too, a group below it moving up into the room; a second double-click, or a click on another of its tabs, expands it (`window.panel.collapse`, kept with the preferences and in saved workspaces). Sets dropped on the left edge of the icon column or of another dock column dock as dock columns (a multi-column dock, `window.panel.dock {column}`), whose groups stack, tab and tear out as a floating set's do, and whose top strip floats the column again. Floating panels, their sets and the Tools panel's position are kept with the preferences and in user workspaces, and clamped into a smaller window. Not done: panels in separate OS windows, reordering tabs by dragging, collapsing a set or dock column to icons, dock columns right of the default dock, resizing floating panels and the groups of a set. From d2d431552449c47aaff6814537a3508c09e744cb Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 09:37:09 -0700 Subject: [PATCH 157/260] .ai import: a Zstandard frame that ends in a zero byte keeps it The reader cut every trailing zero byte off the Zstandard editing data before decoding it, to drop the padding after the last frame. A frame can end in a zero byte itself (a raw or RLE block, or a checksum whose last byte is zero), and cutting it left the frame short, so the file failed to open with "its Zstandard compression is damaged". The reader now decodes frame after frame and stops when only zeros are left. --- crates/eps/src/import/ai.rs | 8 ++++---- crates/eps/src/import/ai/tests.rs | 13 +++++++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 291171f783..5e60e7e81f 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -158,11 +158,11 @@ impl Codec { flate2::read::ZlibDecoder::new(data).take(max + 1).read_to_end(&mut out).map_err(|_| damaged("its zlib compression"))?; } Codec::Zstd => { - // The data may be several frames one after the other, padded with zeros. - let end = data.iter().rposition(|b| *b != 0).map_or(0, |i| i + 1); - let mut src = data.get(..end).unwrap_or_default(); + // The data may be several frames one after the other, padded with zeros. A frame + // can itself end in a zero byte, so the padding is what is left after the last frame. + let mut src = data; let mut frames = 0usize; - while !src.is_empty() { + while src.iter().any(|b| *b != 0) { frames += 1; if frames > MAX_FRAMES { return Err(damaged("its Zstandard compression")); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index cfb6d2b347..34b35e13e4 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -1472,6 +1472,19 @@ fn many_zstandard_frames_are_read_in_one_pass_and_capped() { assert!(started.elapsed() < std::time::Duration::from_secs(20), "{:?}", started.elapsed()); } +/// A Zstandard frame that ends in a zero byte keeps it: only the zeros after the last frame are +/// padding. +#[test] +fn a_zstandard_frame_ending_in_a_zero_byte_is_read_whole() { + // Magic number, a single-segment header with a 1-byte content size of 3, and one raw block + // (last, 3 bytes) holding `ab` and a zero byte. + let frame = [0x28, 0xB5, 0x2F, 0xFD, 0x20, 3, 0x19, 0, 0, b'a', b'b', 0]; + for padding in [0, 64] { + let raw = [&b"%AI24_ZStandard_Data"[..], &frame, &frame, &vec![0; padding]].concat(); + assert_eq!(decode_private(&raw).unwrap(), b"ab\0ab\0"); + } +} + #[test] fn closing_brackets_without_their_opening_dont_rescan_the_stack() { let n = 200_000; From db6c5ea9df62e428be57a00ddeae030e47ffca8f Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 09:11:43 -0700 Subject: [PATCH 158/260] Fix #2678: Ungroup no longer multiplies the group's opacity into its members Ungroup multiplied each member's opacity by the group's, so a member of a 50% group stayed at 50% after the group was gone, and members that overlapped showed through each other. Each member now keeps its own opacity, and the group's opacity is removed with the group. --- crates/engine/src/cmd/object/arrange.rs | 2 +- crates/engine/src/tests/containers.rs | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index 741475d87f..9cafae899a 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -129,7 +129,7 @@ pub(super) fn ungroup(s: &mut Session, _: &Value) -> Result<Value> { { *clipping = false; } - c.opacity *= n.opacity; + // Each member keeps its own opacity; the group's opacity goes with the group. new_sel.push(c.id); out.push(c); } diff --git a/crates/engine/src/tests/containers.rs b/crates/engine/src/tests/containers.rs index aa72ebeccf..1b147ecc1e 100644 --- a/crates/engine/src/tests/containers.rs +++ b/crates/engine/src/tests/containers.rs @@ -69,6 +69,28 @@ fn a_group_fill_paints_both_members_and_the_contents_slot_moves() { assert!(s.execute("appearance.moveItem", &json!({"from": "contents", "to": 1})).is_err()); } +#[test] +fn ungroup_leaves_the_groups_opacity_with_the_group() { + let mut s = session(); + let red = id_of(&run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 40}))); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + let blue = id_of(&run(&mut s, "shape.rectangle", json!({"x": 100, "y": 20, "width": 60, "height": 40}))); + run(&mut s, "paint.setFill", json!({"color": "#0000ff"})); + run(&mut s, "object.setProps", json!({"ids": [blue.0], "opacity": 40})); + run(&mut s, "select.set", json!({"ids": [red.0, blue.0]})); + let g = id_of(&run(&mut s, "object.group", json!({}))); + run(&mut s, "object.setProps", json!({"ids": [g.0], "opacity": 50})); + run(&mut s, "object.ungroup", json!({})); + // Each member keeps its own opacity: the red square is opaque again and the blue one stays at 40%. + assert!((node(&s, red).opacity - 1.0).abs() < 1e-6, "{}", node(&s, red).opacity); + assert!((node(&s, blue).opacity - 0.4).abs() < 1e-6, "{}", node(&s, blue).opacity); + assert_eq!(pixel(&s, 40, 40), RED); + // One undo step brings the group back at 50%. + run(&mut s, "edit.undo", json!({})); + assert!((node(&s, g).opacity - 0.5).abs() < 1e-6); + assert!((node(&s, red).opacity - 1.0).abs() < 1e-6); +} + #[test] fn appearance_commands_target_the_object_or_its_contents() { let mut s = session(); From 7ad5ee0dffecb20cd3a5f60fc21c9cddf01a441a Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 00:40:20 +0700 Subject: [PATCH 159/260] Fix #4931: native Save As Version is a menu of the versions VectorCraft writes --- crates/ui-egui/src/dialogs/save_options.rs | 62 ++++++++++++++++--- .../ui-egui/src/dialogs/save_options/tests.rs | 24 +++++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + 28 files changed, 105 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/save_options.rs b/crates/ui-egui/src/dialogs/save_options.rs index cbf450a6aa..8ee5de9c99 100644 --- a/crates/ui-egui/src/dialogs/save_options.rs +++ b/crates/ui-egui/src/dialogs/save_options.rs @@ -7,12 +7,13 @@ //! editable), `path`, `format`, and one field per option (agents set them with `ui.dialog.set`). //! Native and `.ai` files show their save options (VectorCraft Options after Save As): each //! artboard to a separate file, with `all` (true: every artboard) or `range`, Include Linked Files, -//! Embed ICC Profiles, Create PDF-Compatible File and Use Compression. A `.ai` file's Version comes -//! first: PDF-compatible, or legacy version 7 (`aiVersion: "7"`, a file per artboard), which takes -//! only Transparent Images (`transparentImages`), Hidden Objects (`hiddenObjects`: a hidden layer, -//! omitted or made visible), Text (`outlineText`: editable or outlines) and, with several -//! artboards, a picker of the artboards to save (thumbnails to check, field `boards`, saved as -//! `range`). +//! Embed ICC Profiles, Create PDF-Compatible File and Use Compression. A native file's Version is a +//! menu of the versions VectorCraft writes (`version`, named by the releases that read each). A +//! `.ai` file's Version comes first: PDF-compatible, or legacy version 7 (`aiVersion: "7"`, a file +//! per artboard), which takes only Transparent Images (`transparentImages`), Hidden Objects +//! (`hiddenObjects`: a hidden layer, omitted or made visible), Text (`outlineText`: editable or +//! outlines) and, with several artboards, a picker of the artboards to save (thumbnails to check, +//! field `boards`, saved as `range`). use std::sync::OnceLock; @@ -342,6 +343,10 @@ fn option_row(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, o: &Forma ui.end_row(); return; } + if o.name == "version" && o.ty == "integer" { + native_version(ui, d, o); + return; + } if o.name == "transparentImages" { ui.label(egui::RichText::new(tl!("Transparent Images:")).color(t.text_dim)).on_hover_text(o.description); let choices = [tl!("Flatten"), tl!("Omit")]; @@ -379,7 +384,9 @@ fn option_row(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, o: &Forma if o.ty == "boolean" { ui.label(""); let on = value.as_bool().unwrap_or(false); - if widgets::check_tip(ui, label.trim_end_matches(':'), on, true, o.description) { + // Versions older than compression read only plain files. + let enabled = o.name != "compress" || !uncompressed(d); + if widgets::check_tip(ui, label.trim_end_matches(':'), on && enabled, enabled, o.description) { d.fields.insert(o.name.into(), json!(!on)); } ui.end_row(); @@ -412,6 +419,43 @@ fn option_row(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, o: &Forma ui.end_row(); } +/// The native versions VectorCraft writes, newest first, each with the first release that reads +/// it (the format version each release tag writes: 2 in 0.1, 3 from 0.2, 4 from 0.8). +const NATIVE_VERSIONS: [(u32, &str); 4] = [(4, "0.8"), (3, "0.2"), (2, "0.1"), (1, "0.1")]; + +/// A native file's Version (#4931): a menu of the versions VectorCraft writes, named by the +/// releases that read them, so a version it can't write can't be chosen. A version without +/// compression turns Use Compression off. +fn native_version(ui: &mut egui::Ui, d: &mut Dialog, o: &FormatOption) { + let t = Tokens::get(ui.ctx()); + ui.label(egui::RichText::new(tl!("Version:")).color(t.text_dim)).on_hover_text(o.description); + let names: Vec<String> = NATIVE_VERSIONS + .iter() + .map(|(n, release)| crate::i18n::fmt(tl!("VectorCraft {release} and later (version {n})"), &[("release", release), ("n", &n.to_string())])) + .collect(); + let names: Vec<&str> = names.iter().map(String::as_str).collect(); + let at = NATIVE_VERSIONS.iter().position(|(n, _)| *n == native_version_of(d)).unwrap_or(0); + if let Some(i) = widgets::dropdown_names(ui, ("save-option", o.name), names.get(at).copied().unwrap_or_default(), &names, 254.0) + && let Some((n, _)) = NATIVE_VERSIONS.get(i) + { + d.fields.insert(o.name.into(), json!(n)); + if *n < vectorcraft_format::COMPRESSED_SINCE { + d.fields.insert("compress".into(), json!(false)); + } + } + ui.end_row(); +} + +/// The native version the dialog will write (the current one unless chosen). +fn native_version_of(d: &Dialog) -> u32 { + d.fields.get("version").and_then(Value::as_u64).and_then(|v| u32::try_from(v).ok()).unwrap_or(vectorcraft_format::VERSION) +} + +/// Is a native file to be saved in a version that can't be compressed? +fn uncompressed(d: &Dialog) -> bool { + native_version_of(d) < vectorcraft_format::COMPRESSED_SINCE +} + /// Web Save As: another format brings its own options and file extension. fn switch_format(app: &mut VectorcraftApp, d: &mut Dialog, id: &str) { let (Some(old), Some(new)) = (fileio::format(&d.str("format")), fileio::format(id)) else { return }; @@ -444,6 +488,10 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { .iter() .filter_map(|o| d.fields.get(o.name).filter(|v| !v.is_null() && v.as_str() != Some("")).map(|v| (o.name.to_string(), v.clone()))) .collect(); + if uncompressed(d) { + // Use Compression shows off there, whatever it held before. + options.remove("compress"); + } if legacy_ai(d) { // The artboards checked in the picker (all of them: no range). options.remove("range"); diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index fe46331a5e..9ec00b494b 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -347,3 +347,27 @@ fn eps_save_as_keeps_page_options_and_writes_eps_without_export_only_switches() assert!(vectorcraft_eps::native(&saved[0].1).is_some()); assert_eq!(app.session.active().unwrap().format, "eps"); } + +/// #4931: a native file's Version is a menu of the versions VectorCraft writes, the current one +/// first and chosen, each named by the releases that read it. An older version without +/// compression saves plain, whatever Use Compression held. +#[test] +fn native_version_is_a_menu_of_the_versions_vectorcraft_writes() { + let listed: Vec<u32> = NATIVE_VERSIONS.iter().map(|(n, _)| *n).collect(); + let writable: Vec<u32> = (vectorcraft_format::MIN_VERSION..=vectorcraft_format::VERSION).rev().collect(); + assert_eq!(listed, writable, "every version VectorCraft writes, newest first"); + let (mut app, written, _) = desktop("art.vectorcraft"); + assert_eq!(app.run("file.saveAs", json!({})).unwrap()["pending"], KIND); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx())); + assert!(text.contains("VectorCraft 0.8 and later (version 4)"), "{text}"); + assert_eq!(native_version_of(dialog(&app)), vectorcraft_format::VERSION); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("version".into(), json!(2)); + d.fields.insert("compress".into(), json!(true)); + assert!(uncompressed(d)); + frame(&mut app, true); + assert!(app.ui.dialog.is_none(), "saved: {}", app.ui.status); + let (_, bytes) = written.borrow()[0].clone(); + let head = String::from_utf8_lossy(&bytes[..bytes.len().min(200)]).to_string(); + assert!(head.contains("\"version\": 2") || head.contains("\"version\":2"), "{head}"); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 83697b7f32..59c231102d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5926,3 +5926,4 @@ breakText Glyphs Глифи Set Size of Each Задаване на размер на всеки @msg select exactly two objects изберете точно два обекта @msg give `width` or `height` задайте `width` или `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} и по-нови (версия {n}) diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 3a737414db..5714219657 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5960,3 +5960,4 @@ shape Open Otvoren Set Size of Each Postavi veličinu svakog @msg select exactly two objects odaberite tačno dva objekta @msg give `width` or `height` zadajte `width` ili `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} i novije (verzija {n}) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c04ca4698a..95c59b92cd 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6033,3 +6033,4 @@ breakText Glyphs Glifs Set Size of Each Defineix la mida de cadascun @msg select exactly two objects selecciona exactament dos objectes @msg give `width` or `height` indica `width` o `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} i posteriors (versió {n}) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 558384bb23..0768ea6c88 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6042,3 +6042,4 @@ breakText Glyphs Glyfy Set Size of Each Nastavit velikost jednotlivě @msg select exactly two objects vyberte právě dva objekty @msg give `width` or `height` zadejte `width` nebo `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} a novější (verze {n}) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4914683cc4..170f4d4b9a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5940,3 +5940,4 @@ breakText Glyphs Glyffer Set Size of Each Angiv størrelse for hver @msg select exactly two objects markér præcis to objekter @msg give `width` or `height` angiv `width` eller `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} og nyere (version {n}) diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index aa374c33be..21734d6b48 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5628,3 +5628,4 @@ breakText Glyphs Glyphen Set Size of Each Größe einzeln festlegen @msg select exactly two objects wählen Sie genau zwei Objekte aus @msg give `width` or `height` geben Sie `width` oder `height` an + VectorCraft {release} and later (version {n}) VectorCraft {release} und neuer (Version {n}) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index f1758e7a4f..b3b5e9f979 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5995,3 +5995,4 @@ breakText Glyphs Γλύφοι Set Size of Each Ορισμός μεγέθους καθενός @msg select exactly two objects επιλέξτε ακριβώς δύο αντικείμενα @msg give `width` or `height` δώστε `width` ή `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} και νεότερες (έκδοση {n}) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index bc7ddaf56c..1e4a8fd9b6 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5985,3 +5985,4 @@ breakText Glyphs Glifos Set Size of Each Definir el tamaño de cada uno @msg select exactly two objects selecciona exactamente dos objetos @msg give `width` or `height` indica `width` o `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} y posteriores (versión {n}) diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1d6fd7c02c..540800b588 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6073,3 +6073,4 @@ breakText Glyphs Merkit Set Size of Each Aseta kunkin koko @msg select exactly two objects valitse täsmälleen kaksi objektia @msg give `width` or `height` anna `width` tai `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} ja uudemmat (versio {n}) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3e23421335..f171df8dbf 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6040,3 +6040,4 @@ breakText Glyphs Glyphes Set Size of Each Définir la taille de chaque objet @msg select exactly two objects sélectionnez exactement deux objets @msg give `width` or `height` indiquez `width` ou `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} et ultérieures (version {n}) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 10be9ac87f..7070071b07 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6029,3 +6029,4 @@ breakText Glyphs Glifák Set Size of Each Egyenkénti méret beállítása @msg select exactly two objects jelölj ki pontosan két objektumot @msg give `width` or `height` add meg a `width` vagy a `height` értéket + VectorCraft {release} and later (version {n}) VectorCraft {release} és újabb (verzió: {n}) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 53927a0206..4276a98f2a 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5940,3 +5940,4 @@ breakText Glyphs Glif Set Size of Each Atur ukuran masing-masing @msg select exactly two objects pilih tepat dua objek @msg give `width` or `height` berikan `width` atau `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} dan yang lebih baru (versi {n}) diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index d48cb24f5f..9daf34aec4 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5662,3 +5662,4 @@ breakText Glyphs Glifi Set Size of Each Imposta dimensione di ciascuno @msg select exactly two objects seleziona esattamente due oggetti @msg give `width` or `height` indica `width` o `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} e successive (versione {n}) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index cd1d86f4d5..008940f123 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5728,3 +5728,4 @@ breakText Glyphs 字形 Set Size of Each 個別にサイズを設定 @msg select exactly two objects オブジェクトをちょうど 2 つ選択してください @msg give `width` or `height` `width` または `height` を指定してください + VectorCraft {release} and later (version {n}) VectorCraft {release} 以降 (バージョン {n}) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 798b57b0b0..a32250773c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6032,3 +6032,4 @@ breakText Glyphs გლიფები Set Size of Each თითოეულის ზომის დაყენება @msg select exactly two objects მონიშნეთ ზუსტად ორი ობიექტი @msg give `width` or `height` მიუთითეთ `width` ან `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} და უფრო ახალი (ვერსია {n}) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 38eb0dad0b..a2c3ea0e9d 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5625,3 +5625,4 @@ breakText Glyphs 글리프 Set Size of Each 각각 크기 설정 @msg select exactly two objects 개체를 정확히 두 개 선택하세요 @msg give `width` or `height` `width` 또는 `height`를 지정하세요 + VectorCraft {release} and later (version {n}) VectorCraft {release} 이상 (버전 {n}) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 2a56400a2a..26a3a0c490 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5984,3 +5984,4 @@ breakText Glyphs Glyphs Set Size of Each Formaat van elk instellen @msg select exactly two objects selecteer precies twee objecten @msg give `width` or `height` geef `width` of `height` op + VectorCraft {release} and later (version {n}) VectorCraft {release} en nieuwer (versie {n}) diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 1b8e322eb8..7a71813b07 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5898,3 +5898,4 @@ breakText Glyphs Glify Set Size of Each Ustaw rozmiar każdego @msg select exactly two objects zaznacz dokładnie dwa obiekty @msg give `width` or `height` podaj `width` lub `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} i nowsze (wersja {n}) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index f64b2436d9..e206114885 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5962,3 +5962,4 @@ breakText Glyphs Glifos Set Size of Each Definir Tamanho de Cada Um @msg select exactly two objects selecione exatamente dois objetos @msg give `width` or `height` informe `width` ou `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} e posteriores (versão {n}) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 816096e51f..414f43d29a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6020,3 +6020,4 @@ breakText Glyphs Глифы Set Size of Each Задать размер каждого @msg select exactly two objects выделите ровно два объекта @msg give `width` or `height` укажите `width` или `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} и новее (версия {n}) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 46e4bd8445..46d0eb2262 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6095,3 +6095,4 @@ breakText Glyphs Glyfer Set Size of Each Ange storlek för vart och ett @msg select exactly two objects markera exakt två objekt @msg give `width` or `height` ange `width` eller `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} och senare (version {n}) diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 1c2feb846a..c40b948f1e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6000,3 +6000,4 @@ breakText Glyphs Glifler Set Size of Each Her Birinin Boyutunu Ayarla @msg select exactly two objects tam olarak iki nesne seç @msg give `width` or `height` `width` veya `height` belirt + VectorCraft {release} and later (version {n}) VectorCraft {release} ve sonrası (sürüm {n}) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 05f4ffe480..e92094241a 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5642,3 +5642,4 @@ breakText Glyphs Гліфи Set Size of Each Задати розмір кожного @msg select exactly two objects виділіть рівно два об’єкти @msg give `width` or `height` укажіть `width` або `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} і новіші (версія {n}) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index b2744f443a..44fffd0ce1 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5644,3 +5644,4 @@ breakText Glyphs Glyph Set Size of Each Đặt kích thước từng cái @msg select exactly two objects hãy chọn đúng hai đối tượng @msg give `width` or `height` hãy cho `width` hoặc `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} trở lên (phiên bản {n}) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index cfea6e224d..cb2d7558bc 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5884,3 +5884,4 @@ breakText Glyphs 字形 Set Size of Each 分别设置大小 @msg select exactly two objects 请恰好选择两个对象 @msg give `width` or `height` 请提供 `width` 或 `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} 及更高版本 (版本 {n}) diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 0605652e52..31a2d1dbe5 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5681,3 +5681,4 @@ breakText Glyphs 字符 Set Size of Each 個別設定大小 @msg select exactly two objects 請選取正好兩個物件 @msg give `width` or `height` 請提供 `width` 或 `height` + VectorCraft {release} and later (version {n}) VectorCraft {release} 及更新版本 (版本 {n}) From 78d801395a1491a1c1e429748c85bf8b55f74787 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 00:41:27 +0700 Subject: [PATCH 160/260] Fix #4933: a save refused before writing shows the Can't save alert --- .../ui-egui/src/dialogs/save_options/tests.rs | 19 +++++++++++++++++++ crates/ui-egui/src/io/save.rs | 11 ++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index 9ec00b494b..e5483a935f 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -371,3 +371,22 @@ fn native_version_is_a_menu_of_the_versions_vectorcraft_writes() { let head = String::from_utf8_lossy(&bytes[..bytes.len().min(200)]).to_string(); assert!(head.contains("\"version\": 2") || head.contains("\"version\":2"), "{head}"); } + +/// #4933: a save refused before anything is written (here a version agents can still set) says +/// so in the "Can't save" alert, in the reason's words without the command's, and writes nothing. +#[test] +fn a_refused_save_says_so_in_an_alert() { + let (mut app, written, _) = desktop("art.vectorcraft"); + assert_eq!(app.run("file.saveAs", json!({})).unwrap()["pending"], KIND); + app.ui.dialog.as_mut().unwrap().fields.insert("version".into(), json!(55)); + frame(&mut app, false); + frame(&mut app, true); + let d = dialog(&app); + assert_eq!( + (d.kind.as_str(), d.str("message").as_str(), d.str("detail").as_str()), + (crate::dialogs::confirm::MESSAGE, "Can't save “art.vectorcraft”.", "can't save version 55: VectorCraft writes versions 1 to 4") + ); + assert!(written.borrow().is_empty()); + let st = app.session.active().unwrap(); + assert!(st.is_dirty() && st.path.is_none(), "not saved"); +} diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index b9e2ddeedd..72e45c0b03 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -398,7 +398,16 @@ fn write_plan(app: &mut VectorcraftApp, plan: SavePlan) -> Result<Value, String> if app.background.busy_with(uid) { background::wait_all(app); } - let job = fileio::save_job(&mut app.session, plan).map_err(|e| e.to_string())?; + let refused = plan.path.clone().unwrap_or_else(|| plan.name.clone()); + // Refused before writing (#4933): told as a failed write is, in the reason's own words. + let job = fileio::save_job(&mut app.session, plan).map_err(|e| { + let reason = match &e { + EngineError::BadParams { msg, .. } => msg.clone(), + e => e.to_string(), + }; + report_write_error(app, false, &refused, &reason); + e.to_string() + })?; let (retargets, target) = (job.plan().retargets(), job.plan().path.clone()); let (format, warnings) = (job.plan().format.id, job.known_warnings()); let label = match &target { From 6caa2f74ef10fc1ba9af4a899078d22d2189e6c1 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 00:43:11 +0700 Subject: [PATCH 161/260] =?UTF-8?q?Fix=20#4944:=20About=20=E2=80=BA=20Cont?= =?UTF-8?q?ributors=20table=20keeps=20its=20header=20above=20the=20scrolli?= =?UTF-8?q?ng=20rows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-egui/src/credits.rs | 153 +++++++++++++++++++++++++--------- 1 file changed, 112 insertions(+), 41 deletions(-) diff --git a/crates/ui-egui/src/credits.rs b/crates/ui-egui/src/credits.rs index 35d014dc33..440f94c6e5 100644 --- a/crates/ui-egui/src/credits.rs +++ b/crates/ui-egui/src/credits.rs @@ -263,22 +263,25 @@ pub fn contributors_ui(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let counts = crate::i18n::fmt(tl!("{people} contributors · {commits} commits"), &[("people", &people), ("commits", &commits)]); ui.label(RichText::new(counts).small().weak()); ui.separator(); - egui::ScrollArea::both().max_height(SCROLL_HEIGHT).auto_shrink([false, true]).show(ui, |ui| { - if list.is_empty() { - ui.label(tl!("No contributor data was built into this copy.")); - } else if v.table { - table(app, ui, &list, &mut v); - } else { - ui.horizontal_wrapped(|ui| { - for (i, c) in list.iter().enumerate() { - if i > 0 { - ui.label(RichText::new("·").weak()); + if v.table && !list.is_empty() { + // The table scrolls its rows under its header itself, and sideways as a whole. + egui::ScrollArea::horizontal().auto_shrink([false, true]).show(ui, |ui| table(app, ui, &list, &mut v)); + } else { + egui::ScrollArea::both().max_height(SCROLL_HEIGHT).auto_shrink([false, true]).show(ui, |ui| { + if list.is_empty() { + ui.label(tl!("No contributor data was built into this copy.")); + } else { + ui.horizontal_wrapped(|ui| { + for (i, c) in list.iter().enumerate() { + if i > 0 { + ui.label(RichText::new("·").weak()); + } + link(app, ui, c, v.names); } - link(app, ui, c, v.names); - } - }); - } - }); + }); + } + }); + } ui.data_mut(|d| d.insert_temp(id, v)); } @@ -291,34 +294,55 @@ fn link(app: &mut VectorcraftApp, ui: &mut egui::Ui, c: &Contributor, names: Nam r } +/// The contributors as a table whose header row, the sort buttons, stays above the rows as they +/// scroll (#4944). fn table(app: &mut VectorcraftApp, ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) { - egui::Grid::new("credits_table").striped(true).num_columns(SortKey::ALL.len()).show(ui, |ui| { - for k in SortKey::ALL { - let arrow = if v.key == k { if v.ascending { " ▲" } else { " ▼" } } else { "" }; - if ui.button(RichText::new(format!("{}{arrow}", k.label().1)).strong()).on_hover_text(k.label().0).clicked() { - if v.key == k { - v.ascending = !v.ascending; - } else { - v.key = k; - v.ascending = k.default_ascending(); - } + let (row, names) = (ui.spacing().interact_size.y, v.names); + egui_extras::TableBuilder::new(ui) + .id_salt("credits_table") + .striped(true) + .columns(egui_extras::Column::auto(), SortKey::ALL.len()) + .max_scroll_height(SCROLL_HEIGHT - row) + .header(row, |mut header| { + for k in SortKey::ALL { + header.col(|ui| { + let arrow = if v.key == k { if v.ascending { " ▲" } else { " ▼" } } else { "" }; + if ui.button(RichText::new(format!("{}{arrow}", k.label().1)).strong()).on_hover_text(k.label().0).clicked() { + if v.key == k { + v.ascending = !v.ascending; + } else { + v.key = k; + v.ascending = k.default_ascending(); + } + } + }); } - } - ui.end_row(); - for c in list { - link(app, ui, c, v.names); - ui.label(group(c.prs)); - ui.label(group(c.commits)); - ui.label(group(c.lines_added)); - ui.label(group(c.lines_deleted)); - ui.label(signed(c.lines_delta())); - ui.label(group(c.binary_added)); - ui.label(group(c.binary_deleted)); - ui.label(day(c.first_commit)); - ui.label(day(c.last_commit)); - ui.end_row(); - } - }); + }) + .body(|mut body| { + for c in list { + body.row(row, |mut r| { + r.col(|ui| { + link(app, ui, c, names); + }); + let cells = [ + group(c.prs), + group(c.commits), + group(c.lines_added), + group(c.lines_deleted), + signed(c.lines_delta()), + group(c.binary_added), + group(c.binary_deleted), + day(c.first_commit).to_string(), + day(c.last_commit).to_string(), + ]; + for text in cells { + r.col(|ui| { + ui.label(text); + }); + } + }); + } + }); } /// About ▸ Models: AI models credited in Co-Authored-By trailers. @@ -423,4 +447,51 @@ mod tests { assert_eq!(day("2026-10-07T18:45:23Z"), "2026-10-07"); assert_eq!(day(""), "—"); } + + /// #4944: in the table, the header row (the sort buttons) stays put while the rows scroll + /// under it. + #[test] + fn the_table_header_stays_above_scrolling_rows() { + let first = sorted(CONTRIBUTORS, NameMode::Username, SortKey::FirstCommit, true).first().map(|c| c.name(NameMode::Username)).unwrap(); + assert!(CONTRIBUTORS.len() > 30, "enough rows to scroll"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.data_mut(|d| d.insert_temp(egui::Id::unique("credits_view"), View { table: true, ..View::default() })); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let mut time = 0.0; + // Where the frame painted `text`, if it did. + let mut frame = |events: Vec<egui::Event>, find: &[&str]| { + time += 0.1; + let input = egui::RawInput { events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + ui.set_width(660.0); + contributors_ui(&mut app, ui); + }); + out.textures_delta.clear(); + let at = |text: &str| { + out.shapes.iter().find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text() == text => Some(t.pos), + _ => None, + }) + }; + find.iter().map(|t| at(t)).collect::<Vec<_>>() + }; + frame(vec![], &[]); + let before = frame(vec![], &["PRs", &first]); + let (Some(header), Some(row)) = (before[0], before[1]) else { panic!("header and first row painted: {before:?}") }; + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -200.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + frame(vec![egui::Event::PointerMoved(row + egui::vec2(4.0, 4.0)), wheel], &[]); + let mut after = vec![]; + for _ in 0..10 { + after = frame(vec![], &["PRs", &first]); + } + assert_eq!(after[0], Some(header), "the header stays where it was"); + assert!(after[1].is_none_or(|p| p.y < row.y), "the rows scrolled: {:?} from {row:?}", after[1]); + } } From 14c46162027a0ed094fcdec349800e34f52c4227 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 00:45:18 +0700 Subject: [PATCH 162/260] Fix #4953: the Gradient panel's freeform point swatch opens the point's popover --- crates/ui-egui/src/i18n/bg.tsv | 2 +- crates/ui-egui/src/i18n/bs.tsv | 2 +- crates/ui-egui/src/i18n/ca.tsv | 2 +- crates/ui-egui/src/i18n/cs.tsv | 2 +- crates/ui-egui/src/i18n/da.tsv | 2 +- crates/ui-egui/src/i18n/de.tsv | 2 +- crates/ui-egui/src/i18n/el.tsv | 2 +- crates/ui-egui/src/i18n/es.tsv | 2 +- crates/ui-egui/src/i18n/fi.tsv | 2 +- crates/ui-egui/src/i18n/fr.tsv | 2 +- crates/ui-egui/src/i18n/hu.tsv | 2 +- crates/ui-egui/src/i18n/id.tsv | 2 +- crates/ui-egui/src/i18n/it.tsv | 2 +- crates/ui-egui/src/i18n/ja.tsv | 2 +- crates/ui-egui/src/i18n/ka.tsv | 2 +- crates/ui-egui/src/i18n/ko.tsv | 2 +- crates/ui-egui/src/i18n/nl.tsv | 2 +- crates/ui-egui/src/i18n/pl.tsv | 2 +- crates/ui-egui/src/i18n/pt-br.tsv | 2 +- crates/ui-egui/src/i18n/ru.tsv | 2 +- crates/ui-egui/src/i18n/sv.tsv | 2 +- crates/ui-egui/src/i18n/tr.tsv | 2 +- crates/ui-egui/src/i18n/uk.tsv | 2 +- crates/ui-egui/src/i18n/vi.tsv | 2 +- crates/ui-egui/src/i18n/zh-hans.tsv | 2 +- crates/ui-egui/src/i18n/zh-hant.tsv | 2 +- crates/ui-egui/src/panels/gradient.rs | 16 ++++++++++--- crates/ui-egui/src/panels/gradient/tests.rs | 25 +++++++++++++++++++++ docs/ui-parity.md | 3 ++- 29 files changed, 66 insertions(+), 30 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 59c231102d..e09a592322 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -906,7 +906,7 @@ font-technology Variable Променливи Edit Symbol Редактиране на символ Edit Text Редактиране на текст Edit the applied effect, or add another one? Да се редактира ли приведеният ефект или да се добави друг? - Edit the selected point's colour in the Color panel Редактиране на цвета на избраната точка в панела Цвят + Edit the point Редактиране на точката Edit the stop Редактиране на опорната точка Edit Theme Редактиране на тема Edit theme Редактиране на тема diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 5714219657..f213baaabf 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1516,7 +1516,7 @@ lighting Light Svjetlo Color: Boja: Delete Stop Izbriši tačku Edit Gradient Uredi gradijent - Edit the selected point's colour in the Color panel Uredite boju odabrane tačke u panelu Boja + Edit the point Uredi tačku Edit the stop Uredi tačku Eyedropper: click the art to sample the stop's colour Kapaljka: kliknite crtež da uzmete uzorak boje tačke Eyedropper: click the art to sample the key color Kapaljka: kliknite crtež da uzmete uzorak ključne boje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 95c59b92cd..8d8054c259 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1309,7 +1309,7 @@ Edit Symbol Edita el símbol Edit Text Edita el text Edit the applied effect, or add another one? Vols editar l’efecte aplicat o afegir-ne un altre? - Edit the selected point's colour in the Color panel Edita el color del punt seleccionat al panell Color + Edit the point Edita el punt Edit the stop Edita la parada Edit Theme Edita el tema Edit theme Edita el tema diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 0768ea6c88..0caa797bd8 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1539,7 +1539,7 @@ lighting Light Světlo Color: Barva: Delete Stop Odstranit zarážku Edit Gradient Upravit přechod - Edit the selected point's colour in the Color panel Upravit barvu vybraného bodu v panelu Barva + Edit the point Upravit bod Edit the stop Upravit zarážku Eyedropper: click the art to sample the stop's colour Kapátko: kliknutím na kresbu naberete barvu zarážky Eyedropper: click the art to sample the key color Kapátko: kliknutím na kresbu naberete klíčovou barvu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 170f4d4b9a..1507f30ef9 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1453,7 +1453,7 @@ lighting Light Lys Color: Farve: Delete Stop Slet stop Edit Gradient Redigér gradient - Edit the selected point's colour in the Color panel Redigér det markerede punkts farve i farvepanelet + Edit the point Redigér punktet Edit the stop Redigér stoppet Eyedropper: click the art to sample the stop's colour Pipette: klik på grafikken for at prøvetage stoppets farve Eyedropper: click the art to sample the key color Pipette: klik på grafikken for at prøvetage nøglefarven diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 21734d6b48..22d2280978 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -900,7 +900,7 @@ font-technology Variable Variabel Edit Symbol Symbol bearbeiten Edit Text Text bearbeiten Edit the applied effect, or add another one? Den angewendeten Effekt bearbeiten oder einen weiteren hinzufügen? - Edit the selected point's colour in the Color panel Die Farbe des ausgewählten Punkts im Bedienfeld „Farbe“ bearbeiten + Edit the point Punkt bearbeiten Edit the stop Farbstopp bearbeiten Edit Theme Thema bearbeiten Edit theme Thema bearbeiten diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b3b5e9f979..a993b98407 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -876,7 +876,7 @@ font-technology Variable Μεταβλητές Edit Symbol Επεξεργασία συμβόλου Edit Text Επεξεργασία κειμένου Edit the applied effect, or add another one? Επεξεργασία του εφαρμοσμένου εφέ ή προσθήκη άλλου; - Edit the selected point's colour in the Color panel Επεξεργασία του χρώματος επιλεγμένου σημείου στον πίνακα Χρώμα + Edit the point Επεξεργασία σημείου Edit the stop Επεξεργασία σημείου ντεγκραντέ Edit Theme Επεξεργασία θέματος Edit theme Επεξεργασία θέματος diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 1e4a8fd9b6..19e524cf22 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -921,7 +921,7 @@ font-technology Variable Variables Edit Symbol Editar símbolo Edit Text Editar texto Edit the applied effect, or add another one? ¿Editar el efecto aplicado o agregar otro? - Edit the selected point's colour in the Color panel Edita el color del punto seleccionado en el panel Color + Edit the point Editar el punto Edit the stop Editar la parada Edit Theme Editar tema Edit theme Editar tema diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 540800b588..eb9c0e5254 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1513,7 +1513,7 @@ lighting Light Valo Color: Väri: Delete Stop Poista väripiste Edit Gradient Muokkaa liukuväriä - Edit the selected point's colour in the Color panel Muokkaa valitun pisteen väriä Väri-paneelissa + Edit the point Muokkaa pistettä Edit the stop Muokkaa väripistettä Eyedropper: click the art to sample the stop's colour Pipetti: ota väripisteen väri näytteeksi napsauttamalla kuvitusta Eyedropper: click the art to sample the key color Pipetti: ota avainväri näytteeksi napsauttamalla kuvitusta diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index f171df8dbf..d2ecba42df 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -924,7 +924,7 @@ font-technology Variable Variables Edit Symbol Modifier le symbole Edit Text Modifier le texte Edit the applied effect, or add another one? Modifier l’effet appliqué ou en ajouter un autre ? - Edit the selected point's colour in the Color panel Modifier la couleur du point sélectionné dans le panneau Couleur + Edit the point Modifier le point Edit the stop Modifier l’étape de dégradé Edit Theme Modifier le thème Edit theme Modifier le thème diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 7070071b07..b29f8ef71c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1189,7 +1189,7 @@ font-technology Variable Változó Edit Symbol Szimbólum szerkesztése Edit Text Szöveg szerkesztése Edit the applied effect, or add another one? Szerkeszted az alkalmazott effektust, vagy újat adsz hozzá? - Edit the selected point's colour in the Color panel A kijelölt pont színe a Szín panelen szerkeszthető + Edit the point Pont szerkesztése Edit the stop Színátmenet-pont szerkesztése Edit Theme Téma szerkesztése Edit theme Téma szerkesztése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 4276a98f2a..705f573705 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1453,7 +1453,7 @@ lighting Light Cahaya Color: Warna: Delete Stop Hapus stop Edit Gradient Edit gradien - Edit the selected point's colour in the Color panel Edit warna titik terpilih di panel Warna + Edit the point Edit titik Edit the stop Edit stop Eyedropper: click the art to sample the stop's colour Pipet: klik karya seni untuk mengambil sampel warna stop Eyedropper: click the art to sample the key color Pipet: klik karya seni untuk mengambil sampel warna kunci diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 9daf34aec4..9d6a31cca8 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -921,7 +921,7 @@ font-technology Variable Variabili Edit Symbol Modifica simbolo Edit Text Modifica testo Edit the applied effect, or add another one? Modificare l'effetto applicato o aggiungerne un altro? - Edit the selected point's colour in the Color panel Modifica il colore del punto selezionato nel pannello Colore + Edit the point Modifica il punto Edit the stop Modifica il cursore colore Edit Theme Modifica tema Edit theme Modifica tema diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 008940f123..abe51ff0a1 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1420,7 +1420,7 @@ font-technology Variable バリアブル Edit or Apply Color Group… カラーグループを編集または適用… Edit or Apply Colors カラーを編集/適用 Edit the applied effect, or add another one? 適用済みの効果を編集しますか? それとも別の効果を追加しますか? - Edit the selected point's colour in the Color panel 選択したポイントのカラーをカラーパネルで編集 + Edit the point ポイントを編集 Edit the stop 分岐点を編集 Edit theme テーマを編集 Edit… 編集… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a32250773c..adcb85d678 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1370,7 +1370,7 @@ lighting Light სინათლე Color: ფერი: Delete Stop გადასვლის წერტილის წაშლა Edit Gradient გრადიენტის რედაქტირება - Edit the selected point's colour in the Color panel მონიშნული წერტილის ფერის რედაქტირება ფერის პანელში + Edit the point წერტილის რედაქტირება Edit the stop გადასვლის წერტილის რედაქტირება Eyedropper: click the art to sample the stop's colour პიპეტი: დაწკაპეთ ნახატზე გადასვლის წერტილის ფერის ასაღებად Eyedropper: click the art to sample the key color პიპეტი: დაწკაპეთ ნახატზე საკვანძო ფერის ასაღებად diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index a2c3ea0e9d..b3bf3cd62d 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1411,7 +1411,7 @@ font-technology Variable 가변 Edit or Apply Color Group… 색상 그룹 편집 또는 적용… Edit or Apply Colors 색상 편집 또는 적용 Edit the applied effect, or add another one? 적용된 효과를 편집하거나 다른 효과를 추가하시겠습니까? - Edit the selected point's colour in the Color panel 색상 패널에서 선택한 포인트의 색상 편집 + Edit the point 포인트 편집 Edit the stop 정지점 편집 Edit theme 테마 편집 Edit… 편집… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 26a3a0c490..c3bf46c3ee 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1467,7 +1467,7 @@ lighting Light Licht Color: Kleur: Delete Stop Stoppunt verwijderen Edit Gradient Verloop bewerken - Edit the selected point's colour in the Color panel Bewerk de kleur van het geselecteerde punt in het Kleur-paneel + Edit the point Punt bewerken Edit the stop Stoppunt bewerken Eyedropper: click the art to sample the stop's colour Pipet: klik op de illustratie om de kleur van het stoppunt over te nemen Eyedropper: click the art to sample the key color Pipet: klik op de illustratie om de sleutelkleur over te nemen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 7a71813b07..519595ffcb 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1453,7 +1453,7 @@ lighting Light Światło Color: Kolor: Delete Stop Usuń punkt koloru Edit Gradient Edytuj gradient - Edit the selected point's colour in the Color panel Edytuj kolor zaznaczonego punktu w panelu Kolor + Edit the point Edytuj punkt Edit the stop Edytuj punkt koloru Eyedropper: click the art to sample the stop's colour Kroplomierz: kliknij kompozycję, aby pobrać kolor punktu Eyedropper: click the art to sample the key color Kroplomierz: kliknij kompozycję, aby pobrać kolor kluczowy diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e206114885..b07ec8f665 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -816,7 +816,7 @@ Edit or Apply Color Group… Editar ou Aplicar Grupo de Cores… Edit or Apply Colors Editar ou Aplicar Cores Edit the applied effect, or add another one? Editar o efeito aplicado, ou adicionar outro? - Edit the selected point's colour in the Color panel Edite a cor do ponto selecionado no painel Cor + Edit the point Editar o ponto Edit the stop Editar a parada Edit theme Editar tema Edit… Editar… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 414f43d29a..685d6862b6 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -919,7 +919,7 @@ font-technology Variable Вариативные Edit Symbol Редактировать символ Edit Text Редактировать текст Edit the applied effect, or add another one? Редактировать применённый эффект или добавить другой? - Edit the selected point's colour in the Color panel Редактируйте цвет выбранной точки на панели «Цвет» + Edit the point Редактировать точку Edit the stop Редактировать точку перехода Edit Theme Редактировать тему Edit theme Редактировать тему diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 46d0eb2262..b5ff04674d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -908,7 +908,7 @@ font-technology Variable Variabla Edit Symbol Redigera symbol Edit Text Redigera text Edit the applied effect, or add another one? Vill du redigera den använda effekten eller lägga till en till? - Edit the selected point's colour in the Color panel Redigera den markerade punktens färg i panelen Färg + Edit the point Redigera punkten Edit the stop Redigera stoppet Edit Theme Redigera tema Edit theme Redigera tema diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c40b948f1e..4961fcd152 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -900,7 +900,7 @@ font-technology Variable Değişken Edit Symbol Sembolü Düzenle Edit Text Metni Düzenle Edit the applied effect, or add another one? Uygulanan efekti düzenlemek veya başka bir efekt eklemek mi istiyorsunuz? - Edit the selected point's colour in the Color panel Seçilen noktanın rengini Renk panelinde düzenleyin + Edit the point Noktayı düzenle Edit the stop Durağı düzenle Edit Theme Temayı Düzenle Edit theme Temayı düzenle diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index e92094241a..886675579b 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -915,7 +915,7 @@ font-technology Variable Варіативні Edit Symbol Редагувати символ Edit Text Редагувати текст Edit the applied effect, or add another one? Редагувати застосований ефект або додати інший? - Edit the selected point's colour in the Color panel Редагуйте колір вибраної точки на панелі «Колір» + Edit the point Редагувати точку Edit the stop Редагувати точку переходу Edit Theme Редагувати тему Edit theme Редагувати тему diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 44fffd0ce1..f0ed3842e2 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1071,7 +1071,7 @@ font-technology Variable Biến thiên Edit Symbol Chỉnh sửa ký hiệu Edit Text Chỉnh sửa văn bản Edit the applied effect, or add another one? Chỉnh sửa hiệu ứng đã áp dụng, hay thêm hiệu ứng mới? - Edit the selected point's colour in the Color panel Chỉnh sửa màu của điểm đã chọn trong bảng Màu + Edit the point Chỉnh sửa điểm Edit the stop Chỉnh sửa điểm dừng Edit Theme Chỉnh sửa bộ màu Edit theme Chỉnh sửa bộ màu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index cb2d7558bc..b184706400 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -861,7 +861,7 @@ Edit Symbol 编辑符号 Edit Text 编辑文字 Edit the applied effect, or add another one? 编辑已应用的效果,还是再添加一个? - Edit the selected point's colour in the Color panel 在颜色面板中编辑所选点的颜色 + Edit the point 编辑点 Edit the stop 编辑色标 Edit Theme 编辑主题 Edit theme 编辑主题 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 31a2d1dbe5..2b7e38a403 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -883,7 +883,7 @@ font-technology Variable 可變 Edit Symbol 編輯符號 Edit Text 編輯文字 Edit the applied effect, or add another one? 要編輯已套用的效果,還是新增另一個? - Edit the selected point's colour in the Color panel 在顏色面板中編輯所選點的顏色 + Edit the point 編輯點 Edit the stop 編輯色標 Edit Theme 編輯主題 Edit theme 編輯主題 diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 0f6bcf3958..2b71ea0545 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -18,7 +18,7 @@ //! //! A freeform gradient shows its section instead of the angle, aspect and slider: the Draw //! toggle (Points or Lines: how the Gradient tool adds points) and the selected point's colour -//! (edited in the Color panel), opacity and spread, with Delete Point. +//! (click: its popover, as a stop's), opacity and spread, with Delete Point. //! //! The Presets menu lists ready-made gradients by theme (the built-in gradient libraries), then //! the gradients saved with the panel menu's Save Gradient Preset…; choosing one applies it to the @@ -484,13 +484,18 @@ fn freeform_section(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint) { let point = sel.map(|i| f.points[i]); ui.horizontal(|ui| { widgets::dim_label(ui, tl!("Color:")); - let (r, resp) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover()); + let (r, resp) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::click()); let paint = point.map_or(Paint::None, |p| Paint::solid(p.color)); widgets::swatch_tile(ui, r, &paint, false, resp.hovered()); - resp.on_hover_text(tl!("Edit the selected point's colour in the Color panel")); if let Some(p) = point { widgets::dim_label(ui, &p.color.to_hex().to_uppercase()); } + // The selected point's popover, as a stop's swatch opens the stop's (#4953). + if let Some(i) = sel + && resp.on_hover_text(tl!("Edit the point")).clicked() + { + show_popover(app, i, r.left_bottom() + vec2(0.0, 4.0)); + } }); ui.horizontal(|ui| { ui.add_enabled_ui(sel.is_some(), |ui| { @@ -640,6 +645,11 @@ pub(crate) fn stop_eyedropper(app: &mut VectorcraftApp) { /// Open the stop popover for stop `i` at screen position `at`. fn open_popover(app: &mut VectorcraftApp, i: usize, at: Pos2) { select_stop(app, Some(i)); + show_popover(app, i, at); +} + +/// The popover for the selected stop or freeform point `i`, at screen position `at`. +fn show_popover(app: &mut VectorcraftApp, i: usize, at: Pos2) { app.ui.dialog = Some(Dialog::new("gradientStop", json!({ "index": i, "screen": [at.x, at.y], "tab": "color" }))); } diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index a3b7f5cfa7..83a290bb1d 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -543,6 +543,31 @@ fn double_clicking_a_stop_opens_the_shared_popover_beside_it() { assert_eq!(app.session.selected_stop(), Some(1)); } +/// #4953: with a freeform point selected, clicking the Color swatch opens the popover for that +/// point, which recolours it and leaves the other points as they were. +#[test] +fn the_freeform_color_swatch_opens_the_points_popover() { + let mut app = app(json!({"gradient": {"kind": "freeform"}})); + app.run("paint.freeform.selectPoint", json!({"index": 1})).unwrap(); + let mut p = Panel::new(); + let texts = p.frame(&mut app, vec![], Modifiers::NONE); + let label = text_at(&texts, "Color:").unwrap_or_else(|| panic!("the Color row: {texts:?}")); + let swatch = p.widget_after(label); + p.click(&mut app, swatch.center()); + let d = app.ui.dialog.clone().expect("the popover opened"); + assert_eq!( + (d.kind.as_str(), &d.fields["index"], &d.fields["screen"]), + ("gradientStop", &json!(1), &json!([swatch.left(), swatch.bottom() + 4.0])) + ); + let points = |app: &VectorcraftApp| shown_points(&fill(app)).points.iter().map(|p| p.color.to_hex()).collect::<Vec<_>>(); + let before = points(&app); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + crate::dialogs::confirm(&mut app).unwrap(); + let mut want = before.clone(); + want[1] = "#ff0000".into(); + assert_eq!((fill(&app).gradient.kind, points(&app)), (GradientKind::Freeform, want)); +} + #[test] fn the_stop_eyedropper_arms_the_eyedropper_for_the_stop() { let mut app = app(json!({"gradient": {}})); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index ecda87aae2..fee3db42db 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (files opened from the file manager while VectorCraft runs open in its window on Windows and Linux, #4892) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (native Save As Version menu, refused-save alert, fixed Contributors table header, freeform point swatch opens its popover: #4931, #4933, #4944, #4953) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -381,6 +381,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | VectorCraft Options' Version is a menu of the versions VectorCraft writes, each named by the releases that read it, and an uncompressible version turns Use Compression off (#4931); a save refused before writing shows the Can't save alert with the reason (#4933); About › Contributors' table keeps its header row above the scrolling rows (#4944); the Gradient panel's freeform point swatch opens the point's popover (#4953); scores unchanged | | 2026-10-31 | minor | A file opened from the file manager while VectorCraft runs opens as a new tab in that window, which comes to the front, on Windows and Linux (#4892); `--new-instance` opts out; scores unchanged | | 2026-10-31 | minor | Object › Path › Smooth: Auto-Smooth takes a shaky line to one smooth curve, and direct-selected anchors smooth only their section; scores unchanged | | 2026-10-31 | minor | New Document: More Settings has Save Preset beside the name, as Preset Details does, and saves its settings (#4893); scores and estimates unchanged | From a85487ad39d7c8d0acb49372ab0509e9fa085406 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 00:52:43 +0700 Subject: [PATCH 163/260] Fix #4940: text is shaped in its language Characters get a language (CharStyle::language, a BCP 47 tag of one of Document Setup's languages; none for the default, English: USA, saved only when set). The shaper sets it on the HarfRust buffer, so fonts use their language forms (OpenType locl): Turkish keeps fi apart and the dot on its i. Runs in different languages are shaped apart. New type takes the document's language. --- crates/doc/src/setup.rs | 87 ++++++++++++++------ crates/doc/src/text/char_style.rs | 7 ++ crates/doc/src/text/tests.rs | 12 +++ crates/engine/src/cmd/create.rs | 5 +- crates/engine/src/cmd/docsetup.rs | 4 +- crates/text/src/features.rs | 18 ++++ crates/text/src/shape.rs | 13 +++ crates/ui-egui/src/dialogs/document_setup.rs | 2 +- 8 files changed, 120 insertions(+), 28 deletions(-) diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index 4ab8553298..bb7c497c9f 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -143,34 +143,55 @@ impl Quotes { } } -/// Document languages and the quote characters each uses (choosing a language in Document Setup -/// also picks its quotes). -pub const LANGUAGES: &[(&str, Quotes)] = &[ - ("English: USA", Quotes::ENGLISH), - ("English: UK", Quotes { double: ['“', '”'], single: ['‘', '’'] }), - ("German", Quotes { double: ['„', '“'], single: ['‚', '‘'] }), - ("German: Swiss", Quotes { double: ['«', '»'], single: ['‹', '›'] }), - ("French", Quotes { double: ['«', '»'], single: ['‹', '›'] }), - ("Italian", Quotes { double: ['«', '»'], single: ['‘', '’'] }), - ("Spanish", Quotes { double: ['«', '»'], single: ['‘', '’'] }), - ("Catalan", Quotes { double: ['«', '»'], single: ['‘', '’'] }), - ("Portuguese", Quotes { double: ['«', '»'], single: ['‘', '’'] }), - ("Dutch", Quotes { double: ['“', '”'], single: ['‘', '’'] }), - ("Danish", Quotes { double: ['»', '«'], single: ['›', '‹'] }), - ("Swedish", Quotes { double: ['”', '”'], single: ['’', '’'] }), - ("Finnish", Quotes { double: ['”', '”'], single: ['’', '’'] }), - ("Norwegian", Quotes { double: ['«', '»'], single: ['‘', '’'] }), - ("Polish", Quotes { double: ['„', '”'], single: ['‚', '’'] }), - ("Czech", Quotes { double: ['„', '“'], single: ['‚', '‘'] }), - ("Russian", Quotes { double: ['«', '»'], single: ['„', '“'] }), - ("Turkish", Quotes { double: ['“', '”'], single: ['‘', '’'] }), - ("Japanese", Quotes { double: ['「', '」'], single: ['『', '』'] }), - ("Chinese", Quotes { double: ['“', '”'], single: ['‘', '’'] }), +/// Document and character languages: the name, the BCP 47 tag text is shaped in (so that fonts use +/// their language's forms, OpenType `locl`) and the quote characters each uses (choosing a +/// language in Document Setup also picks its quotes). The first is the default. +pub const LANGUAGES: &[(&str, &str, Quotes)] = &[ + ("English: USA", "en-US", Quotes::ENGLISH), + ("English: UK", "en-GB", Quotes { double: ['“', '”'], single: ['‘', '’'] }), + ("German", "de", Quotes { double: ['„', '“'], single: ['‚', '‘'] }), + ("German: Swiss", "de-CH", Quotes { double: ['«', '»'], single: ['‹', '›'] }), + ("French", "fr", Quotes { double: ['«', '»'], single: ['‹', '›'] }), + ("Italian", "it", Quotes { double: ['«', '»'], single: ['‘', '’'] }), + ("Spanish", "es", Quotes { double: ['«', '»'], single: ['‘', '’'] }), + ("Catalan", "ca", Quotes { double: ['«', '»'], single: ['‘', '’'] }), + ("Portuguese", "pt", Quotes { double: ['«', '»'], single: ['‘', '’'] }), + ("Dutch", "nl", Quotes { double: ['“', '”'], single: ['‘', '’'] }), + ("Danish", "da", Quotes { double: ['»', '«'], single: ['›', '‹'] }), + ("Swedish", "sv", Quotes { double: ['”', '”'], single: ['’', '’'] }), + ("Finnish", "fi", Quotes { double: ['”', '”'], single: ['’', '’'] }), + ("Norwegian", "nb", Quotes { double: ['«', '»'], single: ['‘', '’'] }), + ("Polish", "pl", Quotes { double: ['„', '”'], single: ['‚', '’'] }), + ("Czech", "cs", Quotes { double: ['„', '“'], single: ['‚', '‘'] }), + ("Russian", "ru", Quotes { double: ['«', '»'], single: ['„', '“'] }), + ("Turkish", "tr", Quotes { double: ['“', '”'], single: ['‘', '’'] }), + ("Japanese", "ja", Quotes { double: ['「', '」'], single: ['『', '』'] }), + ("Chinese", "zh", Quotes { double: ['“', '”'], single: ['‘', '’'] }), ]; /// The quotes of a [`LANGUAGES`] entry (case-insensitive). pub fn language_quotes(language: &str) -> Option<Quotes> { - LANGUAGES.iter().find(|(l, _)| l.eq_ignore_ascii_case(language)).map(|(_, q)| *q) + LANGUAGES.iter().find(|(l, _, _)| l.eq_ignore_ascii_case(language)).map(|(_, _, q)| *q) +} + +/// The [`LANGUAGES`] entry named or tagged `language` (case-insensitive) as a character's +/// language ([`crate::CharStyle::language`]) stores it: its tag, or `None` for the default (the +/// first entry); `Err` for a language not in the list. +pub fn char_language(language: &str) -> Result<Option<&'static str>, String> { + let i = LANGUAGES + .iter() + .position(|(n, t, _)| n.eq_ignore_ascii_case(language) || t.eq_ignore_ascii_case(language)) + .ok_or_else(|| format!("unknown language `{language}` (one of {})", LANGUAGES.iter().map(|(n, _, _)| *n).collect::<Vec<_>>().join(", ")))?; + Ok(LANGUAGES.get(i).filter(|_| i > 0).map(|(_, t, _)| *t)) +} + +/// The name of the language a character's stored `language` tag stands for: the default's for +/// none, `None` for a tag not in [`LANGUAGES`] (from a file). +pub fn char_language_name(language: Option<&str>) -> Option<&'static str> { + match language { + None => LANGUAGES.first().map(|(n, _, _)| *n), + Some(tag) => LANGUAGES.iter().find(|(_, t, _)| t.eq_ignore_ascii_case(tag)).map(|(n, _, _)| *n), + } } /// The transparency flattener preset Document Setup uses unless another is chosen. @@ -329,6 +350,24 @@ impl DocSetup { mod tests { use super::*; + /// Characters store a language of the list by its tag, the default as none. + #[test] + fn char_languages_are_stored_by_tag() { + assert_eq!(char_language("Turkish"), Ok(Some("tr"))); + assert_eq!(char_language("TR"), Ok(Some("tr"))); + assert_eq!(char_language("english: usa"), Ok(None)); + assert_eq!(char_language("en-US"), Ok(None)); + assert!(char_language("Klingon").is_err() && char_language("").is_err()); + assert_eq!( + (char_language_name(None), char_language_name(Some("de")), char_language_name(Some("x-unknown"))), + (Some("English: USA"), Some("German"), None) + ); + // Every entry has a tag of its own, and a name of its own. + for (i, (n, t, _)) in LANGUAGES.iter().enumerate() { + assert!(LANGUAGES.iter().skip(i + 1).all(|(n2, t2, _)| n2 != n && t2 != t), "{n} {t}"); + } + } + #[test] fn quotes_open_and_close_by_context() { let mut prev = None; diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index 5189e7aa28..26c8b3c4f8 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -114,6 +114,12 @@ pub struct CharStyle { /// <https://helpx.adobe.com/illustrator/using/hyphenation-line-breaks.html> #[serde(default, rename = "noBreak", skip_serializing_if = "crate::skip::is_default")] pub no_break: bool, + /// Language (Character panel): the BCP 47 tag of one of [`crate::setup::LANGUAGES`] these + /// characters are shaped in, so that the font uses that language's forms (OpenType `locl`). + /// `None`: the default language, English: USA, shaped without a language. New type takes the + /// document's language (Document Setup). Saved only when set. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub language: Option<String>, } /// The numeral system digits are drawn in ([`CharStyle::digits`]): as typed, or every digit of @@ -297,6 +303,7 @@ impl Default for CharStyle { small_caps: None, digits: Digits::Default, no_break: false, + language: None, } } } diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 54142efd7f..25e46a0490 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -60,6 +60,18 @@ fn digits_map_between_the_numeral_systems() { assert_eq!(serde_json::from_value::<CharStyle>(serde_json::to_value(&farsi).unwrap()).unwrap(), farsi); } +/// Language is saved only when set; styles written before it existed read as the default. +#[test] +fn language_is_saved_only_when_set() { + let st = CharStyle::default(); + let old = serde_json::to_value(&st).unwrap(); + assert!(old.get("language").is_none()); + assert_eq!(serde_json::from_value::<CharStyle>(old).unwrap().language, None); + let turkish = CharStyle { language: Some("tr".into()), ..CharStyle::default() }; + assert_eq!(serde_json::to_value(&turkish).unwrap()["language"], "tr"); + assert_eq!(serde_json::from_value::<CharStyle>(serde_json::to_value(&turkish).unwrap()).unwrap(), turkish); +} + /// Auto leading follows the paragraph's Auto Leading; a set leading doesn't. #[test] fn paragraph_effective_leading_follows_auto_leading() { diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index f414182470..65a6ee0c37 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -811,7 +811,8 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str) -> Result<vectorcraf /// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB /// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults, -/// filled with the current fill unless that is None or white (black then). +/// filled with the current fill unless that is None or white (black then), in the document's +/// language. pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle { let mut style = CharStyle::default(); if let Some(sz) = p.get("size").and_then(Value::as_f64) { @@ -831,5 +832,7 @@ pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle { None if !s.paint.fill.is_none() && s.paint.fill != vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE) => s.paint.fill.clone(), None => vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), }; + // In the document's language (Document Setup), none for the default. + style.language = s.doc().ok().and_then(|d| vectorcraft_doc::setup::char_language(&d.doc.setup.language).ok().flatten()).map(str::to_string); style } diff --git a/crates/engine/src/cmd/docsetup.rs b/crates/engine/src/cmd/docsetup.rs index 3f7b632250..f5cb1d6b72 100644 --- a/crates/engine/src/cmd/docsetup.rs +++ b/crates/engine/src/cmd/docsetup.rs @@ -127,8 +127,8 @@ fn apply(s: &mut DocSetup, units: &mut vectorcraft_doc::Unit, k: &str, v: &Value "discardWhiteOverprint" => s.discard_white_overprint = flag(k, v)?, "language" => { let l = v.as_str().unwrap_or(""); - let (name, quotes) = LANGUAGES.iter().find(|(n, _)| n.eq_ignore_ascii_case(l)).ok_or_else(|| { - bad(C, format!("unknown language `{l}` (one of {})", LANGUAGES.iter().map(|(n, _)| *n).collect::<Vec<_>>().join(", "))) + let (name, _, quotes) = LANGUAGES.iter().find(|(n, _, _)| n.eq_ignore_ascii_case(l)).ok_or_else(|| { + bad(C, format!("unknown language `{l}` (one of {})", LANGUAGES.iter().map(|(n, _, _)| *n).collect::<Vec<_>>().join(", "))) })?; s.language = name.to_string(); s.quotes = *quotes; diff --git a/crates/text/src/features.rs b/crates/text/src/features.rs index dd71a20c93..dd9c68c756 100644 --- a/crates/text/src/features.rs +++ b/crates/text/src/features.rs @@ -295,4 +295,22 @@ mod tests { assert!(OtFeatures::default().to_tags().is_empty()); assert!(OtFeatures::known_tag("-onum") && !OtFeatures::known_tag("zzzz")); } + + /// The characters' language reaches the shaper (#4940): Source Serif 4's Turkish forms + /// (`locl`) keep f and i apart, and the dot on the i, where English ligates them. Runs in + /// different languages are shaped apart, each in its own. + #[test] + fn language_picks_the_fonts_forms() { + let st = + |language: Option<&str>| CharStyle { font_family: "Source Serif 4".into(), language: language.map(str::to_string), ..Default::default() }; + let count = |language| layout(FontDb::global(), &TextObject::point(Point::ZERO, "fi", st(language))).glyphs.len(); + assert_eq!((count(None), count(Some("en-US")), count(Some("tr"))), (1, 1, 2)); + // A tag that isn't one (from a file) shapes without a language. + assert_eq!((count(Some("tr; DROP")), count(Some(""))), (1, 1)); + let mut t = TextObject::point(Point::ZERO, "", st(None)); + t.runs = vec![vectorcraft_doc::TextRun::new("fi", st(Some("tr"))), vectorcraft_doc::TextRun::new("fi", st(None))]; + let glyphs = layout(FontDb::global(), &t).glyphs; + let per_run: Vec<usize> = (0..2).map(|r| glyphs.iter().filter(|g| g.run == r).count()).collect(); + assert_eq!(per_run, [2, 1]); + } } diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index ab547ef837..f0fbb0c4de 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -715,6 +715,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { tate_chu_yoko, digits, no_break, + language, } = a; *font_family == b.font_family && *font_style == b.font_style @@ -731,6 +732,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { && *tate_chu_yoko == b.tate_chu_yoko && *digits == b.digits && *no_break == b.no_break + && *language == b.language && ligatures_suppressed_by(*tracking) == ligatures_suppressed_by(b.tracking) } @@ -922,6 +924,12 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe // Shape the segment as if all of it were in `st`, with the features `more` on top. let shape_in = |st: &CharStyle, more: &[Feature]| { + // A BCP 47 tag is short ASCII; anything else (a file may hold anything) is shaped without one. + let language = st + .language + .as_deref() + .filter(|l| l.len() <= 35 && l.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')) + .and_then(|l| l.parse::<harfrust::Language>().ok()); let mut shaped = Shaped::default(); let Shaped { raw, proportional, vpal } = &mut shaped; let hb_shaped = face.hb().map(|hb| { @@ -943,6 +951,11 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe } buf.set_direction(direction); buf.guess_segment_properties(); + // The characters' language picks the font's forms for it (`locl`: Turkish keeps fi + // apart and the dot on its i). + if let Some(l) = &language { + buf.set_language(l.clone()); + } // Harfrust keeps this Unicode context for joining/positional shaping, but does not emit // glyphs for it. This retains context at real style/font segmentation boundaries without // shaping across those boundaries or claiming cross-style ligatures/mark attachment. diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 666d25258f..a449156e74 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -154,7 +154,7 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { fn typography(ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); - let langs: Vec<(&str, &str)> = LANGUAGES.iter().map(|(l, _)| (*l, *l)).collect(); + let langs: Vec<(&str, &str)> = LANGUAGES.iter().map(|(l, _, _)| (*l, *l)).collect(); let before = d.str("language"); choice(ui, d, "language", tl!("Language:"), &langs); // A language brings its quotes. From 2bdaaa89812745276c15eafd0d8ba2534027a595 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 00:52:44 +0700 Subject: [PATCH 164/260] Fix #4946: a Language setting per text, with Indian languages (#4943) Character panel > Language sets the selected characters' language; text.setFormat and text.setRangeStyle take `language` by name or tag (unknown: an error), and character styles carry it. Document Setup's language list gains Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu, with catalog rows; the Digits menu's numeral names move to a digits context, as Hindi is now also a language name. --- crates/doc/src/setup.rs | 17 +++++-- crates/engine/src/cmd/panelcmds.rs | 7 ++- crates/engine/src/cmd/textedit.rs | 18 +++++++- crates/engine/src/cmd/textstyles.rs | 10 ++++- crates/engine/src/cmd/typecmd/area_tests.rs | 49 +++++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 10 +++++ crates/ui-egui/src/i18n/bs.tsv | 10 +++++ crates/ui-egui/src/i18n/ca.tsv | 10 +++++ crates/ui-egui/src/i18n/cs.tsv | 13 +++++- crates/ui-egui/src/i18n/da.tsv | 10 +++++ crates/ui-egui/src/i18n/de.tsv | 10 +++++ crates/ui-egui/src/i18n/el.tsv | 10 +++++ crates/ui-egui/src/i18n/es.tsv | 10 +++++ crates/ui-egui/src/i18n/fi.tsv | 10 +++++ crates/ui-egui/src/i18n/fr.tsv | 10 +++++ crates/ui-egui/src/i18n/hu.tsv | 10 +++++ crates/ui-egui/src/i18n/id.tsv | 10 +++++ crates/ui-egui/src/i18n/it.tsv | 10 +++++ crates/ui-egui/src/i18n/ja.tsv | 13 +++++- crates/ui-egui/src/i18n/ka.tsv | 10 +++++ crates/ui-egui/src/i18n/ko.tsv | 10 +++++ crates/ui-egui/src/i18n/nl.tsv | 10 +++++ crates/ui-egui/src/i18n/pl.tsv | 10 +++++ crates/ui-egui/src/i18n/pt-br.tsv | 10 +++++ crates/ui-egui/src/i18n/ru.tsv | 10 +++++ crates/ui-egui/src/i18n/sv.tsv | 10 +++++ crates/ui-egui/src/i18n/tr.tsv | 10 +++++ crates/ui-egui/src/i18n/uk.tsv | 10 +++++ crates/ui-egui/src/i18n/vi.tsv | 13 +++++- crates/ui-egui/src/i18n/zh-hans.tsv | 13 +++++- crates/ui-egui/src/i18n/zh-hant.tsv | 13 +++++- crates/ui-egui/src/panels/character.rs | 22 +++++++-- docs/mcp.md | 15 +++++++ docs/target-app-parity.md | 3 +- docs/type-parity.md | 4 +- docs/ui-parity.md | 3 +- 36 files changed, 405 insertions(+), 18 deletions(-) diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index bb7c497c9f..62276ece90 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -167,6 +167,17 @@ pub const LANGUAGES: &[(&str, &str, Quotes)] = &[ ("Turkish", "tr", Quotes { double: ['“', '”'], single: ['‘', '’'] }), ("Japanese", "ja", Quotes { double: ['「', '」'], single: ['『', '』'] }), ("Chinese", "zh", Quotes { double: ['“', '”'], single: ['‘', '’'] }), + ("Hindi", "hi", Quotes::ENGLISH), + ("Marathi", "mr", Quotes::ENGLISH), + ("Gujarati", "gu", Quotes::ENGLISH), + ("Bengali", "bn", Quotes::ENGLISH), + ("Punjabi", "pa", Quotes::ENGLISH), + ("Tamil", "ta", Quotes::ENGLISH), + ("Telugu", "te", Quotes::ENGLISH), + ("Kannada", "kn", Quotes::ENGLISH), + ("Malayalam", "ml", Quotes::ENGLISH), + ("Odia", "or", Quotes::ENGLISH), + ("Urdu", "ur", Quotes::ENGLISH), ]; /// The quotes of a [`LANGUAGES`] entry (case-insensitive). @@ -354,13 +365,13 @@ mod tests { #[test] fn char_languages_are_stored_by_tag() { assert_eq!(char_language("Turkish"), Ok(Some("tr"))); - assert_eq!(char_language("TR"), Ok(Some("tr"))); + assert_eq!(char_language("MR"), Ok(Some("mr"))); assert_eq!(char_language("english: usa"), Ok(None)); assert_eq!(char_language("en-US"), Ok(None)); assert!(char_language("Klingon").is_err() && char_language("").is_err()); assert_eq!( - (char_language_name(None), char_language_name(Some("de")), char_language_name(Some("x-unknown"))), - (Some("English: USA"), Some("German"), None) + (char_language_name(None), char_language_name(Some("gu")), char_language_name(Some("x-unknown"))), + (Some("English: USA"), Some("Gujarati"), None) ); // Every entry has a tag of its own, and a name of its own. for (i, (n, t, _)) in LANGUAGES.iter().enumerate() { diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 4c52da717e..081678341b 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", has_doc, set_format ), @@ -372,6 +372,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { "tateChuYoko", "noBreak", "digits", + "language", "fontAxes", "burasagari", "romanHangingPunctuation", @@ -393,6 +394,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { let char_align = super::textedit::char_align_param(p, C)?; let char_direction = super::textedit::char_direction_param(p, C)?; let digits = super::textedit::digits_param(p, C)?; + let language = super::textedit::language_param(p, C)?; let font_axes = super::textedit::font_axes_param(p, C)?; let mojikumi = match p.get("mojikumi") { None => None, @@ -524,6 +526,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { if let Some(v) = digits { st.digits = v; } + if let Some(v) = &language { + st.language.clone_from(v); + } if let Some(v) = flag("proportionalMetrics") { st.proportional_metrics = v; } diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 8d393a58e9..958c5f10df 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -321,6 +321,8 @@ pub(crate) struct CharChange { tate_chu_yoko: Option<bool>, no_break: Option<bool>, digits: Option<vectorcraft_doc::Digits>, + /// The language to set: a tag, or `None` for the default. + language: Option<Option<String>>, font_axes: Option<AxisChange>, } @@ -350,6 +352,15 @@ pub(crate) fn digits_param(p: &Value, cmd: &str) -> Result<Option<vectorcraft_do })) } +/// `language: name|tag` (one of Document Setup's languages, case-insensitive) → the language to +/// set ([`vectorcraft_doc::CharStyle::language`]: `None` inside for the default). +pub(crate) fn language_param(p: &Value, cmd: &str) -> Result<Option<Option<String>>> { + let Some(v) = p.get("language").filter(|v| !v.is_null()) else { return Ok(None) }; + let l = v.as_str().ok_or_else(|| bad(cmd, "`language` must be a language name or tag, such as \"Turkish\" or \"tr\""))?; + let tag = vectorcraft_doc::setup::char_language(l).map_err(|e| bad(cmd, e))?; + Ok(Some(tag.map(str::to_string))) +} + /// Variable Font settings to change: by axis tag, a value in the axis's units, or `None` to go /// back to the style's own setting of that axis. pub(crate) type AxisChange = std::collections::BTreeMap<String, Option<f64>>; @@ -507,6 +518,7 @@ impl CharChange { tate_chu_yoko: flag("tateChuYoko"), no_break: flag("noBreak"), digits: digits_param(p, cmd)?, + language: language_param(p, cmd)?, font_axes: font_axes_param(p, cmd)?, }; if c.size.is_some_and(|v| v <= 0.0) { @@ -552,6 +564,7 @@ impl CharChange { && self.tate_chu_yoko.is_none() && self.no_break.is_none() && self.digits.is_none() + && self.language.is_none() && self.font_axes.is_none() } @@ -655,6 +668,9 @@ impl CharChange { if let Some(v) = self.digits { st.digits = v; } + if let Some(v) = &self.language { + st.language.clone_from(v); + } } } diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 30ccbfc7b7..e70af82a08 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -177,6 +177,7 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> { ("tateChuYoko", json!(v.tate_chu_yoko)), ("noBreak", json!(v.no_break)), ("digits", json!(v.digits)), + ("language", json!(v.language)), ] { m.insert(k.into(), x); } @@ -480,7 +481,14 @@ fn attrs_param(p: &Value, kind: Kind, verb: &str) -> Result<Option<Map<String, V // form (so comparing a style with its text's attributes is exact). let c = kind.cmd(verb); let full = match kind { - Kind::Char => char_attrs(&with_attrs(&CharStyle::default(), m, &c)?), + Kind::Char => { + let mut st = with_attrs(&CharStyle::default(), m, &c)?; + // A language of the list, stored as its tag (as text.setFormat takes it). + if let Some(l) = &st.language { + st.language = vectorcraft_doc::setup::char_language(l).map_err(|e| bad(&c, e))?.map(str::to_string); + } + char_attrs(&st) + } Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), m, &c)?), }; Ok(Some(m.keys().filter_map(|k| full.get(k).map(|v| (k.clone(), v.clone()))).collect())) diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index 4bde140a78..1f93079ace 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -1268,6 +1268,55 @@ fn digits_are_a_character_attribute_saved_only_when_set() { assert_eq!(set, [("صفحة ".to_string(), Digits::Default), ("12".to_string(), Digits::Farsi)]); } +/// Language (Character panel, #4946): a character attribute set by name or tag, saved as the tag +/// only when set, kept by save and reopen and by character styles; new type takes the document's. +#[test] +fn language_is_a_character_attribute_saved_only_when_set() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "fi i fikir"})).unwrap()["id"].as_u64().unwrap(); + let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("text"), + }; + let set = |s: &Session| runs(s).iter().map(|r| (r.text.clone(), r.style.language.clone())).collect::<Vec<_>>(); + assert_eq!(runs(&s)[0].style.language, None); + assert!(serde_json::to_value(&runs(&s)[0].style).unwrap().get("language").is_none()); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("text.setFormat", &json!({"language": "Turkish"})).unwrap(); + assert_eq!(set(&s), [("fi i fikir".to_string(), Some("tr".to_string()))]); + assert_eq!(serde_json::to_value(&runs(&s)[0].style).unwrap()["language"], "tr"); + for wrong in [json!("Klingon"), json!(5)] { + let err = s.execute("text.setFormat", &json!({ "language": wrong })).unwrap_err().to_string(); + assert!(err.contains("language"), "{err}"); + } + // Characters selected with the Type tool: only the range takes it; the default is none. + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 2, "language": "en-US"})).unwrap(); + assert_eq!(set(&s), [("fi".to_string(), None), (" i fikir".to_string(), Some("tr".to_string()))]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(set(&s), [("fi i fikir".to_string(), Some("tr".to_string()))]); + s.execute("edit.redo", &json!({})).unwrap(); + // Saved and reopened as it was. + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") }; + let reopened: Vec<_> = t.runs.iter().map(|r| (r.text.clone(), r.style.language.clone())).collect(); + assert_eq!(reopened, set(&s)); + // A character style captured from the characters carries it, the default included; one given + // a language by name stores its tag. + assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[1].style)["language"], "tr"); + assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[0].style).get("language"), Some(&serde_json::Value::Null)); + s.execute("charStyle.new", &json!({"name": "Marathi", "attrs": {"language": "Marathi"}})).unwrap(); + let listed = s.execute("charStyle.list", &json!({})).unwrap(); + let marathi = listed["styles"].as_array().unwrap().iter().find(|st| st["name"] == "Marathi").unwrap(); + assert_eq!(marathi["attrs"]["language"], "mr"); + assert!(s.execute("charStyle.new", &json!({"name": "Bad", "attrs": {"language": "Klingon"}})).is_err()); + // New type in a Turkish document is in Turkish. + s.execute("document.setup", &json!({"language": "Turkish"})).unwrap(); + let id2 = s.execute("text.create", &json!({"x": 10, "y": 150, "text": "fikir"})).unwrap()["id"].as_u64().unwrap(); + let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id2)).unwrap().kind else { panic!("text") }; + assert_eq!(t.runs[0].style.language.as_deref(), Some("tr")); +} + /// Variable Font settings (Character panel › Variable Font): a character attribute, saved only /// when set, each value clamped to its axis's range, and cleared by another font or style. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index e09a592322..d33addad42 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5926,4 +5926,14 @@ breakText Glyphs Глифи Set Size of Each Задаване на размер на всеки @msg select exactly two objects изберете точно два обекта @msg give `width` or `height` задайте `width` или `height` + Marathi Маратхи + Gujarati Гуджарати + Bengali Бенгалски + Punjabi Пенджабски + Tamil Тамилски + Telugu Телугу + Kannada Каннада + Malayalam Малаялам + Odia Ория + Urdu Урду VectorCraft {release} and later (version {n}) VectorCraft {release} и по-нови (версия {n}) diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index f213baaabf..f527ca2557 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5960,4 +5960,14 @@ shape Open Otvoren Set Size of Each Postavi veličinu svakog @msg select exactly two objects odaberite tačno dva objekta @msg give `width` or `height` zadajte `width` ili `height` + Marathi Marathi + Gujarati Gudžarati + Bengali Bengalski + Punjabi Pandžapski + Tamil Tamilski + Telugu Telugu + Kannada Kanada + Malayalam Malajalam + Odia Odija + Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} i novije (verzija {n}) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 8d8054c259..5873fbadae 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6033,4 +6033,14 @@ breakText Glyphs Glifs Set Size of Each Defineix la mida de cadascun @msg select exactly two objects selecciona exactament dos objectes @msg give `width` or `height` indica `width` o `height` + Marathi Marathi + Gujarati Gujarati + Bengali Bengalí + Punjabi Panjabi + Tamil Tàmil + Telugu Telugu + Kannada Kannada + Malayalam Malaiàlam + Odia Oriya + Urdu Urdú VectorCraft {release} and later (version {n}) VectorCraft {release} i posteriors (versió {n}) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 0caa797bd8..8f7a607107 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1442,7 +1442,8 @@ lighting Light Světlo Character Direction Směr znaků Digits Číslice Arabic Arabské - Hindi Hindské + Hindi Hindština +digits Hindi Hindské Farsi Perské Reset Panel Obnovit panel Roman Baseline Latinková účaří @@ -6042,4 +6043,14 @@ breakText Glyphs Glyfy Set Size of Each Nastavit velikost jednotlivě @msg select exactly two objects vyberte právě dva objekty @msg give `width` or `height` zadejte `width` nebo `height` + Marathi Maráthština + Gujarati Gudžarátština + Bengali Bengálština + Punjabi Paňdžábština + Tamil Tamilština + Telugu Telugština + Kannada Kannadština + Malayalam Malajálamština + Odia Urijština + Urdu Urdština VectorCraft {release} and later (version {n}) VectorCraft {release} a novější (verze {n}) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 1507f30ef9..8b67b907a9 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5940,4 +5940,14 @@ breakText Glyphs Glyffer Set Size of Each Angiv størrelse for hver @msg select exactly two objects markér præcis to objekter @msg give `width` or `height` angiv `width` eller `height` + Marathi Marathi + Gujarati Gujarati + Bengali Bengali + Punjabi Punjabi + Tamil Tamil + Telugu Telugu + Kannada Kannada + Malayalam Malayalam + Odia Oriya + Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} og nyere (version {n}) diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 22d2280978..7400e6f73a 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5628,4 +5628,14 @@ breakText Glyphs Glyphen Set Size of Each Größe einzeln festlegen @msg select exactly two objects wählen Sie genau zwei Objekte aus @msg give `width` or `height` geben Sie `width` oder `height` an + Marathi Marathi + Gujarati Gujarati + Bengali Bengalisch + Punjabi Punjabi + Tamil Tamil + Telugu Telugu + Kannada Kannada + Malayalam Malayalam + Odia Oriya + Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} und neuer (Version {n}) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a993b98407..19ba17dd75 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5995,4 +5995,14 @@ breakText Glyphs Γλύφοι Set Size of Each Ορισμός μεγέθους καθενός @msg select exactly two objects επιλέξτε ακριβώς δύο αντικείμενα @msg give `width` or `height` δώστε `width` ή `height` + Marathi Μαραθικά + Gujarati Γκουγιαράτι + Bengali Βεγγαλικά + Punjabi Παντζαπικά + Tamil Ταμιλικά + Telugu Τελούγκου + Kannada Κανάντα + Malayalam Μαλαγιάλαμ + Odia Όντια + Urdu Ούρντου VectorCraft {release} and later (version {n}) VectorCraft {release} και νεότερες (έκδοση {n}) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 19e524cf22..884ee8e7e3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5985,4 +5985,14 @@ breakText Glyphs Glifos Set Size of Each Definir el tamaño de cada uno @msg select exactly two objects selecciona exactamente dos objetos @msg give `width` or `height` indica `width` o `height` + Marathi Maratí + Gujarati Guyaratí + Bengali Bengalí + Punjabi Punyabí + Tamil Tamil + Telugu Telugu + Kannada Canarés + Malayalam Malayálam + Odia Oriya + Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} y posteriores (versión {n}) diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index eb9c0e5254..1b3528602f 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6073,4 +6073,14 @@ breakText Glyphs Merkit Set Size of Each Aseta kunkin koko @msg select exactly two objects valitse täsmälleen kaksi objektia @msg give `width` or `height` anna `width` tai `height` + Marathi Marathi + Gujarati Gudžarati + Bengali Bengali + Punjabi Pandžabi + Tamil Tamili + Telugu Telugu + Kannada Kannada + Malayalam Malajalam + Odia Orija + Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} ja uudemmat (versio {n}) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index d2ecba42df..46f1c08dbf 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6040,4 +6040,14 @@ breakText Glyphs Glyphes Set Size of Each Définir la taille de chaque objet @msg select exactly two objects sélectionnez exactement deux objets @msg give `width` or `height` indiquez `width` ou `height` + Marathi Marathi + Gujarati Goudjarati + Bengali Bengali + Punjabi Pendjabi + Tamil Tamoul + Telugu Télougou + Kannada Kannada + Malayalam Malayalam + Odia Odia + Urdu Ourdou VectorCraft {release} and later (version {n}) VectorCraft {release} et ultérieures (version {n}) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index b29f8ef71c..bf9ec10b27 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6029,4 +6029,14 @@ breakText Glyphs Glifák Set Size of Each Egyenkénti méret beállítása @msg select exactly two objects jelölj ki pontosan két objektumot @msg give `width` or `height` add meg a `width` vagy a `height` értéket + Marathi Maráthi + Gujarati Gudzsaráti + Bengali Bengáli + Punjabi Pandzsábi + Tamil Tamil + Telugu Telugu + Kannada Kannada + Malayalam Malajálam + Odia Odia + Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} és újabb (verzió: {n}) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 705f573705..99b7471115 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5940,4 +5940,14 @@ breakText Glyphs Glif Set Size of Each Atur ukuran masing-masing @msg select exactly two objects pilih tepat dua objek @msg give `width` or `height` berikan `width` atau `height` + Marathi Marathi + Gujarati Gujarati + Bengali Bengali + Punjabi Punjabi + Tamil Tamil + Telugu Telugu + Kannada Kannada + Malayalam Malayalam + Odia Oriya + Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} dan yang lebih baru (versi {n}) diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 9d6a31cca8..f3cbd75588 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5662,4 +5662,14 @@ breakText Glyphs Glifi Set Size of Each Imposta dimensione di ciascuno @msg select exactly two objects seleziona esattamente due oggetti @msg give `width` or `height` indica `width` o `height` + Marathi Marathi + Gujarati Gujarati + Bengali Bengalese + Punjabi Punjabi + Tamil Tamil + Telugu Telugu + Kannada Kannada + Malayalam Malayalam + Odia Odia + Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} e successive (versione {n}) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index abe51ff0a1..5363c5d06c 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -46,7 +46,8 @@ font-technology Variable バリアブル Character Direction 文字の方向 Digits 数字 Arabic アラビア数字 - Hindi ヒンディー数字 + Hindi ヒンディー語 +digits Hindi ヒンディー数字 Farsi ペルシャ数字 Favorites お気に入り Flip 反転 @@ -5728,4 +5729,14 @@ breakText Glyphs 字形 Set Size of Each 個別にサイズを設定 @msg select exactly two objects オブジェクトをちょうど 2 つ選択してください @msg give `width` or `height` `width` または `height` を指定してください + Marathi マラーティー語 + Gujarati グジャラート語 + Bengali ベンガル語 + Punjabi パンジャブ語 + Tamil タミル語 + Telugu テルグ語 + Kannada カンナダ語 + Malayalam マラヤーラム語 + Odia オディア語 + Urdu ウルドゥー語 VectorCraft {release} and later (version {n}) VectorCraft {release} 以降 (バージョン {n}) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index adcb85d678..8f2c407c4a 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6032,4 +6032,14 @@ breakText Glyphs გლიფები Set Size of Each თითოეულის ზომის დაყენება @msg select exactly two objects მონიშნეთ ზუსტად ორი ობიექტი @msg give `width` or `height` მიუთითეთ `width` ან `height` + Marathi მარათჰი + Gujarati გუჯარათი + Bengali ბენგალური + Punjabi პენჯაბური + Tamil ტამილური + Telugu ტელუგუ + Kannada კანადა + Malayalam მალაიალამური + Odia ორია + Urdu ურდუ VectorCraft {release} and later (version {n}) VectorCraft {release} და უფრო ახალი (ვერსია {n}) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index b3bf3cd62d..acf8135c32 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5625,4 +5625,14 @@ breakText Glyphs 글리프 Set Size of Each 각각 크기 설정 @msg select exactly two objects 개체를 정확히 두 개 선택하세요 @msg give `width` or `height` `width` 또는 `height`를 지정하세요 + Marathi 마라티어 + Gujarati 구자라트어 + Bengali 벵골어 + Punjabi 펀잡어 + Tamil 타밀어 + Telugu 텔루구어 + Kannada 칸나다어 + Malayalam 말라얄람어 + Odia 오리야어 + Urdu 우르두어 VectorCraft {release} and later (version {n}) VectorCraft {release} 이상 (버전 {n}) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c3bf46c3ee..51dd8b37e1 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5984,4 +5984,14 @@ breakText Glyphs Glyphs Set Size of Each Formaat van elk instellen @msg select exactly two objects selecteer precies twee objecten @msg give `width` or `height` geef `width` of `height` op + Marathi Marathi + Gujarati Gujarati + Bengali Bengaals + Punjabi Punjabi + Tamil Tamil + Telugu Telugu + Kannada Kannada + Malayalam Malayalam + Odia Odia + Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} en nieuwer (versie {n}) diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 519595ffcb..30203b1a10 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5898,4 +5898,14 @@ breakText Glyphs Glify Set Size of Each Ustaw rozmiar każdego @msg select exactly two objects zaznacz dokładnie dwa obiekty @msg give `width` or `height` podaj `width` lub `height` + Marathi Marathi + Gujarati Gudżarati + Bengali Bengalski + Punjabi Pendżabski + Tamil Tamilski + Telugu Telugu + Kannada Kannada + Malayalam Malajalam + Odia Orija + Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} i nowsze (wersja {n}) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index b07ec8f665..6ede5c3510 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5962,4 +5962,14 @@ breakText Glyphs Glifos Set Size of Each Definir Tamanho de Cada Um @msg select exactly two objects selecione exatamente dois objetos @msg give `width` or `height` informe `width` ou `height` + Marathi Marati + Gujarati Guzerate + Bengali Bengali + Punjabi Panjabi + Tamil Tâmil + Telugu Télugo + Kannada Canarim + Malayalam Malaiala + Odia Oriá + Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} e posteriores (versão {n}) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 685d6862b6..2bf406c749 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6020,4 +6020,14 @@ breakText Glyphs Глифы Set Size of Each Задать размер каждого @msg select exactly two objects выделите ровно два объекта @msg give `width` or `height` укажите `width` или `height` + Marathi Маратхи + Gujarati Гуджарати + Bengali Бенгальский + Punjabi Панджаби + Tamil Тамильский + Telugu Телугу + Kannada Каннада + Malayalam Малаялам + Odia Ория + Urdu Урду VectorCraft {release} and later (version {n}) VectorCraft {release} и новее (версия {n}) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index b5ff04674d..788d45c8af 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6095,4 +6095,14 @@ breakText Glyphs Glyfer Set Size of Each Ange storlek för vart och ett @msg select exactly two objects markera exakt två objekt @msg give `width` or `height` ange `width` eller `height` + Marathi Marathi + Gujarati Gujarati + Bengali Bengali + Punjabi Punjabi + Tamil Tamil + Telugu Telugu + Kannada Kannada + Malayalam Malayalam + Odia Oriya + Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} och senare (version {n}) diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 4961fcd152..50b7f213b3 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6000,4 +6000,14 @@ breakText Glyphs Glifler Set Size of Each Her Birinin Boyutunu Ayarla @msg select exactly two objects tam olarak iki nesne seç @msg give `width` or `height` `width` veya `height` belirt + Marathi Marathi dili + Gujarati Gücerat dili + Bengali Bengalce + Punjabi Pencapça + Tamil Tamilce + Telugu Telugu dili + Kannada Kannada dili + Malayalam Malayalam dili + Odia Oriya dili + Urdu Urduca VectorCraft {release} and later (version {n}) VectorCraft {release} ve sonrası (sürüm {n}) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 886675579b..03d912f327 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5642,4 +5642,14 @@ breakText Glyphs Гліфи Set Size of Each Задати розмір кожного @msg select exactly two objects виділіть рівно два об’єкти @msg give `width` or `height` укажіть `width` або `height` + Marathi Маратхі + Gujarati Гуджараті + Bengali Бенгальська + Punjabi Панджабі + Tamil Тамільська + Telugu Телугу + Kannada Каннада + Malayalam Малаялам + Odia Одія + Urdu Урду VectorCraft {release} and later (version {n}) VectorCraft {release} і новіші (версія {n}) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f0ed3842e2..cdea7542bb 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1624,7 +1624,8 @@ file-filter Templates Mẫu Highlight Substituted Fonts Đánh dấu phông thay thế Highlight Substituted Glyphs Đánh dấu Glyph bị thay thế Highlight Variable Đánh dấu biến - Hindi Hindi + Hindi Tiếng Hindi +digits Hindi Hindi History Lịch sử History Options… Tùy chọn lịch sử… Step Backward Lùi một bước @@ -5644,4 +5645,14 @@ breakText Glyphs Glyph Set Size of Each Đặt kích thước từng cái @msg select exactly two objects hãy chọn đúng hai đối tượng @msg give `width` or `height` hãy cho `width` hoặc `height` + Marathi Tiếng Marathi + Gujarati Tiếng Gujarati + Bengali Tiếng Bengali + Punjabi Tiếng Punjab + Tamil Tiếng Tamil + Telugu Tiếng Telugu + Kannada Tiếng Kannada + Malayalam Tiếng Malayalam + Odia Tiếng Odia + Urdu Tiếng Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} trở lên (phiên bản {n}) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b184706400..c485086b11 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2358,7 +2358,8 @@ font-script Japanese 汉字 Character Direction 字符方向 Digits 数字 Arabic 阿拉伯数字 - Hindi 印地数字 + Hindi 印地语 +digits Hindi 印地数字 Farsi 波斯数字 Proportional Oldstyle 比例旧式数字 Pucker & Bloat… 缩拢与膨胀… @@ -5884,4 +5885,14 @@ breakText Glyphs 字形 Set Size of Each 分别设置大小 @msg select exactly two objects 请恰好选择两个对象 @msg give `width` or `height` 请提供 `width` 或 `height` + Marathi 马拉地语 + Gujarati 古吉拉特语 + Bengali 孟加拉语 + Punjabi 旁遮普语 + Tamil 泰米尔语 + Telugu 泰卢固语 + Kannada 卡纳达语 + Malayalam 马拉雅拉姆语 + Odia 奥里亚语 + Urdu 乌尔都语 VectorCraft {release} and later (version {n}) VectorCraft {release} 及更高版本 (版本 {n}) diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 2b7e38a403..06ea604985 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3299,7 +3299,8 @@ font-script Japanese 漢字 Character Direction 字元方向 Digits 數字 Arabic 阿拉伯數字 - Hindi 印地數字 + Hindi 印地文 +digits Hindi 印地數字 Farsi 波斯數字 Proportional Oldstyle 比例舊式數字 Pucker & Bloat… 縮攏與膨脹… @@ -5681,4 +5682,14 @@ breakText Glyphs 字符 Set Size of Each 個別設定大小 @msg select exactly two objects 請選取正好兩個物件 @msg give `width` or `height` 請提供 `width` 或 `height` + Marathi 馬拉地文 + Gujarati 古吉拉特文 + Bengali 孟加拉文 + Punjabi 旁遮普文 + Tamil 坦米爾文 + Telugu 泰盧固文 + Kannada 坎那達文 + Malayalam 馬來亞拉姆文 + Odia 歐利亞文 + Urdu 烏都文 VectorCraft {release} and later (version {n}) VectorCraft {release} 及更新版本 (版本 {n}) diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 82445374b3..ebd80f1ed2 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -1,11 +1,12 @@ //! Character panel: font family / style, size, leading, kerning, tracking, vertical and horizontal //! scale, baseline shift, character rotation and the All Caps, Small Caps, Superscript, Subscript, -//! Underline and Strikethrough toggles. +//! Underline and Strikethrough toggles and the Language menu. use std::sync::{Mutex, OnceLock}; use egui::{Key, Ui, vec2}; use serde_json::{Value, json}; +use vectorcraft_doc::setup::{LANGUAGES, char_language_name}; use vectorcraft_doc::{CharStyle, NodeId, NodeKind}; use vectorcraft_tools::{Mods, ToolKey}; @@ -922,6 +923,17 @@ fn attributes(app: &mut VectorcraftApp, ui: &mut Ui) { } } }); + // Language: the characters are shaped in it, so that the font uses that language's forms. + ui.add_space(4.0); + let names: Vec<&str> = LANGUAGES.iter().map(|(n, _, _)| *n).collect(); + // Mixed: blank; a tag from a file that is not in the list: as it is. + let current = shared(app, |s| s.language.clone()) + .map_or_else(String::new, |l| char_language_name(l.as_deref()).map_or_else(|| l.unwrap_or_default(), str::to_string)); + widgets::label_row(ui, tl!("Language:"), 64.0, |ui| { + if let Some(name) = widgets::dropdown(ui, "ch-language", ¤t, &names, w - 72.0).and_then(|i| names.get(i)) { + format(app, json!({"language": name})); + } + }); } /// The `text.setFormat` params of the Superscript or Subscript toggle `p` for text whose @@ -1079,11 +1091,13 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { ui.add_enabled_ui(has, |ui| { ui.menu_button(format!(" {}", tl!("Digits")), |ui| { use vectorcraft_doc::Digits; + // The numeral systems, in the digits context: Hindi is also a language. + let digits_label = |s| crate::i18n::tr_ctx(crate::i18n::current(), "digits", s); for (label, d, key) in [ (tl!("Default"), Digits::Default, "default"), - (tl!("Arabic"), Digits::Arabic, "arabic"), - (tl!("Hindi"), Digits::Hindi, "hindi"), - (tl!("Farsi"), Digits::Farsi, "farsi"), + (digits_label("Arabic"), Digits::Arabic, "arabic"), + (digits_label("Hindi"), Digits::Hindi, "hindi"), + (digits_label("Farsi"), Digits::Farsi, "farsi"), ] { if menu_item(ui, label, true, digits == Some(d)) { format(app, json!({"digits": key})); diff --git a/docs/mcp.md b/docs/mcp.md index a03d5db9f8..baf64c4e29 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5034,6 +5034,21 @@ A digit the font lacks comes from a fallback font. Default and saved only when s {"name":"run_command","arguments":{"command":"text.setFormat","params":{"digits":"hindi"}}} ``` +## Language + +`text.setFormat {language}` (the selected type, or `ids`) and `text.setRangeStyle {id, start, end, language}` (a range) +set the language of the characters, as the Character panel's Language menu does: one of Document Setup's languages +(`document.setup {language}`), by name or BCP 47 tag, case-insensitive (`"Turkish"` or `"tr"`, `"Marathi"` or `"mr"`). +An unknown language is an error. The characters are shaped in it, so the font uses that language's forms (OpenType +`locl`): in Turkish, Source Serif 4 keeps `fi` as two letters and the dot on the i, where English makes the fi ligature. +Runs are saved with the tag, and English: USA, the default, as no language, so files without languages load and save +as before. New type takes the document's language. Character styles captured from type carry it, and `charStyle.new` / +`charStyle.setAttrs` take `attrs: {language}` the same way. One undo step. + +```json +{"name":"run_command","arguments":{"command":"text.setFormat","params":{"language":"Turkish"}}} +``` + ## Touch Type The Touch Type tool (`touchType`, Shift+T) changes one character at a time. A click on a character of a type object diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2adeb29a5d..6dd6db0b28 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (New Document: Save Preset in More Settings, #4893; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Type core: text shaped in its language, a Language per character, Indian languages, #4940 #4946 #4943; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -1403,6 +1403,7 @@ dialogs, Preview and Cancel, Zoom to Selection) and `command_sweep`. Commands: ` | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Type core: a Language per character (Character panel › Language, `text.setFormat` / `text.setRangeStyle {language}`, character styles), new type in the document's language; text is shaped in its language so fonts use their language forms (OpenType `locl`: Turkish `fi`, #4940, #4946); Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu in the language list (#4943); scores unchanged | | 2026-10-31 | minor | Selection tools: with Alt held at the press, a Direct Selection marquee selects every path it touches whole and keeps the Group Selection pointer (#4890); a press on a selected object's centre point selects the object whole and a drag from it moves it (#4891); regression tests in `direct/tests.rs`; scores and estimates unchanged. | | 2026-10-31 | minor | Arrange Tools add-on (a VectorCraft addition): evidence added; scores unchanged. | | 2026-10-31 | minor | Guides and snapping: Snap to Perpendicular and Snap to Tangent apply to an existing line's end dragged with Direct Selection, as the public pages describe for editing existing lines (the end anchor of a straight segment, not mid-line anchors or curved segments); a regression test covers both snaps, both toggles and non-snapping controls (#2530); scores and estimates unchanged. | diff --git a/docs/type-parity.md b/docs/type-parity.md index 4de41b37c3..3d76581f90 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (PDF import finds installed fonts whose PDF names hold hyphens or a composite font's CMap; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Language per character: text is shaped in its language, Character panel › Language, Indian languages; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -60,6 +60,7 @@ against Illustrator's public documentation; **estimated** unless noted. | CJK: Proportional Metrics (`palt` in horizontal type, `vpal` in vertical type) | done | #966 | | CJK: manual tate-chu-yoko | done | Character panel menu › Tate-chu-yoko (`text.setFormat` / `text.setRangeStyle {tateChuYoko}`), with Show East Asian Options: marked characters stand side by side across one em of a vertical column, squeezed to the em when wider; two or three half-width digits still do so without the mark; horizontal type keeps the mark and does not move them. Up/Down and Left/Right settings remain. Evidence: `tests_vertical::manual_tate_chu_yoko_sets_marked_characters_across_one_em`, `typecmd::tate_chu_yoko_is_a_character_attribute_saved_only_when_on` | | CJK: ruby, manual tate-chu-yoko | partial | ruby (ふりがな) for live text (`type.ruby`): a reading over a byte range, above (right of the column in vertical type) or below, start/centre/end alignment, size, overhang or squeeze; saved natively, laid out with its line growing, drawn on the canvas, in SVG and PDF (as outlines where ruby is present), in EPS, EMF/WMF and legacy `.ai` (legacy `.ai` writes type with ruby as outlines), and kept by Create Outlines, Expand Appearance and flattening, each glyph where the layout puts it (`typecmd::ruby_tests::create_outlines_keeps_the_ruby_where_it_is_laid_out`); manual tate-chu-yoko missing | #633 | +| Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). Not yet: hyphenation and spelling by it, `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set` | | No Break | done | Character panel menu (`text.setFormat` / `text.setRangeStyle {noBreak}`): the marked characters stay on one line, including across a space; a run that does not fit after earlier text moves together, and a run longer than the line stays together. Evidence: `layout::wrapping_tests::no_break_keeps_marked_characters_on_one_line`, `tests::no_break_keeps_marked_words_on_one_line`, `typecmd::no_break_is_a_character_attribute_saved_only_when_on` | | CJK: ruby | missing | #633 | | Inline symbols in text | beyond Illustrator | not scored | @@ -71,6 +72,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Language per character (#4946): Character panel › Language, `text.setFormat` / `text.setRangeStyle {language}`, character styles; text is shaped in its language (`locl`, #4940); new type takes the document's; Indian languages in the list (#4943); scores unchanged | | 2026-10-31 | minor | PDF import finds an installed font whose PDF name holds hyphens (`Noto-Sans-Bold` is Noto Sans, Bold: the longest part before a hyphen that names an installed family) and a composite font by its CIDFont's name rather than its base name, which ends in the CMap's (`Name-Identity-H`, [ISO 32000-1 §9.7.6.1](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)); a missing font is split only before a style part (`Helvetica-BoldOblique`), so it is reported as `MS PGothic`, not `MS`; scores unchanged | | 2026-10-31 | minor | Highlight Alternate Glyphs: an optional feature (such as `salt`) that changes a lam-alef ligature is highlighted again, only the required ligature staying clear, and a lam-alef with any combining mark (Arabic Extended-A/B/C included) counts as the ligature (#394); scores unchanged | | 2026-10-30 | minor | Highlight Alternate Glyphs leaves the required lam-alef ligature unhighlighted also in older Arabic fonts (such as legacy Arial) that put it in `liga` rather than `rlig` (#394); scores unchanged | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index fee3db42db..f7a7c1e16f 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (native Save As Version menu, refused-save alert, fixed Contributors table header, freeform point swatch opens its popover: #4931, #4933, #4944, #4953) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Character panel › Language, Indian languages in Document Setup › Language, #4946 #4943) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -381,6 +381,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Character panel › Language: the selected characters' language, from Document Setup's list, which gains Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu (#4946, #4943); the Digits menu's numeral names keep their own translations; scores unchanged | | 2026-11-01 | minor | VectorCraft Options' Version is a menu of the versions VectorCraft writes, each named by the releases that read it, and an uncompressible version turns Use Compression off (#4931); a save refused before writing shows the Can't save alert with the reason (#4933); About › Contributors' table keeps its header row above the scrolling rows (#4944); the Gradient panel's freeform point swatch opens the point's popover (#4953); scores unchanged | | 2026-10-31 | minor | A file opened from the file manager while VectorCraft runs opens as a new tab in that window, which comes to the front, on Windows and Linux (#4892); `--new-instance` opts out; scores unchanged | | 2026-10-31 | minor | Object › Path › Smooth: Auto-Smooth takes a shaky line to one smooth curve, and direct-selected anchors smooth only their section; scores unchanged | From 214fca7ca70611b673ce4d90e0137f28787bee44 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 01:37:54 +0700 Subject: [PATCH 165/260] Character: apply() sets the font in a helper of its own --- crates/engine/src/cmd/textedit.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 958c5f10df..0efc70bc6b 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -577,7 +577,8 @@ impl CharChange { Ok(()) } - pub(crate) fn apply(&self, st: &mut CharStyle) { + /// The font family, style and Variable Font settings of [`Self::apply`]. + fn apply_font(&self, st: &mut CharStyle) { if let Some(f) = &self.font { st.font_family = f.clone(); // Keep the style when the new family has it, else its closest match. @@ -596,6 +597,10 @@ impl CharChange { if let Some(v) = &self.font_axes { change_font_axes(st, v); } + } + + pub(crate) fn apply(&self, st: &mut CharStyle) { + self.apply_font(st); if let Some(v) = self.size { st.size = v; } From dfd07552c8173a6a7c0afe64aa92f14f2063aa92 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 09:33:42 -0700 Subject: [PATCH 166/260] Cursors: Caps Lock gives the drawing tools the crosshair While Caps Lock is on, the tools whose pointer General > Use Precise Cursors changes show the crosshair, and the saved preference does not change. The desktop app reads the lock state on macOS, Windows and Linux X11 and passes each change to the new view.capsLock command. A change to view.capsLock or usePreciseCursors through app.run refreshes the canvas pointer. The view.preciseCursors command is labeled Use Precise Cursors, so command search finds it by the preference's name. --- apps/vectorcraft/Cargo.toml | 9 +- apps/vectorcraft/src/app.rs | 3 + apps/vectorcraft/src/caps_lock.rs | 216 ++++++++++++++++++++++++ apps/vectorcraft/src/main.rs | 3 + crates/engine/src/cmd/views.rs | 8 + crates/engine/src/lib.rs | 2 + crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/prefs.rs | 25 +++ crates/engine/src/tooling.rs | 6 +- crates/ui-egui/src/app.rs | 10 ++ crates/ui-egui/src/app/commands.rs | 4 + crates/ui-egui/src/canvas/tests.rs | 20 +++ crates/ui-egui/src/menus/tests.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/palette.rs | 18 ++ docs/ui-parity.md | 2 +- 16 files changed, 321 insertions(+), 10 deletions(-) create mode 100644 apps/vectorcraft/src/caps_lock.rs diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 7af8c51eff..47d26eb7b6 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -55,8 +55,9 @@ pollster = "1" # read a pen's barrel button from its pointer messages. Win32_UI_Input_Pointer has # `GetPointerPenInfo`, which it uses to read the pen's pressure and which end of the pen is down. # Win32_System_Threading has `GetProcessAffinityMask`, which src/windows_cores.rs uses to count the -# cores the process may run on. -windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Threading", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] } +# cores the process may run on. Win32_UI_Input_KeyboardAndMouse has `GetKeyState`, which +# src/caps_lock.rs uses to read whether Caps Lock is on. +windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] } # The renderer's worker count follows those cores (src/windows_cores.rs). vectorcraft-render = { workspace = true } @@ -90,8 +91,8 @@ pollster = "1" winit = { version = "0.30", default-features = false, features = ["wayland-csd-adwaita-notitle"] } # A drawing tablet's pen pressure under X11 and XWayland (src/tablet.rs): XInput2 raw events on a # second X connection, x11rb's pure-Rust `RustConnection`. MIT OR Apache-2.0, already in the build -# through winit with the `xinput` feature. -x11rb = { version = "0.13", default-features = false, features = ["xinput"] } +# through winit with the `xinput` feature. XKB reads Caps Lock's locked modifier state (src/caps_lock.rs). +x11rb = { version = "0.13", default-features = false, features = ["xinput", "xkb"] } # Asks the Wayland compositor which GPU it draws with (linux-dmabuf feedback, src/compositor_gpu.rs), # so Automatic draws on that one. Both are already in the build through winit. diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index affb234660..423fb53fc7 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -68,6 +68,9 @@ impl eframe::App for App { // macOS converts the frame from sRGB to the display's profile (#2249). #[cfg(all(target_os = "macos", feature = "wgpu"))] super::mac_color_space::tag(ui); + if let Some(on) = self.host_caps_lock.read_transition() { + self.app.set_caps_lock(on); + } file_access::unconfined(|| self.app.ui(ui)); // Preferences are written when confirmed, not only at exit: a session ended any other way // (the system shutting down, the process ended or crashing) used to lose them (#1747). diff --git a/apps/vectorcraft/src/caps_lock.rs b/apps/vectorcraft/src/caps_lock.rs new file mode 100644 index 0000000000..231a37e037 --- /dev/null +++ b/apps/vectorcraft/src/caps_lock.rs @@ -0,0 +1,216 @@ +//! Read the host's Caps Lock state, which gives the drawing tools the precise crosshair while it is on. + +/// Only host transitions replace a value set by a script through `view.capsLock`. +#[derive(Default)] +pub struct HostCapsLock { + previous: Option<bool>, + #[cfg(target_os = "linux")] + x11: Option<X11CapsLock>, +} + +#[cfg(target_os = "linux")] +struct X11CapsLock { + connection: x11rb::rust_connection::RustConnection, + locked: bool, + initial_sequence: u16, +} + +impl HostCapsLock { + pub fn new(window: Option<&winit::window::Window>) -> Self { + #[cfg(target_os = "linux")] + let x11 = window.and_then(x11_connection); + #[cfg(not(target_os = "linux"))] + let _ = window; + Self { + previous: None, + #[cfg(target_os = "linux")] + x11, + } + } + + pub fn read_transition(&mut self) -> Option<bool> { + #[cfg(target_os = "linux")] + let current = match self.x11.as_mut() { + Some(state) => match state.poll() { + Some(locked) => Some(locked), + None => { + self.x11 = None; + None + } + }, + None => { + // Native Wayland does not expose the seat's XKB lock bit through winit or egui. + None + } + }; + #[cfg(any(target_os = "macos", windows))] + let current = Some(read()); + // This platform has no lock-state reader. + #[cfg(not(any(target_os = "macos", windows, target_os = "linux")))] + let current = None; + self.transition(current) + } + + fn transition(&mut self, reading: Option<bool>) -> Option<bool> { + reading.and_then(|current| self.observe(current)) + } + + fn observe(&mut self, current: bool) -> Option<bool> { + if self.previous.replace(current) == Some(current) { None } else { Some(current) } + } +} + +#[cfg(target_os = "linux")] +fn x11_connection(window: &winit::window::Window) -> Option<X11CapsLock> { + use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; + use x11rb::protocol::xkb; + if !matches!(window.window_handle().ok()?.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)) { + return None; + } + let (connection, _) = x11rb::connect(None).ok()?; + let supported = x11rb::protocol::xkb::use_extension(&connection, 1, 0).ok()?.reply().ok()?.supported; + if !supported { + return None; + } + // Subscribe before the initial read so changes during setup remain queued. + xkb::select_events( + &connection, + xkb::ID::USE_CORE_KBD.into(), + xkb::EventType::default(), + xkb::EventType::default(), + xkb::MapPart::default(), + xkb::MapPart::default(), + &xkb::SelectEventsAux { + state_notify: Some(xkb::SelectEventsAuxStateNotify { + affect_state: xkb::StatePart::MODIFIER_LOCK, + state_details: xkb::StatePart::MODIFIER_LOCK, + }), + ..Default::default() + }, + ) + .ok()? + .check() + .ok()?; + let (locked, initial_sequence) = read_x11(&connection)?; + Some(X11CapsLock { connection, locked, initial_sequence }) +} + +#[cfg(target_os = "linux")] +impl X11CapsLock { + fn poll(&mut self) -> Option<bool> { + use x11rb::connection::Connection as _; + use x11rb::protocol::Event; + while let Some(event) = self.connection.poll_for_event().ok()? { + if let Event::XkbStateNotify(state) = event + // Events queued before the initial GetState reply must not replace that newer snapshot. + && state.sequence.wrapping_sub(self.initial_sequence) < 0x8000 + { + self.locked = lock_modifier_is_set(state.locked_mods); + } + } + Some(self.locked) + } +} + +#[cfg(target_os = "linux")] +fn read_x11(connection: &x11rb::rust_connection::RustConnection) -> Option<(bool, u16)> { + use x11rb::protocol::xkb; + let state = xkb::get_state(connection, xkb::ID::USE_CORE_KBD.into()).ok()?.reply().ok()?; + Some((lock_modifier_is_set(state.locked_mods), state.sequence)) +} + +#[cfg(target_os = "linux")] +fn lock_modifier_is_set(modifiers: x11rb::protocol::xproto::ModMask) -> bool { + use x11rb::protocol::xproto::ModMask; + u16::from(modifiers) & u16::from(ModMask::LOCK) != 0 +} + +#[cfg(target_os = "macos")] +const MAC_CAPS_LOCK: usize = 1 << 16; + +#[cfg(target_os = "macos")] +fn mac_flags_have_caps_lock(flags: usize) -> bool { + flags & MAC_CAPS_LOCK != 0 +} + +#[cfg(target_os = "macos")] +pub fn read() -> bool { + mac_flags_have_caps_lock(objc2_app_kit::NSEvent::modifierFlags_class().bits()) +} + +#[cfg(windows)] +fn windows_state_has_caps_lock(state: i16) -> bool { + state & 1 != 0 +} + +#[cfg(windows)] +#[allow(unsafe_code)] +pub fn read() -> bool { + // GetKeyState reports the toggle bit for the calling UI thread's keyboard state. + use windows::Win32::UI::Input::KeyboardAndMouse::{GetKeyState, VK_CAPITAL}; + // SAFETY: `GetKeyState` takes a virtual-key code by value and reads no caller memory. + windows_state_has_caps_lock(unsafe { GetKeyState(i32::from(VK_CAPITAL.0)) }) +} + +// Querying XWayland for a native Wayland window would read a different keyboard. + +#[cfg(test)] +mod tests { + #[test] + fn no_host_reader_preserves_scripted_value_and_next_reading_transitions() { + let mut host = super::HostCapsLock::default(); + let mut session = vectorcraft_engine::Session::new(); + session.execute("view.capsLock", &serde_json::json!({"on": true})).unwrap(); + if let Some(on) = host.transition(None) { + session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); + } + assert!(session.caps_lock); + assert_eq!(host.transition(Some(false)), Some(false)); + } + + #[cfg(target_os = "linux")] + #[test] + fn no_x11_reader_has_no_transition() { + assert_eq!(super::HostCapsLock::default().read_transition(), None); + } + + #[test] + fn scripted_value_survives_unchanged_host_until_transition() { + let mut host = super::HostCapsLock::default(); + let mut session = vectorcraft_engine::Session::new(); + if let Some(on) = host.observe(false) { + session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); + } + session.execute("view.capsLock", &serde_json::json!({"on": true})).unwrap(); + if let Some(on) = host.observe(false) { + session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); + } + assert!(session.caps_lock); + session.execute("view.capsLock", &serde_json::json!({"on": false})).unwrap(); + if let Some(on) = host.observe(true) { + session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); + } + assert!(session.caps_lock); + if let Some(on) = host.observe(false) { + session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); + } + assert!(!session.caps_lock); + } + + #[cfg(target_os = "macos")] + #[test] + fn mac_modifier_flags_map_caps_lock() { + assert!(!super::mac_flags_have_caps_lock(0)); + assert!(!super::mac_flags_have_caps_lock(1 << 17)); + assert!(super::mac_flags_have_caps_lock(1 << 16)); + assert!(super::mac_flags_have_caps_lock((1 << 16) | (1 << 17))); + } + + #[cfg(windows)] + #[test] + fn windows_key_state_maps_toggle_bit() { + assert!(!super::windows_state_has_caps_lock(0)); + assert!(!super::windows_state_has_caps_lock(i16::MIN)); + assert!(super::windows_state_has_caps_lock(1)); + } +} diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 33d27ab352..a7d86d201e 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -19,6 +19,7 @@ #![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")] mod automation_args; +mod caps_lock; mod clipboard; #[cfg(feature = "wgpu")] mod compositor_gpu; @@ -94,6 +95,7 @@ use titlebar::{custom_titlebar, native_options}; struct App { app: VectorcraftApp, + host_caps_lock: caps_lock::HostCapsLock, /// Reported by wgpu when the window's graphics device is lost (a driver reset). graphics_loss: GraphicsLoss, /// The graphics device was lost and the unsaved changes are kept for Data Recovery. @@ -487,6 +489,7 @@ fn main() -> std::process::ExitCode { // The content and the pointer stay aligned on Windows (#1758). let window_frame = window_frame::service(cc, custom_titlebar); Ok(Box::new(App { + host_caps_lock: caps_lock::HostCapsLock::new(winit_window.as_deref()), app, graphics_loss, graphics_lost: false, diff --git a/crates/engine/src/cmd/views.rs b/crates/engine/src/cmd/views.rs index 281b99230f..8597a0963e 100644 --- a/crates/engine/src/cmd/views.rs +++ b/crates/engine/src/cmd/views.rs @@ -9,6 +9,7 @@ use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_req, fi pub fn specs() -> Vec<CommandSpec> { vec![ + cmd!(query "view.capsLock", "Caps Lock Cursor State", [], None, "{on?: bool} set or read the Caps Lock state the desktop app reports; while it is on, the drawing tools show the precise crosshair, and Use Precise Cursors keeps its saved value → {on}", always, caps_lock), cmd!( "view.saved.new", "New View…", @@ -54,6 +55,13 @@ fn glyph_snap_options(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!(s.prefs.glyph_snap)) } +fn caps_lock(s: &mut Session, p: &Value) -> Result<Value> { + if let Some(on) = p.get("on") { + s.caps_lock = on.as_bool().ok_or_else(|| bad("view.capsLock", "on must be true or false"))?; + } + Ok(json!({ "on": s.caps_lock })) +} + fn transparency_grid(s: &mut Session, p: &Value) -> Result<Value> { let st = s.doc_mut()?; st.transparency_grid = p.get("on").and_then(Value::as_bool).unwrap_or(!st.transparency_grid); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 595b22743a..d5b4bdb037 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -48,6 +48,8 @@ pub struct Session { docs: Vec<DocState>, active: Option<usize>, pub prefs: Prefs, + /// Whether Caps Lock is on, as the desktop host reports it; never saved with the preferences. + pub caps_lock: bool, /// Fill/stroke for new art (the toolbar proxy). pub paint: PaintDefaults, /// Which proxy is in front (true = Fill, false = Stroke) — the X key toggles. diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index a331144d5b..b7e7f51fe2 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -28,6 +28,7 @@ impl Session { docs: vec![], active: None, prefs: Prefs::default(), + caps_lock: false, paint: PaintDefaults::default(), fill_active: true, clipboard: Clipboard::default(), diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index d2123ef87e..feaba57a1f 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -389,6 +389,31 @@ fn use_precise_cursors_makes_drawing_cursors_crosshairs() { assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Eyedropper); } +/// Caps Lock gives the drawing tools the precise crosshair while it is on, and leaves the saved +/// Use Precise Cursors preference as it was. +#[test] +fn caps_lock_gives_drawing_tools_the_crosshair() { + use vectorcraft_tools::{Cursor, Mods}; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let cursor = |s: &mut Session, tool: &str| { + s.select_tool(tool, ViewInfo::default()).unwrap(); + s.cursor(vectorcraft_geom::Point::new(300.0, 300.0), Mods::default(), ViewInfo::default()) + }; + assert_eq!(s.execute("view.capsLock", &json!({})).unwrap(), json!({"on": false})); + assert_eq!(s.execute("view.capsLock", &json!({"on": true})).unwrap(), json!({"on": true})); + assert!(!s.prefs.use_precise_cursors, "Caps Lock leaves the preference off"); + assert_eq!(cursor(&mut s, "pen"), Cursor::Crosshair); + assert_eq!(cursor(&mut s, "lasso"), Cursor::Crosshair); + assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Crosshair); + assert_eq!(cursor(&mut s, "selection"), Cursor::Arrow); + assert_eq!(s.execute("view.capsLock", &json!({"on": false})).unwrap(), json!({"on": false})); + assert_eq!(cursor(&mut s, "pen"), Cursor::Pen); + assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Eyedropper); + assert!(s.execute("view.capsLock", &json!({"on": 1})).is_err()); + assert_eq!(s.execute("view.capsLock", &json!({})).unwrap(), json!({"on": false})); +} + /// Use Precise Cursors changes the pointer of the tools that have one of their own: off, each shows its own /// pointer; on, a crosshair. Every other drawing tool shows a crosshair either way, and the Type tool and the /// Scissors over no path keep theirs. diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 90f4ff61ce..642d9a0349 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -604,8 +604,8 @@ impl Session { v } - /// The pointer the active tool shows at `p` (General › Use Precise Cursors makes the drawing - /// tools' a crosshair, [`Cursor::precise`]). With Cmd held, the pointer of the selection tool a + /// The pointer the active tool shows at `p` (General › Use Precise Cursors, or Caps Lock while + /// it is on, makes the drawing tools' a crosshair, [`Cursor::precise`]). With Cmd held, the pointer of the selection tool a /// press would borrow ([`Self::lend_selection_tool`]). pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor { let lent = if mods.cmd && self.lender.is_none() { self.lent_tool(self.tool.id(), &mods) } else { None }; @@ -619,7 +619,7 @@ impl Session { } None => self.with_tool_cx(view, |t, cx| t.cursor(cx, p, mods)), }; - if self.prefs.use_precise_cursors { c.precise() } else { c } + if self.prefs.use_precise_cursors || self.caps_lock { c.precise() } else { c } } pub fn tool_options(&self) -> Value { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 13d5a00d8a..355322a78b 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -31,6 +31,16 @@ mod view; pub use fonts::MAX_RECENT_FONTS; impl VectorcraftApp { + /// Takes the host's Caps Lock state, which gives the drawing tools the crosshair while it is on + /// without changing the saved Use Precise Cursors preference. + pub fn set_caps_lock(&mut self, on: bool) { + if self.session.caps_lock != on + && let Err(err) = self.run("view.capsLock", json!({ "on": on })) + { + log::error!("Could not update Caps Lock cursor state: {err}"); + } + } + /// The app around `session`, reaching the platform through `services` (file pickers, the /// clipboard, files and the like). It starts cataloguing the installed fonts at once, gives /// Data Recovery the host's store and makes a view for each open document. diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 2cbbf3eb13..8ca150101a 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -92,7 +92,11 @@ impl VectorcraftApp { let ime_view = self.view_info(); let ime_target = crate::ime::target(&mut self.session, ime_view); let ime_before = crate::ime::stamp(&mut self.session, ime_view); + let cursor_settings = (self.session.caps_lock, self.session.prefs.use_precise_cursors); let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string()); + if r.is_ok() && cursor_settings != (self.session.caps_lock, self.session.prefs.use_precise_cursors) { + self.canvas.hover_cursor = None; + } if r.is_ok() && let Some(ctx) = self.ui_ctx.clone() { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index f7361da0ca..1bcc164a36 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -75,6 +75,26 @@ fn system_cursors_show_the_same_crosshair_with_precise_cursors_on_or_off() { } } +/// A change to Caps Lock or to Use Precise Cursors through `app.run` (the host, the control channel, +/// MCP) refreshes the pointer over the canvas without the pointer moving. +#[test] +fn command_cursor_settings_refresh_hover_cursor_while_view_moves() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.session.select_tool("pen", vectorcraft_engine::ViewInfo::default()).unwrap(); + app.hover_doc = Some(Point::new(200.0, 150.0)); + let mods = Mods::default(); + let view = vectorcraft_engine::ViewInfo::default(); + assert_eq!(hover_cursor(&mut app, mods, view, false), Some(Cursor::Pen)); + + app.run("view.capsLock", json!({"on": true})).unwrap(); + assert_eq!(hover_cursor(&mut app, mods, view, false), Some(Cursor::Crosshair)); + app.run("view.capsLock", json!({"on": false})).unwrap(); + assert_eq!(hover_cursor(&mut app, mods, view, false), Some(Cursor::Pen)); + app.run("prefs.set", json!({"key": "usePreciseCursors", "value": true})).unwrap(); + assert_eq!(hover_cursor(&mut app, mods, view, false), Some(Cursor::Crosshair)); +} + /// #826: in a turned view each ruler still has ticks along its whole length; at 0° the top one /// reads x where the canvas has it. #[test] diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 17a8864c10..046639b942 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -524,7 +524,7 @@ fn precise_cursors_command_toggles_the_preference() { fn precise_cursors_command_is_listed_and_assignable_in_the_shortcut_editor() { use crate::shortcut_editor as ed; let e = ed::entry("view.preciseCursors").expect("listed in the editor"); - assert_eq!((e.label.as_str(), e.group.as_str(), e.is_tool), ("Precise Cursors", "View", false)); + assert_eq!((e.label.as_str(), e.group.as_str(), e.is_tool), ("Use Precise Cursors", "View", false)); assert_eq!(ed::default_of("view.preciseCursors"), None, "no default key"); let mut overrides = craft_keymap::Overrides::new(); assert_eq!(ed::effective_in(&overrides, "view.preciseCursors"), None); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index bd633da60e..355da568fb 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -187,7 +187,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ), ( "view.preciseCursors", - "Precise Cursors", + "Use Precise Cursors", "", "{} toggle General › Use Precise Cursors: the drawing tools' pointers become a crosshair → true when on", ), diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index ec205e4f54..7cad17d0cb 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -176,6 +176,24 @@ mod tests { } } + /// Searching for the preference's name, Use Precise Cursors, finds the command that toggles it, + /// and choosing the first result changes the preference. + #[test] + fn use_precise_cursors_palette_result_toggles_the_preference() { + let ctx = egui::Context::default(); + let query = "use precise cursors"; + let entries = entries(&ctx, Lang::EN); + let matches: Vec<&Entry> = entries.iter().filter(|e| query.split_whitespace().all(|word| e.haystack.contains(word))).take(14).collect(); + assert!(matches.iter().any(|e| e.id == "view.preciseCursors"), "preference toggle appears for its name"); + assert!(entries.iter().filter(|e| e.id == "view.capsLock").all(|e| e.shown != "Use Precise Cursors")); + + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let before = app.session.prefs.use_precise_cursors; + let first = matches.first().expect("query has a result"); + menus::invoke(&mut app, &first.id, json!({})); + assert_ne!(app.session.prefs.use_precise_cursors, before, "first result toggles the preference"); + } + /// The palette lists `select.key` once, as Cancel Key Object (#541): a pick runs it with no id, /// which cancels the key object. `engine.commands` gives agents the same label. #[test] diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f7a7c1e16f..a135d587c7 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -240,7 +240,7 @@ tools, never checked side by side) isn't captured row by row. | Polygon/Star exact-size placement remembers the chosen sides/points for later drags and dialog openings; Cancel preserves the previous count | done | Session tool options; existing dialog-opening gestures retained; regression in `toolbar.rs` | | Tool double-click opens its options | done | | | Per-platform mapping (Cmd ↔ Ctrl, Option ↔ Alt) | done | | -| Eyedropper cursor; Use Precise Cursors | partial | original pipette at the sampling tip, distinct from the precise crosshair at five DPI scales (#1269); OS cursor display and Caps Lock unverified; a Precise Cursors command toggles the preference and can take a shortcut (#1663); cursors are painted into the window on Wayland (#1652, not run on Linux) | +| Eyedropper cursor; Use Precise Cursors | partial | original pipette at the sampling tip, distinct from the precise crosshair at five DPI scales (#1269); OS cursor display unverified; while Caps Lock is on, the tools that Use Precise Cursors changes show the crosshair, and the saved preference does not change (the desktop app reads the lock state on macOS, Windows and Linux X11, not on native Wayland; `view.capsLock` reads or sets it); a Use Precise Cursors command toggles the preference and can take a shortcut (#1663); cursors are painted into the window on Wayland (#1652, not run on Linux) | | Every tool's modifiers checked against the shortcut reference | missing | this is the fidelity pass | ## Keyboard shortcuts From 23da2fe46190c6d5da3fdc39a6407d57d327db26 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 09:52:57 -0700 Subject: [PATCH 167/260] Part of #3187: a gradient mesh made from an ellipse keeps its shape Create Gradient Mesh and a Mesh tool click estimated each border edge's handles from the surface's derivatives, so the mesh's border cut across a curved outline: a 1x1 mesh over a 400 x 300 pt ellipse came out up to 7 pt off it, with corners at its four mesh points. Each border edge now takes the handles of the cubic that best fits the outline between its points, and handles where two border edges meet along a side stay collinear. Deleting a mesh line (Alt-click with the Mesh tool) joined the two edges on either side with a straight line, which turned the ellipse's border into a diamond. The joined edge now keeps the outer handles, grown back to the length they had before the line split the edge. --- crates/doc/src/live.rs | 54 +++++++++++++++ crates/doc/src/live/mesh.rs | 131 +++++++++++++++++++++++++++++++++--- 2 files changed, 177 insertions(+), 8 deletions(-) diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 304b7fede4..cd96cd444d 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -233,6 +233,60 @@ mod tests { assert_eq!(envelope_mapper(&kind, Rect::new(0.0, 0.0, 100.0, 100.0))(p), p); } + /// How far the border of `m` strays from the ellipse in `r`, in points (measured across the + /// ellipse's short radius), checked at 20 places along every border edge. + fn mesh_border_off_ellipse(m: &GradientMesh, r: Rect) -> f64 { + let (rows, cols) = (m.rows as usize, m.cols as usize); + let edges = (0..cols).flat_map(|c| [m.edge_u(0, c), m.edge_u(rows, c)]).chain((0..rows).flat_map(|k| [m.edge_v(k, 0), m.edge_v(k, cols)])); + let (c, a, b) = (r.center(), r.width() / 2.0, r.height() / 2.0); + edges + .flat_map(|e| (0..=20).map(move |i| e.eval(f64::from(i) / 20.0))) + .map(|p| ((p.x - c.x) / a).hypot((p.y - c.y) / b) - 1.0) + .fold(0.0f64, |w, d| w.max(d.abs() * a.min(b))) + } + + /// #3187: a gradient mesh made from an ellipse keeps the ellipse's shape: a Mesh tool click + /// (a 1×1 mesh with lines through the point) and Create Gradient Mesh's 4×4 grid both lay + /// their border on the outline, within about twice the 0.35 pt the outline is flattened to. + /// The 1×1 mesh was up to 7 pt off this 400 × 300 pt ellipse. + #[test] + fn a_mesh_from_an_ellipse_keeps_its_outline() { + const OFF: f64 = 0.75; + let r = Rect::new(100.0, 100.0, 500.0, 400.0); + let e = shapes::ellipse(r); + for (rows, cols) in [(1, 1), (4, 4), (2, 5)] { + let m = GradientMesh::for_path(&e, rows, cols, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); + let off = mesh_border_off_ellipse(&m, r); + assert!(off < OFF, "{rows}×{cols} mesh: border {off} pt off the ellipse"); + } + let made = GradientMesh::for_path(&e, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); + let mut m = made.clone(); + // Off centre, so each line splits its edges unevenly. + let i = m.add_lines_at(Point::new(200.0, 330.0)).unwrap(); + let off = mesh_border_off_ellipse(&m, r); + assert!(off < OFF, "after a Mesh tool click: {off} pt"); + // Deleting the lines again (Alt-click) gives the border back as it was. + assert!(m.remove_point_lines(i)); + assert_eq!((m.rows, m.cols), (1, 1)); + for (k, (now, was)) in m.points.iter().zip(&made.points).enumerate() { + let moved = now.handles.iter().zip(&was.handles).map(|(a, b)| (*a - *b).hypot()).fold(0.0, f64::max); + assert!(now.p.distance(was.p) < 1e-6 && moved < 1e-3, "point {k}: {now:?}, made as {was:?}"); + } + // With a handle at the new border point shortened since, the two edges no longer make one + // curve: the merged edge is straight rather than grown past its ends. + let mut m = made.clone(); + let i = m.add_lines_at(Point::new(200.0, 330.0)).unwrap(); + let top = m.idx(0, 1); + m.points[top].handles[H_LEFT] *= 1e-4; + assert!(m.remove_point_lines(i)); + let (a, b) = (m.points[0].p, m.points[1].p); + assert!((m.points[0].handles[H_RIGHT] - (b - a) / 3.0).hypot() < 1e-9, "{:?}", m.points[0].handles); + // A rectangle's mesh keeps straight edges with handles a third of the way along. + let m = GradientMesh::for_path(&shapes::rectangle(Rect::new(0.0, 0.0, 90.0, 60.0)), 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); + let e = m.edge_u(0, 0); + assert!(e.p1.distance(Point::new(30.0, 0.0)) < 1e-6 && e.p2.distance(Point::new(60.0, 0.0)) < 1e-6, "{e:?}"); + } + #[test] fn mesh_insert_and_remove_lines() { let mut m = diff --git a/crates/doc/src/live/mesh.rs b/crates/doc/src/live/mesh.rs index e6ba1656f1..a87cbd9b4f 100644 --- a/crates/doc/src/live/mesh.rs +++ b/crates/doc/src/live/mesh.rs @@ -166,6 +166,76 @@ impl Coons { // Gradient meshes // ===================================================================================== +/// The handles, as offsets from `ends`, of the cubic from `ends.0` to `ends.1` that comes closest +/// (least squares) to `side` between `span.0` and `span.1`; `None` when they can't be computed. +/// Each point of the side is matched to the curve's nearest point, refined over a few rounds. +fn fit_edge(side: &[Point], span: (f64, f64), ends: (Point, Point)) -> Option<(Vec2, Vec2)> { + const N: usize = 32; + const ROUNDS: usize = 6; + let (p0, p3) = (ends.0, ends.1); + let qs: Vec<Point> = (1..N).map(|i| Coons::sample(side, span.0 + (span.1 - span.0) * i as f64 / N as f64)).collect(); + let mut ts: Vec<f64> = (1..N).map(|i| i as f64 / N as f64).collect(); + let mut fit = None; + for _ in 0..ROUNDS { + let (mut c11, mut c12, mut c22) = (0.0, 0.0, 0.0); + let (mut x1, mut x2) = (Vec2::ZERO, Vec2::ZERO); + for (q, &t) in qs.iter().zip(&ts) { + let s = 1.0 - t; + let (b0, b1, b2, b3) = (s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t); + let r = q.to_vec2() - b0 * p0.to_vec2() - b3 * p3.to_vec2(); + c11 += b1 * b1; + c12 += b1 * b2; + c22 += b2 * b2; + x1 += b1 * r; + x2 += b2 * r; + } + let det = c11 * c22 - c12 * c12; + if det.abs() < 1e-12 { + break; + } + let (p1, p2) = (((c22 * x1 - c12 * x2) / det).to_point(), ((c11 * x2 - c12 * x1) / det).to_point()); + if !(p1.is_finite() && p2.is_finite()) { + break; + } + fit = Some((p1 - p0, p2 - p3)); + // One Newton step towards the nearest point of the curve for each point of the side. + let c = CubicBez::new(p0, p1, p2, p3); + let (a, b, k) = (p1 - p0, p2 - p1, p3 - p2); + for (q, t) in qs.iter().zip(ts.iter_mut()) { + let s = 1.0 - *t; + let v = 3.0 * (s * s * a + 2.0 * s * *t * b + *t * *t * k); + let acc = 6.0 * (s * (b - a) + *t * (k - b)); + let e = c.eval(*t) - *q; + let den = v.hypot2() + e.dot(acc); + if den.abs() > 1e-12 { + *t = (*t - e.dot(v) / den).clamp(0.0, 1.0); + } + } + } + fit +} + +/// The handles of one cubic standing for two edges that meet at point `mid.0`, whose handles +/// towards them are `mid.1` (towards `a`) and `mid.2` (towards `b`), as offsets from their outer +/// ends: each outer handle grown back by the share of the curve its edge had, which undoes the +/// split [`GradientMesh::insert_row`] and [`GradientMesh::insert_col`] make, so deleting a mesh +/// line keeps the curve of the border it crossed (#3187). The share is the split parameter, read +/// from the lengths of the middle handles. When the edges no longer fit one cubic (a point or a +/// handle was moved since the split), the cubic grown back would not pass through the middle +/// point, and the merged edge is straight. +fn merged_handles(a: (Point, Vec2), mid: (Point, Vec2, Vec2), b: (Point, Vec2)) -> (Vec2, Vec2) { + let straight = ((b.0 - a.0) / 3.0, (a.0 - b.0) / 3.0); + let (la, lb) = (mid.1.hypot(), mid.2.hypot()); + let t = la / (la + lb); + if !(0.01..=0.99).contains(&t) { + return straight; + } + let (ha, hb) = (a.1 / t, b.1 / (1.0 - t)); + let through = CubicBez::new(a.0, a.0 + ha, b.0 + hb, b.0).eval(t); + let tol = 1e-3 * (a.0.distance(mid.0) + mid.0.distance(b.0)).max(1e-9); + if ha.is_finite() && hb.is_finite() && through.distance(mid.0) <= tol { (ha, hb) } else { straight } +} + /// `0, 1/n, …, 1` for `n` (clamped to 1..=200) even steps. fn even_steps(n: u32) -> Vec<f64> { let n = n.clamp(1, 200); @@ -283,7 +353,49 @@ impl GradientMesh { /// colour and opacity `color_at` gives at its position (a gradient fill's, say). pub fn for_path_with(path: &PathData, rows: u32, cols: u32, color_at: &dyn Fn(Point) -> (Color, f32)) -> Option<Self> { let coons = Coons::from_path(path)?; - Some(Self::from_grid(&even_steps(cols), &even_steps(rows), &|u, v| coons.eval(u, v), &|_, _, p| color_at(p))) + let (us, vs) = (even_steps(cols), even_steps(rows)); + let mut m = Self::from_grid(&us, &vs, &|u, v| coons.eval(u, v), &|_, _, p| color_at(p)); + m.fit_border(&coons, &us, &vs); + Some(m) + } + + /// Give each edge on the mesh's border the handles that make it follow the outline it stands + /// for, in place of the handles [`Self::from_grid`] estimates from the surface's derivatives + /// (#3187). Where two border edges meet along a side, their handles are made collinear, so the + /// border stays smooth there; the four corners keep the handles their own edges were fitted with. + fn fit_border(&mut self, coons: &Coons, us: &[f64], vs: &[f64]) { + let (rows, cols) = (self.rows as usize, self.cols as usize); + if !self.is_valid() || us.len() != cols + 1 || vs.len() != rows + 1 { + return; + } + let edges = [(0, &coons.top), (rows, &coons.bottom)] + .map(|(r, side)| (r, side, true)) + .into_iter() + .chain([(0, &coons.left), (cols, &coons.right)].map(|(c, side)| (c, side, false))); + for (line, side, along_u) in edges { + let (n, steps) = if along_u { (cols, us) } else { (rows, vs) }; + for k in 0..n { + let (a, b, out, back) = if along_u { + (self.idx(line, k), self.idx(line, k + 1), H_RIGHT, H_LEFT) + } else { + (self.idx(k, line), self.idx(k + 1, line), H_DOWN, H_UP) + }; + if let Some((h1, h2)) = fit_edge(side, (steps[k], steps[k + 1]), (self.points[a].p, self.points[b].p)) { + self.points[a].handles[out] = h1; + self.points[b].handles[back] = h2; + } + } + for k in 1..n { + let (i, out, back) = if along_u { (self.idx(line, k), H_RIGHT, H_LEFT) } else { (self.idx(k, line), H_DOWN, H_UP) }; + let h = &mut self.points[i].handles; + let (fwd, bwd) = (h[out], h[back]); + let dir = (fwd.normalize() - bwd.normalize()).normalize(); + if fwd.hypot2() > 0.0 && bwd.hypot2() > 0.0 && dir.is_finite() { + h[out] = dir * fwd.hypot(); + h[back] = -dir * bwd.hypot(); + } + } + } } /// Create Gradient Mesh → Appearance: lighten the points towards white, to the centre or to @@ -792,10 +904,11 @@ impl GradientMesh { let above = self.idx(r - 1, cc); let below = self.idx(r + 1, cc); let mid = self.idx(r, cc); - let (pa, pm, pb) = (self.points[above].p, self.points[mid].p, self.points[below].p); - let _ = pm; - self.points[above].handles[H_DOWN] = (pb - pa) / 3.0; - self.points[below].handles[H_UP] = (pa - pb) / 3.0; + let (pa, pb, m) = (self.points[above].p, self.points[below].p, &self.points[mid]); + let hm = (m.p, m.handles[H_UP], m.handles[H_DOWN]); + let (down, up) = merged_handles((pa, self.points[above].handles[H_DOWN]), hm, (pb, self.points[below].handles[H_UP])); + self.points[above].handles[H_DOWN] = down; + self.points[below].handles[H_UP] = up; } self.points.drain(r * w..(r + 1) * w); self.rows -= 1; @@ -806,9 +919,11 @@ impl GradientMesh { let rows = self.rows as usize; for rr in 0..=rows { let (l, rt) = (rr * w + c - 1, rr * w + c + 1); - let (pl, pr) = (self.points[l].p, self.points[rt].p); - self.points[l].handles[H_RIGHT] = (pr - pl) / 3.0; - self.points[rt].handles[H_LEFT] = (pl - pr) / 3.0; + let (pl, pr, m) = (self.points[l].p, self.points[rt].p, &self.points[rr * w + c]); + let hm = (m.p, m.handles[H_LEFT], m.handles[H_RIGHT]); + let (right, left) = merged_handles((pl, self.points[l].handles[H_RIGHT]), hm, (pr, self.points[rt].handles[H_LEFT])); + self.points[l].handles[H_RIGHT] = right; + self.points[rt].handles[H_LEFT] = left; } let mut k = 0; self.points.retain(|_| { From cf656e2b70093c7f0305487e50f391ae4322601f Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 02:07:08 +0700 Subject: [PATCH 168/260] Gradient mesh tests: add_lines_at takes the click tolerance (#4954) --- crates/doc/src/live.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index cd96cd444d..9a2aa4fea5 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -262,7 +262,7 @@ mod tests { let made = GradientMesh::for_path(&e, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); let mut m = made.clone(); // Off centre, so each line splits its edges unevenly. - let i = m.add_lines_at(Point::new(200.0, 330.0)).unwrap(); + let i = m.add_lines_at(Point::new(200.0, 330.0), 0.0).unwrap(); let off = mesh_border_off_ellipse(&m, r); assert!(off < OFF, "after a Mesh tool click: {off} pt"); // Deleting the lines again (Alt-click) gives the border back as it was. @@ -275,7 +275,7 @@ mod tests { // With a handle at the new border point shortened since, the two edges no longer make one // curve: the merged edge is straight rather than grown past its ends. let mut m = made.clone(); - let i = m.add_lines_at(Point::new(200.0, 330.0)).unwrap(); + let i = m.add_lines_at(Point::new(200.0, 330.0), 0.0).unwrap(); let top = m.idx(0, 1); m.points[top].handles[H_LEFT] *= 1e-4; assert!(m.remove_point_lines(i)); From 69985f49980ccc2d0252695d84ab0eabffb76292 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 01:49:54 +0700 Subject: [PATCH 169/260] Fix #4928: Arrange Tools: Group Overlapping Objects addon.arrange.groupOverlapping groups the selected top-level objects whose visual bounds overlap or touch, chains included (union-find over a sweep along x, at most 20000 objects), only within one layer or group. Each group takes its frontmost member's stacking place; one undo step, all groups made in one pass over the tree. Menu item, tests, sweep case, catalog rows and docs. --- ROADMAP.md | 4 +- crates/engine/src/cmd/addons/arrange.rs | 90 ++++++++++++++++++- crates/engine/src/cmd/addons/arrange/tests.rs | 77 +++++++++++++++- crates/engine/tests/command_sweep.rs | 1 + crates/ui-egui/src/addons/arrange.rs | 3 +- crates/ui-egui/src/addons/arrange/tests.rs | 14 +++ crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/bs.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + docs/mcp.md | 1 + docs/target-app-parity.md | 7 +- docs/ui-parity.md | 4 +- 35 files changed, 272 insertions(+), 7 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 3511fe3f23..c943bbb027 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -9,7 +9,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Progress log rows for the Arrange Tools add-on, Export for Screens as the reference app's dialog and the 2026-10-31 community landings; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for Group Overlapping Objects in the Arrange Tools add-on; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. - 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged. - 2026-10-30: Gradient panel presets: a Presets menu applies one of the built-in gradient libraries' presets (grouped by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the current gradient as a preset, kept with the preferences, and deletes saved ones (`gradient.presets.list/apply/save/delete`). @@ -204,6 +205,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Progress log row for Group Overlapping Objects (Arrange Tools add-on, #4928); headline numbers unchanged. | | 2026-10-31 | minor | Progress log row for Export for Screens laid out as the reference app's (#4895) and the 2026-10-31 community landings; headline numbers unchanged. | | 2026-10-31 | minor | Progress log row for the Arrange Tools add-on; headline numbers unchanged. | | 2026-10-29 | minor | Progress log row for the Linux Flatpak clipboard's core Wayland protocol text fallback; headline numbers unchanged. | diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 2011559c3b..986016213e 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -2,14 +2,17 @@ //! out in rows and columns, a row or a column; Swap Objects swaps the places (and sizes) of two; //! Replace with Top Object puts a copy of the topmost selected object in place of each of the //! others; and Set Size of Each gives every selected object an exact width and height. Places and -//! sizes are measured and set as `object.setBounds` does. Its submenu (Object › Plug-ins › Arrange +//! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the +//! objects whose visual bounds overlap. Its submenu (Object › Plug-ins › Arrange //! Tools), its dialogs and Zoom to Selection (a view command) are the UI's. #[cfg(test)] mod tests; +use std::sync::Arc; + use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, OrientedBox}; +use vectorcraft_doc::{Node, NodeId, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect}; use vectorcraft_render::effects; @@ -25,6 +28,8 @@ const LIMIT: f64 = 1e6; const LEAST: f64 = 0.001; /// The most columns Arrange in Grid takes. const MAX_COLUMNS: u64 = 10_000; +/// The most objects Group Overlapping Objects looks at. +const MAX_OBJECTS: usize = 20_000; pub fn specs() -> Vec<CommandSpec> { vec![ @@ -64,6 +69,15 @@ pub fn specs() -> Vec<CommandSpec> { has_selection, size ), + cmd!( + "addon.arrange.groupOverlapping", + "Group Overlapping Objects", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{} group the selected objects (the top-level ones, at most 20000) wherever their visual bounds overlap or touch, chains included (when A overlaps B and B overlaps C, all three go in one group), as one undo step. Only objects in the same layer or group are grouped together, objects that overlap nothing stay as they are, and each new group goes where its frontmost member was in the stacking order; the new groups and the objects left alone stay selected → {groups: [id…], grouped (how many objects went into groups)}", + has_multi, + group_overlapping + ), ] } @@ -270,3 +284,75 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> { transform_each(s, "Set Size of Each", strokes, &xfs)?; Ok(json!({ "count": xfs.len() })) } + +/// The sets of two or more of `items` (each in the order given) whose rects overlap or touch, +/// chains included, among items of the same key (parent). A sweep along x: only the rects still +/// open where each one starts are compared with it. +fn overlapping<K: PartialEq>(items: &[(K, Rect)]) -> Vec<Vec<usize>> { + fn root(up: &mut [usize], mut i: usize) -> usize { + while up[i] != i { + up[i] = up[up[i]]; + i = up[i]; + } + i + } + let mut up: Vec<usize> = (0..items.len()).collect(); + let mut order: Vec<usize> = (0..items.len()).collect(); + order.sort_by(|a, b| items[*a].1.x0.total_cmp(&items[*b].1.x0)); + let mut open: Vec<usize> = vec![]; + for i in order { + let (key, r) = (&items[i].0, items[i].1); + open.retain(|&j| items[j].1.x1 >= r.x0); + for &j in &open { + let (k, o) = (&items[j].0, items[j].1); + if k == key && o.y0 <= r.y1 && r.y0 <= o.y1 { + let (a, b) = (root(&mut up, i), root(&mut up, j)); + up[a] = b; + } + } + open.push(i); + } + let mut sets: Vec<Vec<usize>> = vec![vec![]; items.len()]; + for i in 0..items.len() { + let r = root(&mut up, i); + sets[r].push(i); + } + sets.retain(|s| s.len() > 1); + sets.sort_by_key(|s| s.first().copied()); + sets +} + +fn group_overlapping(s: &mut Session, _: &Value) -> Result<Value> { + const C: &str = "addon.arrange.groupOverlapping"; + let roots = selected_roots(s)?; + if roots.len() > MAX_OBJECTS { + return Err(bad(C, "too many objects selected (at most 20000)")); + } + let d = &s.doc()?.doc; + let items: Vec<(NodeId, (Option<NodeId>, Rect))> = + roots.iter().filter_map(|id| Some((*id, (d.parent_of(*id), effects::preview::bounds_of(d, &[*id], true)?)))).collect(); + let keyed: Vec<(Option<NodeId>, Rect)> = items.iter().map(|(_, k)| *k).collect(); + let sets: Vec<Vec<NodeId>> = overlapping(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect(); + if sets.is_empty() { + return Ok(json!({ "groups": [], "grouped": 0 })); + } + let grouped: std::collections::HashSet<NodeId> = sets.iter().flatten().copied().collect(); + let groups = s.edit("Group Overlapping Objects", |d, sel| { + // Every group at once: the members behind each front one go, then each front one is + // replaced by its group (one pass over the tree each, however many groups). + let (mut places, mut behind, mut groups) = (vec![], vec![], vec![]); + for set in &sets { + let Some((&front, rest)) = set.split_last() else { continue }; + let children: Vec<Arc<Node>> = set.iter().filter_map(|id| d.node(*id).cloned().map(Arc::new)).collect(); + let gid = d.alloc_id(); + places.push((front, vec![Node::group(gid, children)])); + behind.extend_from_slice(rest); + groups.push(gid); + } + d.remove_many(&behind)?; + d.insert_beside(places, true)?; + sel.set(groups.iter().copied().chain(roots.iter().copied().filter(|id| !grouped.contains(id)))); + Ok(groups) + })?; + Ok(json!({ "groups": groups.iter().map(|i| i.0).collect::<Vec<_>>(), "grouped": grouped.len() })) +} diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index db19cc1e9e..48f9ae4ec9 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -256,8 +256,83 @@ fn off_without_a_selection() { let mut s = session(); rect(&mut s, 0.0, 0.0, 20.0, 10.0); s.execute("select.none", &json!({})).unwrap(); - for c in ["addon.arrange.grid", "addon.arrange.swap", "addon.arrange.replace", "addon.arrange.size"] { + for c in ["addon.arrange.grid", "addon.arrange.swap", "addon.arrange.replace", "addon.arrange.size", "addon.arrange.groupOverlapping"] { assert!(!enabled(&s, c), "{c}"); } assert!(!enabled(&Session::new(), "addon.arrange.swap")); } + +fn ids_of(v: &Value) -> Vec<NodeId> { + v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +fn children(s: &Session, id: NodeId) -> Vec<NodeId> { + s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect() +} + +#[test] +fn group_overlapping_groups_chains_and_leaves_loners() { + let mut s = session(); + // a–b–c a chain (c only touches b), d alone, e over f. + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let d = rect(&mut s, 200.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0); + let e = rect(&mut s, 100.0, 100.0, 30.0, 30.0); + let c = rect(&mut s, 35.0, 0.0, 10.0, 20.0); + let f = rect(&mut s, 110.0, 110.0, 5.0, 5.0); + select(&mut s, &[a, b, c, d, e, f]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupOverlapping", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!(r["grouped"], json!(5)); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 2); + assert_eq!(children(&s, groups[0]), [a, b, c], "members keep their stacking order"); + assert_eq!(children(&s, groups[1]), [e, f]); + // Each group where its frontmost member was: a d [abc] [ef] → d, group(abc) above it, then (ef). + let layer: Vec<NodeId> = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(layer, [d, groups[0], groups[1]]); + let sel = &s.doc().unwrap().selection.objects; + assert!(sel.contains(&groups[0]) && sel.contains(&groups[1]) && sel.contains(&d) && sel.len() == 3, "{sel:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 6); +} + +#[test] +fn group_overlapping_keeps_layers_apart_and_measures_visual_bounds() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let gap = rect(&mut s, 22.0, 0.0, 20.0, 20.0); + s.execute("layer.new", &json!({})).unwrap(); + let other = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + select(&mut s, &[a, gap, other]); + // 2 pt apart: nothing overlaps within a layer, and a and `other` are in different layers. + let n = steps(&s); + let r = s.execute("addon.arrange.groupOverlapping", &json!({})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "no groups, no step"); + // A 4 pt stroke reaches 2 pt out: the two in the first layer now touch. + select(&mut s, &[a, gap]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + select(&mut s, &[a, gap, other]); + let r = s.execute("addon.arrange.groupOverlapping", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [a, gap]); + let doc = &s.doc().unwrap().doc; + assert_ne!(doc.layer_of(other), doc.layer_of(a), "left in its own layer"); +} + +#[test] +fn group_overlapping_is_off_with_one_object_and_scales_to_many() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[a]); + assert!(!enabled(&s, "addon.arrange.groupOverlapping")); + // A long row of pairs: each pair overlaps, neighbouring pairs don't. + let rects: Vec<(usize, Rect)> = + (0..4000).map(|i| (0, Rect::new(i as f64 * 10.0, 0.0, i as f64 * 10.0 + if i % 2 == 0 { 12.0 } else { 3.0 }, 5.0))).collect(); + let sets = super::overlapping(&rects); + assert_eq!(sets.len(), 2000); + assert!(sets.iter().all(|s| s.len() == 2 && s[1] == s[0] + 1)); +} diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 69c69097ec..14d7f95592 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -588,6 +588,7 @@ fn structured_junk() { ("addon.arrange.replace", json!({"fit": "bounds", "scaleStrokes": true})), ("addon.arrange.size", json!({"width": 1e6, "height": 0.001, "reference": 8, "scaleStrokes": true})), ("addon.arrange.size", json!({"width": 0.001, "proportional": true, "reference": u64::MAX})), + ("addon.arrange.groupOverlapping", json!({"ids": "x", "junk": f64::MAX})), // Smart Pen add-on. ("addon.pen.append", json!({"id": 2, "x": 1e308, "y": 0, "in": [1e308, -1e308]})), ("addon.pen.append", json!({"id": 2, "subpath": u64::MAX, "x": 0, "y": 0, "segment": "curved"})), diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index 8435483cb8..f33757cee6 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -1,6 +1,6 @@ //! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of //! Arrange in Grid, Replace with Top Object and Set Size of Each, which preview on the canvas and -//! run their `addon.arrange.*` command on OK; and Zoom to Selection ([`ZOOM`]), which fits the +//! run their `addon.arrange.*` command on OK; Group Overlapping Objects; and Zoom to Selection ([`ZOOM`]), which fits the //! active view to the selection. use egui::Ui; @@ -38,6 +38,7 @@ pub fn menu() -> Vec<Item> { Item::Cmd("Swap Objects and Sizes", "addon.arrange.swap", json!({ "size": true })), Item::Cmd("Replace with Top Object…", "addon.arrange.replace", Value::Null), Item::Cmd("Set Size of Each…", "addon.arrange.size", Value::Null), + Item::Cmd("Group Overlapping Objects", "addon.arrange.groupOverlapping", json!({})), Item::Sep, Item::Cmd("Zoom to Selection", ZOOM, json!({})), ] diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 63e58448b6..72411f3889 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -40,6 +40,7 @@ fn the_plugins_submenu_lists_the_tools() { ("Swap Objects and Sizes", "addon.arrange.swap"), ("Replace with Top Object…", "addon.arrange.replace"), ("Set Size of Each…", "addon.arrange.size"), + ("Group Overlapping Objects", "addon.arrange.groupOverlapping"), ("Zoom to Selection", ZOOM), ] { assert_eq!(under(label).and_then(|e| e.command.as_deref()), Some(id), "{label}"); @@ -125,3 +126,16 @@ fn zoom_to_selection_fits_the_selection_in_the_view() { assert!(!menus::enabled(&app, ZOOM)); assert!(app.run(ZOOM, json!({})).is_err()); } + +#[test] +fn group_overlapping_objects_runs_directly() { + let (mut app, a, b) = app(); + let c = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + app.run("select.all", json!({})).unwrap(); + click(&mut app, "Group Overlapping Objects"); + assert!(app.ui.dialog.is_none()); + let doc = &app.session.doc().unwrap().doc; + let g = doc.parent_of(a).unwrap(); + assert_eq!(doc.parent_of(c), Some(g), "a and c overlap: grouped"); + assert_ne!(doc.parent_of(b), Some(g), "b is left alone"); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index d33addad42..a960e7dd27 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5926,6 +5926,9 @@ breakText Glyphs Глифи Set Size of Each Задаване на размер на всеки @msg select exactly two objects изберете точно два обекта @msg give `width` or `height` задайте `width` или `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Групиране на припокриващи се обекти +@msg too many objects selected (at most 20000) избрани са твърде много обекти (най-много 20000) Marathi Маратхи Gujarati Гуджарати Bengali Бенгалски diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index f527ca2557..6dba3afdf9 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5960,6 +5960,9 @@ shape Open Otvoren Set Size of Each Postavi veličinu svakog @msg select exactly two objects odaberite tačno dva objekta @msg give `width` or `height` zadajte `width` ili `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Grupiši preklapajuće objekte +@msg too many objects selected (at most 20000) odabrano je previše objekata (najviše 20000) Marathi Marathi Gujarati Gudžarati Bengali Bengalski diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 5873fbadae..a102f7a7cc 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6033,6 +6033,9 @@ breakText Glyphs Glifs Set Size of Each Defineix la mida de cadascun @msg select exactly two objects selecciona exactament dos objectes @msg give `width` or `height` indica `width` o `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Agrupa els objectes superposats +@msg too many objects selected (at most 20000) s’han seleccionat massa objectes (com a màxim 20000) Marathi Marathi Gujarati Gujarati Bengali Bengalí diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 8f7a607107..b0c04ffe2d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6043,6 +6043,9 @@ breakText Glyphs Glyfy Set Size of Each Nastavit velikost jednotlivě @msg select exactly two objects vyberte právě dva objekty @msg give `width` or `height` zadejte `width` nebo `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Seskupit překrývající se objekty +@msg too many objects selected (at most 20000) vybráno příliš mnoho objektů (nejvýše 20000) Marathi Maráthština Gujarati Gudžarátština Bengali Bengálština diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 8b67b907a9..d85c865bf4 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5940,6 +5940,9 @@ breakText Glyphs Glyffer Set Size of Each Angiv størrelse for hver @msg select exactly two objects markér præcis to objekter @msg give `width` or `height` angiv `width` eller `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Gruppér overlappende objekter +@msg too many objects selected (at most 20000) for mange objekter markeret (højst 20000) Marathi Marathi Gujarati Gujarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7400e6f73a..b1e187de85 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5628,6 +5628,9 @@ breakText Glyphs Glyphen Set Size of Each Größe einzeln festlegen @msg select exactly two objects wählen Sie genau zwei Objekte aus @msg give `width` or `height` geben Sie `width` oder `height` an +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Überlappende Objekte gruppieren +@msg too many objects selected (at most 20000) zu viele Objekte ausgewählt (höchstens 20000) Marathi Marathi Gujarati Gujarati Bengali Bengalisch diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 19ba17dd75..76d29ca75f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5995,6 +5995,9 @@ breakText Glyphs Γλύφοι Set Size of Each Ορισμός μεγέθους καθενός @msg select exactly two objects επιλέξτε ακριβώς δύο αντικείμενα @msg give `width` or `height` δώστε `width` ή `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Ομαδοποίηση επικαλυπτόμενων αντικειμένων +@msg too many objects selected (at most 20000) επιλέχθηκαν πάρα πολλά αντικείμενα (το πολύ 20000) Marathi Μαραθικά Gujarati Γκουγιαράτι Bengali Βεγγαλικά diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 884ee8e7e3..f1d2645dce 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5985,6 +5985,9 @@ breakText Glyphs Glifos Set Size of Each Definir el tamaño de cada uno @msg select exactly two objects selecciona exactamente dos objetos @msg give `width` or `height` indica `width` o `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Agrupar objetos superpuestos +@msg too many objects selected (at most 20000) demasiados objetos seleccionados (como máximo 20000) Marathi Maratí Gujarati Guyaratí Bengali Bengalí diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1b3528602f..65c7df1264 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6073,6 +6073,9 @@ breakText Glyphs Merkit Set Size of Each Aseta kunkin koko @msg select exactly two objects valitse täsmälleen kaksi objektia @msg give `width` or `height` anna `width` tai `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Ryhmitä päällekkäiset objektit +@msg too many objects selected (at most 20000) liian monta objektia valittu (enintään 20000) Marathi Marathi Gujarati Gudžarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 46f1c08dbf..f0d74bcc76 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6040,6 +6040,9 @@ breakText Glyphs Glyphes Set Size of Each Définir la taille de chaque objet @msg select exactly two objects sélectionnez exactement deux objets @msg give `width` or `height` indiquez `width` ou `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Grouper les objets qui se chevauchent +@msg too many objects selected (at most 20000) trop d’objets sélectionnés (20000 au plus) Marathi Marathi Gujarati Goudjarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index bf9ec10b27..bd2b64965a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6029,6 +6029,9 @@ breakText Glyphs Glifák Set Size of Each Egyenkénti méret beállítása @msg select exactly two objects jelölj ki pontosan két objektumot @msg give `width` or `height` add meg a `width` vagy a `height` értéket +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Átfedő objektumok csoportosítása +@msg too many objects selected (at most 20000) túl sok objektum van kijelölve (legfeljebb 20000) Marathi Maráthi Gujarati Gudzsaráti Bengali Bengáli diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 99b7471115..c7a2f0021b 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5940,6 +5940,9 @@ breakText Glyphs Glif Set Size of Each Atur ukuran masing-masing @msg select exactly two objects pilih tepat dua objek @msg give `width` or `height` berikan `width` atau `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Grupkan objek yang tumpang tindih +@msg too many objects selected (at most 20000) terlalu banyak objek dipilih (paling banyak 20000) Marathi Marathi Gujarati Gujarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index f3cbd75588..5f340b02bc 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5662,6 +5662,9 @@ breakText Glyphs Glifi Set Size of Each Imposta dimensione di ciascuno @msg select exactly two objects seleziona esattamente due oggetti @msg give `width` or `height` indica `width` o `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Raggruppa oggetti sovrapposti +@msg too many objects selected (at most 20000) troppi oggetti selezionati (al massimo 20000) Marathi Marathi Gujarati Gujarati Bengali Bengalese diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 5363c5d06c..da7fd34f00 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5729,6 +5729,9 @@ breakText Glyphs 字形 Set Size of Each 個別にサイズを設定 @msg select exactly two objects オブジェクトをちょうど 2 つ選択してください @msg give `width` or `height` `width` または `height` を指定してください +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects 重なり合うオブジェクトをグループ化 +@msg too many objects selected (at most 20000) 選択されたオブジェクトが多すぎます(最大 20000) Marathi マラーティー語 Gujarati グジャラート語 Bengali ベンガル語 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8f2c407c4a..d71ee8b9bd 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6032,6 +6032,9 @@ breakText Glyphs გლიფები Set Size of Each თითოეულის ზომის დაყენება @msg select exactly two objects მონიშნეთ ზუსტად ორი ობიექტი @msg give `width` or `height` მიუთითეთ `width` ან `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects გადაფარვადი ობიექტების დაჯგუფება +@msg too many objects selected (at most 20000) არჩეულია ძალიან ბევრი ობიექტი (მაქსიმუმ 20000) Marathi მარათჰი Gujarati გუჯარათი Bengali ბენგალური diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index acf8135c32..6b9ef0524f 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5625,6 +5625,9 @@ breakText Glyphs 글리프 Set Size of Each 각각 크기 설정 @msg select exactly two objects 개체를 정확히 두 개 선택하세요 @msg give `width` or `height` `width` 또는 `height`를 지정하세요 +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects 겹치는 개체 그룹화 +@msg too many objects selected (at most 20000) 선택한 개체가 너무 많습니다(최대 20000개) Marathi 마라티어 Gujarati 구자라트어 Bengali 벵골어 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 51dd8b37e1..c4d9c535e1 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5984,6 +5984,9 @@ breakText Glyphs Glyphs Set Size of Each Formaat van elk instellen @msg select exactly two objects selecteer precies twee objecten @msg give `width` or `height` geef `width` of `height` op +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Overlappende objecten groeperen +@msg too many objects selected (at most 20000) te veel objecten geselecteerd (hoogstens 20000) Marathi Marathi Gujarati Gujarati Bengali Bengaals diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 30203b1a10..2418eae3cd 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5898,6 +5898,9 @@ breakText Glyphs Glify Set Size of Each Ustaw rozmiar każdego @msg select exactly two objects zaznacz dokładnie dwa obiekty @msg give `width` or `height` podaj `width` lub `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Grupuj nakładające się obiekty +@msg too many objects selected (at most 20000) zaznaczono za dużo obiektów (najwyżej 20000) Marathi Marathi Gujarati Gudżarati Bengali Bengalski diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 6ede5c3510..34b223428a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5962,6 +5962,9 @@ breakText Glyphs Glifos Set Size of Each Definir Tamanho de Cada Um @msg select exactly two objects selecione exatamente dois objetos @msg give `width` or `height` informe `width` ou `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Agrupar objetos sobrepostos +@msg too many objects selected (at most 20000) objetos demais selecionados (no máximo 20000) Marathi Marati Gujarati Guzerate Bengali Bengali diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 2bf406c749..747c915850 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6020,6 +6020,9 @@ breakText Glyphs Глифы Set Size of Each Задать размер каждого @msg select exactly two objects выделите ровно два объекта @msg give `width` or `height` укажите `width` или `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Сгруппировать перекрывающиеся объекты +@msg too many objects selected (at most 20000) выделено слишком много объектов (не более 20000) Marathi Маратхи Gujarati Гуджарати Bengali Бенгальский diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 788d45c8af..26b3a1d59d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6095,6 +6095,9 @@ breakText Glyphs Glyfer Set Size of Each Ange storlek för vart och ett @msg select exactly two objects markera exakt två objekt @msg give `width` or `height` ange `width` eller `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Gruppera överlappande objekt +@msg too many objects selected (at most 20000) för många objekt markerade (högst 20000) Marathi Marathi Gujarati Gujarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 50b7f213b3..a4851f2e3c 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6000,6 +6000,9 @@ breakText Glyphs Glifler Set Size of Each Her Birinin Boyutunu Ayarla @msg select exactly two objects tam olarak iki nesne seç @msg give `width` or `height` `width` veya `height` belirt +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Çakışan Nesneleri Grupla +@msg too many objects selected (at most 20000) çok fazla nesne seçili (en fazla 20000) Marathi Marathi dili Gujarati Gücerat dili Bengali Bengalce diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 03d912f327..a4c04383aa 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5642,6 +5642,9 @@ breakText Glyphs Гліфи Set Size of Each Задати розмір кожного @msg select exactly two objects виділіть рівно два об’єкти @msg give `width` or `height` укажіть `width` або `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Згрупувати об’єкти, що перекриваються +@msg too many objects selected (at most 20000) виділено забагато об’єктів (не більше 20000) Marathi Маратхі Gujarati Гуджараті Bengali Бенгальська diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index cdea7542bb..ab593787bb 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5645,6 +5645,9 @@ breakText Glyphs Glyph Set Size of Each Đặt kích thước từng cái @msg select exactly two objects hãy chọn đúng hai đối tượng @msg give `width` or `height` hãy cho `width` hoặc `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects Nhóm các đối tượng chồng lên nhau +@msg too many objects selected (at most 20000) chọn quá nhiều đối tượng (tối đa 20000) Marathi Tiếng Marathi Gujarati Tiếng Gujarati Bengali Tiếng Bengali diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c485086b11..9b506a128f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5885,6 +5885,9 @@ breakText Glyphs 字形 Set Size of Each 分别设置大小 @msg select exactly two objects 请恰好选择两个对象 @msg give `width` or `height` 请提供 `width` 或 `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects 编组重叠对象 +@msg too many objects selected (at most 20000) 选择的对象过多(最多 20000 个) Marathi 马拉地语 Gujarati 古吉拉特语 Bengali 孟加拉语 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 06ea604985..3e645ca095 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5682,6 +5682,9 @@ breakText Glyphs 字符 Set Size of Each 個別設定大小 @msg select exactly two objects 請選取正好兩個物件 @msg give `width` or `height` 請提供 `width` 或 `height` +# Arrange Tools add-on: Group Overlapping Objects. + Group Overlapping Objects 群組重疊物件 +@msg too many objects selected (at most 20000) 選取的物件過多(最多 20000 個) Marathi 馬拉地文 Gujarati 古吉拉特文 Bengali 孟加拉文 diff --git a/docs/mcp.md b/docs/mcp.md index baf64c4e29..705b9d54b3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6251,6 +6251,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. | | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | +| `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6dd6db0b28..1a0fe7d618 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Type core: text shaped in its language, a Language per character, Indian languages, #4940 #4946 #4943; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Arrange Tools add-on: Group Overlapping Objects, #4928; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -1399,10 +1399,15 @@ scaling, replace with each fit and kept originals in stacking order, size with p undo step, off states, bad params refused), `addons::arrange::tests` in `vectorcraft-ui-egui` (the submenu, the dialogs, Preview and Cancel, Zoom to Selection) and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +## Arrange Tools add-on: Group Overlapping Objects (2026-11-01) + +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the top-level selected objects wherever their visual bounds overlap or touch, chains included (A overlapping B and B overlapping C makes one group of three), only among objects of the same layer or group; objects that overlap nothing stay as they are, each new group takes its frontmost member's place in the stacking order, and the groups and the loose objects stay selected. One undo step; at most 20000 objects, compared by a sweep along x with union-find. Tests: `group_overlapping_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (chains, loners, stacking order, layers kept apart, visual bounds, no step when nothing overlaps, many objects), `group_overlapping_objects_runs_directly` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. + ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Group Overlapping Objects (#4928); evidence added; scores unchanged. | | 2026-11-01 | minor | Type core: a Language per character (Character panel › Language, `text.setFormat` / `text.setRangeStyle {language}`, character styles), new type in the document's language; text is shaped in its language so fonts use their language forms (OpenType `locl`: Turkish `fi`, #4940, #4946); Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu in the language list (#4943); scores unchanged | | 2026-10-31 | minor | Selection tools: with Alt held at the press, a Direct Selection marquee selects every path it touches whole and keeps the Group Selection pointer (#4890); a press on a selected object's centre point selects the object whole and a drag from it moves it (#4891); regression tests in `direct/tests.rs`; scores and estimates unchanged. | | 2026-10-31 | minor | Arrange Tools add-on (a VectorCraft addition): evidence added; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index a135d587c7..6672e0f94f 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Character panel › Language, Indian languages in Document Setup › Language, #4946 #4943) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Arrange Tools add-on: Group Overlapping Objects, #4928) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -329,6 +329,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 | | Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | | Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its seven tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | @@ -381,6 +382,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Group Overlapping Objects (#4928); scores and estimates unchanged | | 2026-11-01 | minor | Character panel › Language: the selected characters' language, from Document Setup's list, which gains Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu (#4946, #4943); the Digits menu's numeral names keep their own translations; scores unchanged | | 2026-11-01 | minor | VectorCraft Options' Version is a menu of the versions VectorCraft writes, each named by the releases that read it, and an uncompressible version turns Use Compression off (#4931); a save refused before writing shows the Can't save alert with the reason (#4933); About › Contributors' table keeps its header row above the scrolling rows (#4944); the Gradient panel's freeform point swatch opens the point's popover (#4953); scores unchanged | | 2026-10-31 | minor | A file opened from the file manager while VectorCraft runs opens as a new tab in that window, which comes to the front, on Windows and Linux (#4892); `--new-instance` opts out; scores unchanged | From 9e3f8dccec3621c70d1cddb44f2bb1e6d0ade57d Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 01:56:23 +0700 Subject: [PATCH 170/260] Fix #4950: Path Precision Tools: Divide into Dashes addon.pathtools.divideDashes cuts the selected paths (or only their direct-selected segments) into separate open paths of a dash length measured along the curve, with an optional gap (gap pieces dropped unless removeGaps is false) and Fit to Corners and Ends; pieces keep the path's appearance, one undo step, at most 100000 pieces. Geometry in vectorcraft-pathops; dialog with unit fields and Preview; tests, sweep cases, catalog rows and docs. --- ROADMAP.md | 4 +- crates/engine/src/cmd/addons/pathtools.rs | 90 ++++++- .../engine/src/cmd/addons/pathtools/tests.rs | 74 +++++ crates/engine/tests/command_sweep.rs | 3 + crates/pathops/src/addons/pathtools.rs | 5 +- crates/pathops/src/addons/pathtools/dashes.rs | 252 ++++++++++++++++++ crates/ui-egui/src/addons/pathtools.rs | 12 +- crates/ui-egui/src/addons/pathtools/dashes.rs | 91 +++++++ crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/i18n/bg.tsv | 9 + crates/ui-egui/src/i18n/bs.tsv | 9 + crates/ui-egui/src/i18n/ca.tsv | 9 + crates/ui-egui/src/i18n/cs.tsv | 9 + crates/ui-egui/src/i18n/da.tsv | 9 + crates/ui-egui/src/i18n/de.tsv | 9 + crates/ui-egui/src/i18n/el.tsv | 9 + crates/ui-egui/src/i18n/es.tsv | 9 + crates/ui-egui/src/i18n/fi.tsv | 9 + crates/ui-egui/src/i18n/fr.tsv | 9 + crates/ui-egui/src/i18n/hu.tsv | 9 + crates/ui-egui/src/i18n/id.tsv | 9 + crates/ui-egui/src/i18n/it.tsv | 9 + crates/ui-egui/src/i18n/ja.tsv | 9 + crates/ui-egui/src/i18n/ka.tsv | 9 + crates/ui-egui/src/i18n/ko.tsv | 9 + crates/ui-egui/src/i18n/nl.tsv | 9 + crates/ui-egui/src/i18n/pl.tsv | 9 + crates/ui-egui/src/i18n/pt-br.tsv | 9 + crates/ui-egui/src/i18n/ru.tsv | 9 + crates/ui-egui/src/i18n/sv.tsv | 9 + crates/ui-egui/src/i18n/tr.tsv | 9 + crates/ui-egui/src/i18n/uk.tsv | 9 + crates/ui-egui/src/i18n/vi.tsv | 9 + crates/ui-egui/src/i18n/zh-hans.tsv | 9 + crates/ui-egui/src/i18n/zh-hant.tsv | 9 + crates/ui-egui/src/menus/invoke.rs | 1 + docs/mcp.md | 10 + docs/target-app-parity.md | 7 +- docs/ui-parity.md | 4 +- 39 files changed, 770 insertions(+), 18 deletions(-) create mode 100644 crates/pathops/src/addons/pathtools/dashes.rs create mode 100644 crates/ui-egui/src/addons/pathtools/dashes.rs diff --git a/ROADMAP.md b/ROADMAP.md index c943bbb027..b8365d0f0f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -9,7 +9,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for Group Overlapping Objects in the Arrange Tools add-on; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for Divide into Dashes in the Path Precision Tools add-on; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. - 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged. @@ -205,6 +206,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Progress log row for Divide into Dashes (Path Precision Tools add-on, #4950); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for Group Overlapping Objects (Arrange Tools add-on, #4928); headline numbers unchanged. | | 2026-10-31 | minor | Progress log row for Export for Screens laid out as the reference app's (#4895) and the 2026-10-31 community landings; headline numbers unchanged. | | 2026-10-31 | minor | Progress log row for the Arrange Tools add-on; headline numbers unchanged. | diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index b78eb09763..94114a59c4 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -1,8 +1,8 @@ //! Path Precision Tools (`addon.pathtools.*`), a built-in add-on: the Anchor Eraser Brush's stroke, //! the Extend Path tool's extension, the Measure & Inspect tool's readouts, the Anchor Inspector's //! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners -//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), and the Shared Edge Merge Tool's -//! merges with Keep Shared Points Together ([`shared_edge`]). +//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's +//! merges with Keep Shared Points Together ([`shared_edge`]), and Divide into Dashes. //! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's //! and the UI's. @@ -40,6 +40,8 @@ const MIN_RADIUS: f64 = 0.05; const MAX_DIAMETER: f64 = 2500.0; /// The farthest an end is extended at once (pt). const MAX_EXTEND: f64 = 1e6; +/// Most pieces Divide into Dashes makes at once. +const MAX_PIECES: usize = 100_000; /// Most anchors Add Points puts on each segment. const MAX_ADD: u64 = pt::MAX_ADDED_PER_SEGMENT as u64; @@ -153,6 +155,15 @@ pub fn specs() -> Vec<CommandSpec> { has_doc, slide_anchor ), + cmd!( + "addon.pathtools.divideDashes", + "Divide into Dashes", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{dash?: pt 0.01..1000000 (10), gap?: pt 0..1000000 (0: the pieces touch), fit?: bool (false: exact lengths, the last piece of each run what is left; true: fit to corners and ends, every run between corners and ends holding whole dashes, all stretched or squeezed alike so it starts and ends on a dash), removeGaps?: bool (true: the gaps are left empty; false: they stay as pieces too)} cut the selected paths into separate open paths along the curve, each dash long with gap between them and keeping the path's appearance, as one undo step. Only the direct-selected segments (or those between two direct-selected anchors) are divided when there are any, the dash pattern running on across segments that follow one another; the rest of such a path stays, as pieces of its own. The pieces are selected; at most 100000 → {ids, dashes}", + has_selection, + divide_dashes + ), ]; v.extend(shape::specs()); v.extend(corners::specs()); @@ -583,6 +594,16 @@ fn remove_keep_shape(s: &mut Session, _: &Value) -> Result<Value> { Ok(json!({ "removed": removed })) } +/// The segments of subpath `si` (`sp`) picked: the direct-selected segments `segments` of its +/// path, else those between two of its selected `anchors`. +fn picked_segments(segments: Option<&BTreeSet<(usize, usize)>>, si: usize, sp: &SubPath, anchors: &BTreeSet<usize>) -> BTreeSet<usize> { + let n = sp.anchors.len().max(1); + match segments.filter(|set| !set.is_empty()) { + Some(set) => set.iter().filter(|(s, _)| *s == si).map(|(_, k)| *k).collect(), + None => (0..sp.segment_count()).filter(|k| anchors.contains(k) && anchors.contains(&((k + 1) % n))).collect(), + } +} + fn add_points(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "addon.pathtools.addPoints"; let count = number_or(p, "count", 1.0, C)?; @@ -597,16 +618,10 @@ fn add_points(s: &mut Session, p: &Value) -> Result<Value> { let mut changed = vec![]; for (id, by_sub) in &picked { let Some(path) = d.node(*id).and_then(|n| n.path_data()) else { continue }; - let picked_segments = st.selection.segments.get(id); let mut np = path.clone(); for (si, sp) in np.subpaths.iter_mut().enumerate() { let Some(anchors) = by_sub.get(&si) else { continue }; - let n = sp.anchors.len(); - // Picked segments, else those between two selected anchors. - let segs: BTreeSet<usize> = match picked_segments { - Some(set) => set.iter().filter(|(s, _)| *s == si).map(|(_, k)| *k).collect(), - None => (0..sp.segment_count()).filter(|k| anchors.contains(k) && anchors.contains(&((k + 1) % n.max(1)))).collect(), - }; + let segs = picked_segments(st.selection.segments.get(id), si, sp, anchors); let (out, marks) = pt::add_points(sp, Some(&segs), count as usize); added += marks.len(); *sp = out; @@ -721,3 +736,60 @@ fn crossings(s: &mut Session, p: &Value) -> Result<Value> { })?; Ok(json!({ "ids": out.iter().map(|i| i.0).collect::<Vec<_>>(), "crossings": count })) } + +// ---------- Divide into Dashes ---------- + +fn divide_dashes(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "addon.pathtools.divideDashes"; + let spec = pt::DashSpec { + dash: given(p, "dash", Some((0.01, 1e6)), C)?.unwrap_or(10.0), + gap: given(p, "gap", Some((0.0, 1e6)), C)?.unwrap_or(0.0), + fit: switch_or(p, "fit", false, C)?, + }; + let remove_gaps = switch_or(p, "removeGaps", true, C)?; + let picked = picked_anchors(s, true)?; + let st = s.doc()?; + let d = &st.doc; + check_size(picked.iter().filter_map(|(id, _)| d.node(*id)?.path_data()), C)?; + let (mut made, mut dashes) = (0, 0); + // Each path divided: what stays of it (the subpaths not divided, as one path) and its pieces. + let mut changed: Vec<(NodeId, Vec<PathData>)> = vec![]; + for (id, by_sub) in &picked { + let Some(path) = d.node(*id).and_then(|n| n.path_data()) else { continue }; + let (mut kept, mut pieces) = (vec![], vec![]); + for (si, sp) in path.subpaths.iter().enumerate() { + let segs = by_sub.get(&si).map(|anchors| picked_segments(st.selection.segments.get(id), si, sp, anchors)).unwrap_or_default(); + if segs.is_empty() { + kept.push(sp.clone()); + continue; + } + let only = (segs.len() < sp.segment_count()).then_some(&segs); + let out = pt::divide_dashes(sp, only, spec, MAX_PIECES.saturating_sub(made)) + .ok_or_else(|| bad(C, "that makes too many pieces (at most 100000): make the dashes longer"))?; + made += out.len(); + for (piece, kind) in out.into_iter().filter(|(_, k)| !(remove_gaps && *k == pt::Piece::Gap)) { + dashes += usize::from(kind == pt::Piece::Dash); + pieces.push(PathData::single(piece)); + } + } + if !pieces.is_empty() { + changed.push((*id, (!kept.is_empty()).then(|| PathData::new(kept)).into_iter().chain(pieces).collect())); + } + } + if changed.is_empty() { + return Err(bad(C, "select paths, or segments, to divide")); + } + let ids = s.edit("Divide into Dashes", |d, sel| { + let mut all = vec![]; + let mut beside = Beside::replacing(d, &changed.iter().map(|(id, _)| *id).collect::<Vec<_>>()); + for (id, pieces) in changed { + all.extend(replace_with_pieces(d, &mut beside, id, pieces)?); + } + beside.finish(d)?; + // The pieces join the objects selected (whole, in one go: there may be many). + let before = std::mem::take(&mut sel.objects); + sel.set(before.into_iter().chain(all.iter().copied())); + Ok(all) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "dashes": dashes })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index 52f0c7078e..cc745385cd 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -674,3 +674,77 @@ fn the_slide_tool_previews_and_commits_one_step() { s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(at(&s), Point::new(200.0, 100.0)); } + +fn ids(v: &Value) -> Vec<NodeId> { + v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +#[test] +fn divide_into_dashes_cuts_a_path_into_open_pieces_keeping_its_look() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)], false); + select(&mut s, &[l]); + s.execute("stroke.set", &json!({"weight": 3})).unwrap(); + let n = steps(&s); + let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 30, "gap": 10})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + // 30 + 10 + 30 + 10 + 20: the gaps are left empty. + let pieces = ids(&r); + assert_eq!((pieces.len(), r["dashes"].clone()), (3, json!(3))); + let st = s.doc().unwrap(); + let spans: Vec<(f64, f64)> = pieces.iter().map(|id| path(&s, *id).bounds().map(|b| (b.x0, b.x1)).unwrap()).collect(); + let want = [(0.0, 30.0), (40.0, 70.0), (80.0, 100.0)]; + assert!(spans.iter().zip(want).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6), "{spans:?}"); + assert!(pieces.iter().all(|id| st.doc.node(*id).unwrap().appearance.stroke_width() == 3.0), "the stroke stays"); + assert_eq!(st.selection.objects, pieces); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, l).anchor_count(), 2); + // Kept gaps; fitted 25s with no gap. + let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 30, "gap": 10, "removeGaps": false})).unwrap(); + assert_eq!((ids(&r).len(), r["dashes"].clone()), (5, json!(3))); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 30, "fit": true})).unwrap(); + let spans: Vec<f64> = ids(&r).iter().map(|id| path(&s, *id).bounds().unwrap().width()).collect(); + assert_eq!(spans.len(), 3); + assert!(spans.iter().all(|w| (w - 100.0 / 3.0).abs() < 1e-6), "{spans:?}"); +} + +#[test] +fn divide_into_dashes_divides_only_the_selected_segments() { + let mut s = session(); + let u = line(&mut s, &[(0.0, 0.0), (40.0, 0.0), (40.0, 40.0), (0.0, 40.0)], false); + // The middle side, between anchors 1 and 2. + select_anchors(&mut s, u, &[1, 2]); + let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 10})).unwrap(); + let pieces = ids(&r); + assert_eq!((pieces.len(), r["dashes"].clone()), (6, json!(4)), "the first side, four dashes, the last side"); + assert_eq!(path(&s, pieces[0]).bounds().unwrap().width(), 40.0); + let layer: Vec<NodeId> = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(layer, pieces, "in the path's place, in order"); +} + +#[test] +fn divide_into_dashes_refuses_bad_params_and_too_many_pieces() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (1e5, 0.0)], false); + select(&mut s, &[l]); + refuses( + &mut s, + "addon.pathtools.divideDashes", + &[ + json!({"dash": 0}), + json!({"dash": -5}), + json!({"dash": 1e308}), + json!({"dash": "10"}), + json!({"gap": -1}), + json!({"gap": 2e6}), + json!({"fit": "yes"}), + json!({"removeGaps": 1}), + json!({"dash": 0.5}), + ], + ); + // 200000 pieces refused above; 1000 is fine. + assert_eq!(s.execute("addon.pathtools.divideDashes", &json!({"dash": 100})).unwrap()["dashes"], json!(1000)); + s.execute("select.none", &json!({})).unwrap(); + refuses(&mut s, "addon.pathtools.divideDashes", &[json!({})]); +} diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 14d7f95592..36fe6401d5 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -589,6 +589,9 @@ fn structured_junk() { ("addon.arrange.size", json!({"width": 1e6, "height": 0.001, "reference": 8, "scaleStrokes": true})), ("addon.arrange.size", json!({"width": 0.001, "proportional": true, "reference": u64::MAX})), ("addon.arrange.groupOverlapping", json!({"ids": "x", "junk": f64::MAX})), + ("addon.pathtools.divideDashes", json!({"dash": 1e-308, "gap": -1e308, "fit": "x"})), + ("addon.pathtools.divideDashes", json!({"dash": 0.01, "gap": 1e6, "fit": true, "removeGaps": false})), + ("addon.pathtools.divideDashes", json!({"dash": f64::MAX, "gap": [0], "removeGaps": null})), // Smart Pen add-on. ("addon.pen.append", json!({"id": 2, "x": 1e308, "y": 0, "in": [1e308, -1e308]})), ("addon.pen.append", json!({"id": 2, "subpath": u64::MAX, "x": 0, "y": 0, "segment": "curved"})), diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index b98778cc56..1de342ffc8 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -3,9 +3,11 @@ //! ([`add_anchors`], [`smooth_anchors`], [`split_at_anchors`]), the readouts the Measure & Inspect //! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]), the places //! where paths cross ([`crossings`]), anchors slid along their path ([`slide`]), touching edges -//! merged ([`shared_edge`]) and the Parametric Shape Tool's shapes ([`shapes`]). +//! merged ([`shared_edge`]), paths divided into dashes ([`divide_dashes`]) and the Parametric Shape +//! Tool's shapes ([`shapes`]). mod crossings; +mod dashes; mod extend; pub mod shapes; mod shared_edge; @@ -19,6 +21,7 @@ use kurbo::{CubicBez, ParamCurve, ParamCurveArclen, ParamCurveNearest, Point, Ve use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; pub use crossings::{MAX_CROSSING_SEGMENTS, crossings, insert_at}; +pub use dashes::{DashSpec, Piece, divide_dashes}; pub use extend::{ExtendMode, extend_length_to, extend_open}; pub use shared_edge::{ COINCIDENCE, EndSide, Follow, MAX_COINCIDENCE, MergePlan, MergePreview, Stretch, apply_merge, ends_at, merge_preview, stretches_at, diff --git a/crates/pathops/src/addons/pathtools/dashes.rs b/crates/pathops/src/addons/pathtools/dashes.rs new file mode 100644 index 0000000000..cec805d84d --- /dev/null +++ b/crates/pathops/src/addons/pathtools/dashes.rs @@ -0,0 +1,252 @@ +//! Divide into Dashes: a subpath (or some of its segments) cut into open pieces of a given length +//! measured along the curve, with gaps of a given length between them. + +use std::collections::BTreeSet; + +use kurbo::{CubicBez, ParamCurve, ParamCurveArclen}; +use vectorcraft_geom::{Anchor, AnchorKind, SubPath}; + +use super::{ACCURACY, TINY}; + +/// What a piece [`divide_dashes`] cuts is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Piece { + Dash, + /// The stretch between two dashes. + Gap, + /// A stretch of segments that weren't to be divided, as it was. + Rest, +} + +/// How [`divide_dashes`] measures. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct DashSpec { + /// Each dash's length (pt), more than 0. + pub dash: f64, + /// Each gap's length (pt), 0 or more (0: the dashes touch). + pub gap: f64, + /// Fit to corners and ends: every run between corners and ends holds a whole number of dashes + /// (and the gaps between them), all stretched or squeezed alike so it starts and ends on a + /// dash; a closed subpath with no corner holds whole periods. Otherwise the lengths are exact + /// and the last piece of each run is what is left. + pub fit: bool, +} + +/// `sp` cut into open pieces in order along it: the segments `segments` picks (all when `None`) +/// cut into dashes and gaps as `spec` says, the dash pattern running on across the picked +/// segments that follow one another, and each stretch of segments not picked as one piece. `None` +/// when that would make more than `room` pieces, or `spec` is no pattern (lengths not finite, a +/// dash not more than 0, a negative gap). +pub fn divide_dashes(sp: &SubPath, segments: Option<&BTreeSet<usize>>, spec: DashSpec, room: usize) -> Option<Vec<(SubPath, Piece)>> { + let DashSpec { dash, gap, fit } = spec; + if !(dash.is_finite() && gap.is_finite() && dash > TINY && gap >= 0.0) { + return None; + } + let n = sp.segment_count(); + let picked = |k: usize| segments.is_none_or(|s| s.contains(&k)); + if !(0..n).any(picked) { + return Some(vec![(sp.clone(), Piece::Rest)]); + } + // An anchor between two segments where the outline turns: a corner a fitted run ends at. + let corner = |i: usize| sp.anchors.get(i).is_some_and(|a| Anchor::with_handles(a.p, a.h_in, a.h_out).kind != AnchorKind::Smooth); + // A closed subpath starts where picked and unpicked segments meet, else (fitting) at a corner. + let start = if sp.closed { + (0..n).find(|&k| picked(k) != picked((k + n - 1) % n)).or_else(|| (0..n).find(|&k| fit && corner(k))).unwrap_or(0) + } else { + 0 + }; + // Runs of segments alike; a fitted picked run also ends at each corner. + let mut runs: Vec<(bool, Vec<usize>)> = vec![]; + for k in (0..n).map(|i| (start + i) % n) { + let p = picked(k); + match runs.last_mut() { + Some((q, segs)) if *q == p && !(p && fit && corner(k)) => segs.push(k), + _ => runs.push((p, vec![k])), + } + } + let whole_loop = sp.closed && runs.len() == 1 && !(fit && corner(start)); + let mut out = vec![]; + for (p, segs) in runs { + let curves: Vec<CubicBez> = segs.iter().map(|&k| sp.segment(k)).collect(); + if !p { + out.extend(from_cubics(&curves).map(|s| (s, Piece::Rest))); + continue; + } + let lens: Vec<f64> = curves.iter().map(|c| c.arclen(ACCURACY)).collect(); + let len: f64 = lens.iter().sum(); + if !(len.is_finite() && len > TINY) { + continue; + } + let cuts = spans(len, spec, whole_loop, room.checked_sub(out.len())?)?; + let mut cursor = 0; + let mut from = 0.0; + let starts: Vec<f64> = lens + .iter() + .map(|l| { + let s = from; + from += l; + s + }) + .collect(); + for (a, b, kind) in cuts { + let mut piece = vec![]; + let mut j = cursor; + while let (Some(&s0), Some(&l), Some(c)) = (starts.get(j), lens.get(j), curves.get(j)) { + if s0 >= b - TINY { + break; + } + let (t0, t1) = ((a - s0).max(0.0), (b - s0).min(l)); + if t1 - t0 > TINY { + let at = |d: f64| { + if d <= 0.0 { + 0.0 + } else if d >= l { + 1.0 + } else { + c.inv_arclen(d, ACCURACY) + } + }; + piece.push(c.subsegment(at(t0)..at(t1))); + } + if s0 + l > b + TINY { + break; + } + j += 1; + } + cursor = j; + out.extend(from_cubics(&piece).map(|s| (s, kind))); + } + } + Some(out) +} + +/// The pieces (start, end along the run, kind) of a run `len` long; `None` past `room` pieces. +fn spans(len: f64, DashSpec { dash, gap, fit }: DashSpec, whole_loop: bool, room: usize) -> Option<Vec<(f64, f64, Piece)>> { + let period = dash + gap; + // A loop holds whole periods; an open run one gap fewer than dashes. + let scale = if !fit { + 1.0 + } else if whole_loop { + len / ((len / period).round().max(1.0) * period) + } else { + let count = ((len + gap) / period).round().max(1.0); + len / (count * dash + (count - 1.0) * gap) + }; + let (dash, gap) = (dash * scale, gap * scale); + // Rounding (of the length measured, over many pieces): what is left past `end` is no piece. + let end = len - (len * 1e-9).max(TINY); + let most = (end / (dash + gap)).ceil() * if gap > 0.0 { 2.0 } else { 1.0 }; + if !(most.is_finite() && most <= room as f64) { + return None; + } + let mut out = vec![]; + let (mut at, mut on) = (0.0, true); + while at < end { + let step = if on { dash } else { gap }; + if step > 0.0 { + let to = (at + step).min(len); + out.push((at, if to >= end { len } else { to }, if on { Piece::Dash } else { Piece::Gap })); + at = to; + } + on = !on; + } + Some(out) +} + +/// An open subpath through cubic segments that follow one another; `None` for none. +fn from_cubics(cs: &[CubicBez]) -> Option<SubPath> { + let (first, last) = (cs.first()?, cs.last()?); + let mut anchors = vec![Anchor::with_handles(first.p0, first.p0, first.p1)]; + anchors.extend(cs.windows(2).filter_map(|w| match w { + [a, b] => Some(Anchor::with_handles(b.p0, a.p2, b.p1)), + _ => None, + })); + anchors.push(Anchor::with_handles(last.p3, last.p2, last.p3)); + Some(SubPath::new(anchors, false)) +} + +#[cfg(test)] +mod tests { + use kurbo::Point; + + use super::*; + + fn line(len: f64) -> SubPath { + SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(len, 0.0)], false) + } + + fn length(sp: &SubPath) -> f64 { + (0..sp.segment_count()).map(|k| sp.segment(k).arclen(ACCURACY)).sum() + } + + fn lengths(pieces: &[(SubPath, Piece)]) -> Vec<(i64, Piece)> { + pieces.iter().map(|(s, k)| ((length(s) * 1000.0).round() as i64, *k)).collect() + } + + const EXACT: DashSpec = DashSpec { dash: 10.0, gap: 0.0, fit: false }; + + #[test] + fn a_line_is_cut_into_dashes_and_gaps() { + let p = divide_dashes(&line(35.0), None, EXACT, 100).unwrap(); + assert_eq!(lengths(&p), [(10_000, Piece::Dash), (10_000, Piece::Dash), (10_000, Piece::Dash), (5_000, Piece::Dash)]); + assert_eq!(p[0].0.anchors[1].p, p[1].0.anchors[0].p, "touching"); + assert!(p[1].0.anchors[0].p.distance(Point::new(10.0, 0.0)) < 1e-6); + let p = divide_dashes(&line(35.0), None, DashSpec { gap: 5.0, ..EXACT }, 100).unwrap(); + let kinds: Vec<Piece> = p.iter().map(|(_, k)| *k).collect(); + assert_eq!(kinds, [Piece::Dash, Piece::Gap, Piece::Dash, Piece::Gap, Piece::Dash]); + assert_eq!(lengths(&p)[4], (5_000, Piece::Dash)); + } + + #[test] + fn fitting_stretches_the_pattern_to_start_and_end_on_a_dash() { + // 35 with 10 + 5: three dashes and two gaps, squeezed from 40 to 35. + let p = divide_dashes(&line(35.0), None, DashSpec { dash: 10.0, gap: 5.0, fit: true }, 100).unwrap(); + let (d, g) = ((8_750, Piece::Dash), (4_375, Piece::Gap)); + assert_eq!(lengths(&p), [d, g, d, g, d]); + // A square: each side its own run, each starting and ending on a dash. + let sq = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(30.0, 0.0), Point::new(30.0, 30.0), Point::new(0.0, 30.0)], true); + let p = divide_dashes(&sq, None, DashSpec { dash: 7.0, gap: 0.0, fit: true }, 100).unwrap(); + assert_eq!(p.len(), 16, "four dashes of 7.5 on each side"); + assert!(lengths(&p).iter().all(|(l, k)| *l == 7_500 && *k == Piece::Dash)); + } + + #[test] + fn a_curve_is_measured_along_it() { + let arc = SubPath::new( + vec![ + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(0.0, 55.0)), + Anchor::with_handles(Point::new(100.0, 100.0), Point::new(45.0, 100.0), Point::new(100.0, 100.0)), + ], + false, + ); + let total = length(&arc); + let p = divide_dashes(&arc, None, EXACT, 1000).unwrap(); + assert_eq!(p.len(), (total / 10.0).ceil() as usize); + assert!(p.iter().rev().skip(1).all(|(s, _)| (length(s) - 10.0).abs() < 1e-4)); + assert!((p.iter().map(|(s, _)| length(s)).sum::<f64>() - total).abs() < 1e-4); + } + + #[test] + fn only_the_picked_segments_are_divided() { + // Three sides of 20; the middle one picked. + let u = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(20.0, 0.0), Point::new(20.0, 20.0), Point::new(0.0, 20.0)], false); + let p = divide_dashes(&u, Some(&BTreeSet::from([1])), EXACT, 100).unwrap(); + assert_eq!(lengths(&p), [(20_000, Piece::Rest), (10_000, Piece::Dash), (10_000, Piece::Dash), (20_000, Piece::Rest)]); + // Closed: the unpicked rest is one piece round the start. + let sq = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(20.0, 0.0), Point::new(20.0, 20.0), Point::new(0.0, 20.0)], true); + let p = divide_dashes(&sq, Some(&BTreeSet::from([1])), EXACT, 100).unwrap(); + assert_eq!(lengths(&p), [(10_000, Piece::Dash), (10_000, Piece::Dash), (60_000, Piece::Rest)]); + assert!(p.iter().all(|(s, _)| !s.closed)); + } + + #[test] + fn too_many_pieces_or_no_pattern_is_none() { + assert!(divide_dashes(&line(1000.0), None, EXACT, 99).is_none()); + assert!(divide_dashes(&line(1000.0), None, EXACT, 100).is_some()); + for bad in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert!(divide_dashes(&line(10.0), None, DashSpec { dash: bad, ..EXACT }, 100).is_none()); + } + assert!(divide_dashes(&line(10.0), None, DashSpec { gap: -1.0, ..EXACT }, 100).is_none()); + assert!(divide_dashes(&line(1e6), None, DashSpec { dash: 1e-6, ..EXACT }, 100_000).is_none()); + } +} diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index b55c38ccd5..9503a35e44 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,12 +1,13 @@ //! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools), -//! which selects its tools, opens its panels and runs Split / Add Points at Crossings and Convert -//! to Parametric Shape; the Anchor Inspector panel (the selected anchor's position and handles as -//! numbers, the add-on's anchor edits, the Corner Tool's values, [`corner`], and the Shared Edge -//! Merge Tool's, [`shared_edge`]); the Parametric Shape panel ([`shape`]); and its tools' options -//! dialog (a double-click on the tool). Everything acts through `addon.pathtools.*` and +//! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Divide into +//! Dashes ([`dashes`]) and Convert to Parametric Shape; the Anchor Inspector panel (the selected +//! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values, +//! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel +//! ([`shape`]); and its tools' options dialog (a double-click on the tool). Everything acts through `addon.pathtools.*` and //! `tool.setOption`. pub mod corner; +pub mod dashes; pub mod shape; pub mod shared_edge; @@ -63,6 +64,7 @@ pub fn menu() -> Vec<Item> { Item::Sep, Item::Cmd("Add Points at Crossings", "addon.pathtools.crossings", json!({})), Item::Cmd("Split at Crossings", "addon.pathtools.crossings", json!({ "cut": true })), + Item::Cmd("Divide into Dashes…", dashes::COMMAND, Value::Null), Item::Cmd("Convert to Parametric Shape", "addon.pathtools.shape.convert", json!({})), ] } diff --git a/crates/ui-egui/src/addons/pathtools/dashes.rs b/crates/ui-egui/src/addons/pathtools/dashes.rs new file mode 100644 index 0000000000..aa798d03ea --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/dashes.rs @@ -0,0 +1,91 @@ +//! Divide into Dashes in the interface: its dialog (dash and gap lengths, Fit to Corners and Ends, +//! Remove Gaps), which previews on the canvas and runs `addon.pathtools.divideDashes` on OK. + +use egui::Ui; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::state::Dialog; +use crate::widgets; + +/// The command, and its dialog's kind. +pub const COMMAND: &str = "addon.pathtools.divideDashes"; +pub const KIND: &str = "divideDashes"; +/// The dash and gap lengths the command takes (pt). +const DASHES: std::ops::RangeInclusive<f64> = 0.01..=1e6; +const GAPS: std::ops::RangeInclusive<f64> = 0.0..=1e6; +const LABEL_W: f32 = 60.0; +const FIELD_W: f32 = 90.0; + +/// The dialog's fields to start with: the command's defaults. +pub(crate) fn fields() -> Value { + json!({ "dash": 10, "gap": 0, "fit": false, "removeGaps": true }) +} + +pub(crate) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Divide into Dashes").to_string(), body, confirm, preview: true, min_width: 280.0, ..DialogSpec::FORM }; + +fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + let unit = app.session.general_unit(); + widgets::label_row(ui, tl!("Dash:"), LABEL_W, |ui| { + form::length_within(ui, d, "dash", unit, FIELD_W, Some(DASHES)); + }); + widgets::label_row(ui, tl!("Gap:"), LABEL_W, |ui| { + form::length_within(ui, d, "gap", unit, FIELD_W, Some(GAPS)); + }); + form::check(ui, d, "fit", tl!("Fit to Corners and Ends")); + // Without a gap there are no gap pieces to remove. + let gaps = d.f64("gap", 0.0) > 0.0; + ui.add_enabled_ui(gaps, |ui| form::check(ui, d, "removeGaps", tl!("Remove Gaps"))); + form::preview(app, ui, d, "Divide into Dashes", COMMAND, form::params(d)); + false +} + +/// OK: run the command (keep its preview) and close. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { + form::commit_preview(app, COMMAND, form::params(d)) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use vectorcraft_engine::Session; + + use crate::tests_labels::painted_text; + use crate::{VectorcraftApp, menus}; + + #[test] + fn divide_into_dashes_opens_its_dialog_previews_and_runs_on_ok() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let anchors = json!([{"x": 0, "y": 0}, {"x": 100, "y": 0}]); + let id = app.run("path.create", json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Divide into Dashes…").unwrap(); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(&mut app, &cmd, p); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::KIND)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Divide into Dashes", "Dash:", "Gap:", "Fit to Corners and Ends", "Remove Gaps", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().unwrap().len(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("dash".into(), json!(25)); + d.fields.insert("preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(count(&app), 4, "previewed"); + crate::dialogs::cancel(&mut app); + assert_eq!(count(&app), 1, "rolled back"); + menus::invoke(&mut app, &cmd, serde_json::Value::Null); + let n = app.session.doc().unwrap().history.undo.len(); + app.ui.dialog.as_mut().unwrap().fields.insert("gap".into(), json!(10)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1); + // 10 + 10 + … over 100: five dashes, the gaps left empty. + assert_eq!(count(&app), 5); + } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a4eac70418..0f23c2bc4a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -397,6 +397,7 @@ registry! { PathfinderOptions: [pathfinder_options::KIND] => pathfinder_options::SPEC, RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC, PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC, + DivideDashes: [crate::addons::pathtools::dashes::KIND] => crate::addons::pathtools::dashes::SPEC, ArrangeTools: [crate::addons::arrange::GRID, crate::addons::arrange::REPLACE, crate::addons::arrange::SIZE] => crate::addons::arrange::SPEC, ShortcutImport: [shortcut_import::KIND] => DialogSpec::window(shortcut_import::show, shortcut_import::confirm), } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index a960e7dd27..e92164cde9 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5929,6 +5929,15 @@ breakText Glyphs Глифи # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Групиране на припокриващи се обекти @msg too many objects selected (at most 20000) избрани са твърде много обекти (най-много 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Разделяне на тирета… + Divide into Dashes Разделяне на тирета + Dash: Тире: + Gap: Разстояние: + Fit to Corners and Ends Напасване към ъгли и краища + Remove Gaps Премахване на разстоянията +@msg that makes too many pieces (at most 100000): make the dashes longer така се получават твърде много части (най-много 100000): удължете тиретата +@msg select paths, or segments, to divide изберете пътища или сегменти за разделяне Marathi Маратхи Gujarati Гуджарати Bengali Бенгалски diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 6dba3afdf9..68745fa1a9 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5963,6 +5963,15 @@ shape Open Otvoren # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Grupiši preklapajuće objekte @msg too many objects selected (at most 20000) odabrano je previše objekata (najviše 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Podijeli na crtice… + Divide into Dashes Podijeli na crtice + Dash: Crtica: + Gap: Razmak: + Fit to Corners and Ends Uklopi u uglove i krajeve + Remove Gaps Ukloni razmake +@msg that makes too many pieces (at most 100000): make the dashes longer to daje previše dijelova (najviše 100000): produžite crtice +@msg select paths, or segments, to divide odaberite putanje ili segmente za dijeljenje Marathi Marathi Gujarati Gudžarati Bengali Bengalski diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a102f7a7cc..3186093437 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6036,6 +6036,15 @@ breakText Glyphs Glifs # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Agrupa els objectes superposats @msg too many objects selected (at most 20000) s’han seleccionat massa objectes (com a màxim 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Divideix en guions… + Divide into Dashes Divideix en guions + Dash: Guió: + Gap: Separació: + Fit to Corners and Ends Ajusta a les cantonades i els extrems + Remove Gaps Elimina les separacions +@msg that makes too many pieces (at most 100000): make the dashes longer això fa massa trossos (com a màxim 100000): allargueu els guions +@msg select paths, or segments, to divide seleccioneu camins o segments per dividir Marathi Marathi Gujarati Gujarati Bengali Bengalí diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b0c04ffe2d..838906c888 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6046,6 +6046,15 @@ breakText Glyphs Glyfy # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Seskupit překrývající se objekty @msg too many objects selected (at most 20000) vybráno příliš mnoho objektů (nejvýše 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Rozdělit na čárky… + Divide into Dashes Rozdělit na čárky + Dash: Pomlčka: + Gap: Mezera: + Fit to Corners and Ends Přizpůsobit rohům a koncům + Remove Gaps Odstranit mezery +@msg that makes too many pieces (at most 100000): make the dashes longer tím vznikne příliš mnoho dílů (nejvýše 100000): prodlužte čárky +@msg select paths, or segments, to divide vyberte cesty nebo segmenty k rozdělení Marathi Maráthština Gujarati Gudžarátština Bengali Bengálština diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index d85c865bf4..bdde0358b4 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5943,6 +5943,15 @@ breakText Glyphs Glyffer # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Gruppér overlappende objekter @msg too many objects selected (at most 20000) for mange objekter markeret (højst 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Opdel i streger… + Divide into Dashes Opdel i streger + Dash: Tankestreg: + Gap: Afstand: + Fit to Corners and Ends Tilpas til hjørner og ender + Remove Gaps Fjern mellemrum +@msg that makes too many pieces (at most 100000): make the dashes longer det giver for mange stykker (højst 100000): gør stregerne længere +@msg select paths, or segments, to divide vælg stier eller segmenter, der skal opdeles Marathi Marathi Gujarati Gujarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index b1e187de85..a4d2ec778b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5631,6 +5631,15 @@ breakText Glyphs Glyphen # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Überlappende Objekte gruppieren @msg too many objects selected (at most 20000) zu viele Objekte ausgewählt (höchstens 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… In Striche aufteilen… + Divide into Dashes In Striche aufteilen + Dash: Strich: + Gap: Abstand: + Fit to Corners and Ends An Ecken und Enden anpassen + Remove Gaps Lücken entfernen +@msg that makes too many pieces (at most 100000): make the dashes longer das ergibt zu viele Teile (höchstens 100000): machen Sie die Striche länger +@msg select paths, or segments, to divide wählen Sie Pfade oder Segmente zum Aufteilen aus Marathi Marathi Gujarati Gujarati Bengali Bengalisch diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 76d29ca75f..e602041396 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5998,6 +5998,15 @@ breakText Glyphs Γλύφοι # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Ομαδοποίηση επικαλυπτόμενων αντικειμένων @msg too many objects selected (at most 20000) επιλέχθηκαν πάρα πολλά αντικείμενα (το πολύ 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Διαίρεση σε παύλες… + Divide into Dashes Διαίρεση σε παύλες + Dash: Παύλα: + Gap: Απόσταση: + Fit to Corners and Ends Προσαρμογή σε γωνίες και άκρα + Remove Gaps Αφαίρεση κενών +@msg that makes too many pieces (at most 100000): make the dashes longer αυτό δίνει πάρα πολλά κομμάτια (το πολύ 100000): κάντε τις παύλες μεγαλύτερες +@msg select paths, or segments, to divide επιλέξτε διαδρομές ή τμήματα για διαίρεση Marathi Μαραθικά Gujarati Γκουγιαράτι Bengali Βεγγαλικά diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f1d2645dce..8ce984b1d8 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5988,6 +5988,15 @@ breakText Glyphs Glifos # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Agrupar objetos superpuestos @msg too many objects selected (at most 20000) demasiados objetos seleccionados (como máximo 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Dividir en guiones… + Divide into Dashes Dividir en guiones + Dash: Guion: + Gap: Separación: + Fit to Corners and Ends Ajustar a esquinas y extremos + Remove Gaps Quitar separaciones +@msg that makes too many pieces (at most 100000): make the dashes longer eso da demasiados trozos (como máximo 100000): alargue los guiones +@msg select paths, or segments, to divide seleccione trazados o segmentos para dividir Marathi Maratí Gujarati Guyaratí Bengali Bengalí diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 65c7df1264..0380746599 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6076,6 +6076,15 @@ breakText Glyphs Merkit # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Ryhmitä päällekkäiset objektit @msg too many objects selected (at most 20000) liian monta objektia valittu (enintään 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Jaa viivoiksi… + Divide into Dashes Jaa viivoiksi + Dash: Ajatusviiva: + Gap: Väli: + Fit to Corners and Ends Sovita kulmiin ja päihin + Remove Gaps Poista välit +@msg that makes too many pieces (at most 100000): make the dashes longer siitä tulee liian monta osaa (enintään 100000): pidennä viivoja +@msg select paths, or segments, to divide valitse jaettavat polut tai segmentit Marathi Marathi Gujarati Gudžarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index f0d74bcc76..135abca40c 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6043,6 +6043,15 @@ breakText Glyphs Glyphes # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Grouper les objets qui se chevauchent @msg too many objects selected (at most 20000) trop d’objets sélectionnés (20000 au plus) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Diviser en tirets… + Divide into Dashes Diviser en tirets + Dash: Tiret : + Gap: Écart : + Fit to Corners and Ends Ajuster aux angles et aux extrémités + Remove Gaps Supprimer les écarts +@msg that makes too many pieces (at most 100000): make the dashes longer cela donne trop de morceaux (100000 au plus) : allongez les tirets +@msg select paths, or segments, to divide sélectionnez des tracés ou des segments à diviser Marathi Marathi Gujarati Goudjarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index bd2b64965a..9e64f5f39a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6032,6 +6032,15 @@ breakText Glyphs Glifák # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Átfedő objektumok csoportosítása @msg too many objects selected (at most 20000) túl sok objektum van kijelölve (legfeljebb 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Felosztás szaggatásokra… + Divide into Dashes Felosztás szaggatásokra + Dash: Gondolatjel: + Gap: Hézag: + Fit to Corners and Ends Illesztés a sarkokhoz és végekhez + Remove Gaps Hézagok eltávolítása +@msg that makes too many pieces (at most 100000): make the dashes longer ez túl sok darabot adna (legfeljebb 100000): hosszabbítsa meg a szaggatásokat +@msg select paths, or segments, to divide jelöljön ki felosztandó útvonalakat vagy szakaszokat Marathi Maráthi Gujarati Gudzsaráti Bengali Bengáli diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c7a2f0021b..0ec84f9948 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5943,6 +5943,15 @@ breakText Glyphs Glif # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Grupkan objek yang tumpang tindih @msg too many objects selected (at most 20000) terlalu banyak objek dipilih (paling banyak 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Bagi menjadi garis putus… + Divide into Dashes Bagi menjadi garis putus + Dash: Tanda pisah: + Gap: Celah: + Fit to Corners and Ends Paskan ke sudut dan ujung + Remove Gaps Hapus celah +@msg that makes too many pieces (at most 100000): make the dashes longer itu menghasilkan terlalu banyak potongan (paling banyak 100000): perpanjang garisnya +@msg select paths, or segments, to divide pilih jalur atau segmen yang akan dibagi Marathi Marathi Gujarati Gujarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f340b02bc..863fa08e8d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5665,6 +5665,15 @@ breakText Glyphs Glifi # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Raggruppa oggetti sovrapposti @msg too many objects selected (at most 20000) troppi oggetti selezionati (al massimo 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Dividi in trattini… + Divide into Dashes Dividi in trattini + Dash: Trattino: + Gap: Distanza: + Fit to Corners and Ends Adatta ad angoli ed estremità + Remove Gaps Rimuovi le distanze +@msg that makes too many pieces (at most 100000): make the dashes longer così si ottengono troppi pezzi (al massimo 100000): allunga i trattini +@msg select paths, or segments, to divide seleziona tracciati o segmenti da dividere Marathi Marathi Gujarati Gujarati Bengali Bengalese diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index da7fd34f00..c6e9c62fb9 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5732,6 +5732,15 @@ breakText Glyphs 字形 # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects 重なり合うオブジェクトをグループ化 @msg too many objects selected (at most 20000) 選択されたオブジェクトが多すぎます(最大 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… ダッシュに分割… + Divide into Dashes ダッシュに分割 + Dash: ダッシュ: + Gap: 間隔: + Fit to Corners and Ends コーナーと端に合わせる + Remove Gaps 間隔を削除 +@msg that makes too many pieces (at most 100000): make the dashes longer 分割数が多すぎます(最大 100000):ダッシュを長くしてください +@msg select paths, or segments, to divide 分割するパスまたはセグメントを選択してください Marathi マラーティー語 Gujarati グジャラート語 Bengali ベンガル語 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d71ee8b9bd..c37dceb8ea 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6035,6 +6035,15 @@ breakText Glyphs გლიფები # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects გადაფარვადი ობიექტების დაჯგუფება @msg too many objects selected (at most 20000) არჩეულია ძალიან ბევრი ობიექტი (მაქსიმუმ 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… ტირეებად დაყოფა… + Divide into Dashes ტირეებად დაყოფა + Dash: ტირე: + Gap: ღრეჩო: + Fit to Corners and Ends კუთხეებსა და ბოლოებზე მორგება + Remove Gaps ღრეჩოების მოცილება +@msg that makes too many pieces (at most 100000): make the dashes longer ეს ძალიან ბევრ ნაწილს იძლევა (მაქსიმუმ 100000): გაზარდეთ ტირეების სიგრძე +@msg select paths, or segments, to divide აირჩიეთ დასაყოფი კონტურები ან სეგმენტები Marathi მარათჰი Gujarati გუჯარათი Bengali ბენგალური diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 6b9ef0524f..0d03c7496e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5628,6 +5628,15 @@ breakText Glyphs 글리프 # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects 겹치는 개체 그룹화 @msg too many objects selected (at most 20000) 선택한 개체가 너무 많습니다(최대 20000개) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… 대시로 나누기… + Divide into Dashes 대시로 나누기 + Dash: 대시: + Gap: 간격: + Fit to Corners and Ends 모퉁이와 끝에 맞추기 + Remove Gaps 간격 제거 +@msg that makes too many pieces (at most 100000): make the dashes longer 조각이 너무 많아집니다(최대 100000개). 대시를 더 길게 하십시오 +@msg select paths, or segments, to divide 나눌 패스나 세그먼트를 선택하십시오 Marathi 마라티어 Gujarati 구자라트어 Bengali 벵골어 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c4d9c535e1..acecce2dcb 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5987,6 +5987,15 @@ breakText Glyphs Glyphs # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Overlappende objecten groeperen @msg too many objects selected (at most 20000) te veel objecten geselecteerd (hoogstens 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Verdelen in streepjes… + Divide into Dashes Verdelen in streepjes + Dash: Streepje: + Gap: Tussenruimte: + Fit to Corners and Ends Passend maken op hoeken en uiteinden + Remove Gaps Tussenruimten verwijderen +@msg that makes too many pieces (at most 100000): make the dashes longer dat geeft te veel stukken (hoogstens 100000): maak de streepjes langer +@msg select paths, or segments, to divide selecteer paden of segmenten om te verdelen Marathi Marathi Gujarati Gujarati Bengali Bengaals diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2418eae3cd..4b42f1e2d3 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5901,6 +5901,15 @@ breakText Glyphs Glify # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Grupuj nakładające się obiekty @msg too many objects selected (at most 20000) zaznaczono za dużo obiektów (najwyżej 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Podziel na kreski… + Divide into Dashes Podziel na kreski + Dash: Myślnik: + Gap: Odstęp: + Fit to Corners and Ends Dopasuj do narożników i końców + Remove Gaps Usuń odstępy +@msg that makes too many pieces (at most 100000): make the dashes longer to daje za dużo części (najwyżej 100000): wydłuż kreski +@msg select paths, or segments, to divide zaznacz ścieżki lub segmenty do podzielenia Marathi Marathi Gujarati Gudżarati Bengali Bengalski diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 34b223428a..86518877a3 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5965,6 +5965,15 @@ breakText Glyphs Glifos # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Agrupar objetos sobrepostos @msg too many objects selected (at most 20000) objetos demais selecionados (no máximo 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Dividir em traços… + Divide into Dashes Dividir em traços + Dash: Travessão: + Gap: Distância: + Fit to Corners and Ends Ajustar aos cantos e extremidades + Remove Gaps Remover distâncias +@msg that makes too many pieces (at most 100000): make the dashes longer isso gera peças demais (no máximo 100000): aumente os traços +@msg select paths, or segments, to divide selecione demarcadores ou segmentos para dividir Marathi Marati Gujarati Guzerate Bengali Bengali diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 747c915850..2b0b85161c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6023,6 +6023,15 @@ breakText Glyphs Глифы # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Сгруппировать перекрывающиеся объекты @msg too many objects selected (at most 20000) выделено слишком много объектов (не более 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Разделить на штрихи… + Divide into Dashes Разделить на штрихи + Dash: Тире: + Gap: Зазор: + Fit to Corners and Ends Подогнать к углам и концам + Remove Gaps Убрать зазоры +@msg that makes too many pieces (at most 100000): make the dashes longer так получится слишком много частей (не более 100000): удлините штрихи +@msg select paths, or segments, to divide выделите контуры или сегменты для разделения Marathi Маратхи Gujarati Гуджарати Bengali Бенгальский diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 26b3a1d59d..e6ab913806 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6098,6 +6098,15 @@ breakText Glyphs Glyfer # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Gruppera överlappande objekt @msg too many objects selected (at most 20000) för många objekt markerade (högst 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Dela upp i streck… + Divide into Dashes Dela upp i streck + Dash: Tankstreck: + Gap: Mellanrum: + Fit to Corners and Ends Anpassa till hörn och ändar + Remove Gaps Ta bort mellanrum +@msg that makes too many pieces (at most 100000): make the dashes longer det blir för många delar (högst 100000): gör strecken längre +@msg select paths, or segments, to divide markera banor eller segment att dela upp Marathi Marathi Gujarati Gujarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a4851f2e3c..c4b924a012 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6003,6 +6003,15 @@ breakText Glyphs Glifler # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Çakışan Nesneleri Grupla @msg too many objects selected (at most 20000) çok fazla nesne seçili (en fazla 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Tirelere Böl… + Divide into Dashes Tirelere Böl + Dash: Tire: + Gap: Boşluk: + Fit to Corners and Ends Köşelere ve Uçlara Uydur + Remove Gaps Boşlukları Kaldır +@msg that makes too many pieces (at most 100000): make the dashes longer bu çok fazla parça oluşturur (en fazla 100000): tireleri uzatın +@msg select paths, or segments, to divide bölünecek yolları veya bölümleri seçin Marathi Marathi dili Gujarati Gücerat dili Bengali Bengalce diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index a4c04383aa..d22468de3b 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5645,6 +5645,15 @@ breakText Glyphs Гліфи # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Згрупувати об’єкти, що перекриваються @msg too many objects selected (at most 20000) виділено забагато об’єктів (не більше 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Розділити на штрихи… + Divide into Dashes Розділити на штрихи + Dash: Тире: + Gap: Проміжок: + Fit to Corners and Ends Припасувати до кутів і кінців + Remove Gaps Прибрати проміжки +@msg that makes too many pieces (at most 100000): make the dashes longer так вийде забагато частин (не більше 100000): подовжте штрихи +@msg select paths, or segments, to divide виділіть контури або сегменти для розділення Marathi Маратхі Gujarati Гуджараті Bengali Бенгальська diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index ab593787bb..f6b12617a0 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5648,6 +5648,15 @@ breakText Glyphs Glyph # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects Nhóm các đối tượng chồng lên nhau @msg too many objects selected (at most 20000) chọn quá nhiều đối tượng (tối đa 20000) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… Chia thành nét đứt… + Divide into Dashes Chia thành nét đứt + Dash: Gạch ngang: + Gap: Khoảng hở: + Fit to Corners and Ends Khớp với góc và đầu mút + Remove Gaps Gỡ các khoảng hở +@msg that makes too many pieces (at most 100000): make the dashes longer như vậy tạo ra quá nhiều mảnh (tối đa 100000): hãy kéo dài nét +@msg select paths, or segments, to divide chọn các đường dẫn hoặc đoạn để chia Marathi Tiếng Marathi Gujarati Tiếng Gujarati Bengali Tiếng Bengali diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 9b506a128f..9381523e5e 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5888,6 +5888,15 @@ breakText Glyphs 字形 # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects 编组重叠对象 @msg too many objects selected (at most 20000) 选择的对象过多(最多 20000 个) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… 分割为短划线… + Divide into Dashes 分割为短划线 + Dash: 短划线: + Gap: 间隙: + Fit to Corners and Ends 适合转角和端点 + Remove Gaps 移除间隙 +@msg that makes too many pieces (at most 100000): make the dashes longer 这会产生过多片段(最多 100000 个):请加长短划线 +@msg select paths, or segments, to divide 请选择要分割的路径或线段 Marathi 马拉地语 Gujarati 古吉拉特语 Bengali 孟加拉语 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 3e645ca095..0d6ae8b2b4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5685,6 +5685,15 @@ breakText Glyphs 字符 # Arrange Tools add-on: Group Overlapping Objects. Group Overlapping Objects 群組重疊物件 @msg too many objects selected (at most 20000) 選取的物件過多(最多 20000 個) +# Path Precision Tools add-on: Divide into Dashes. + Divide into Dashes… 分割為短破折號… + Divide into Dashes 分割為短破折號 + Dash: 短破折號: + Gap: 間隙: + Fit to Corners and Ends 符合轉角和端點 + Remove Gaps 移除間隙 +@msg that makes too many pieces (at most 100000): make the dashes longer 這會產生過多片段(最多 100000 個):請加長短破折號 +@msg select paths, or segments, to divide 請選取要分割的路徑或線段 Marathi 馬拉地文 Gujarati 古吉拉特文 Bengali 孟加拉文 diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 70c8639710..77dd67f447 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -68,6 +68,7 @@ pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static st ("splitIntoGrid", crate::dialogs::path_ops::split_fields(size.0, size.1)) } "object.vectorHalftone" => (crate::dialogs::halftone::KIND, crate::dialogs::halftone::fields()), + crate::addons::pathtools::dashes::COMMAND => (crate::addons::pathtools::dashes::KIND, crate::addons::pathtools::dashes::fields()), "artboard.rearrange" => (crate::dialogs::rearrange_artboards::KIND, crate::dialogs::rearrange_artboards::open_fields(app)), _ => return None, }) diff --git a/docs/mcp.md b/docs/mcp.md index 705b9d54b3..8c1d1f907a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5966,6 +5966,16 @@ Commands: - `addon.pathtools.crossings {cut?, selfCrossings?, ids?}` adds anchors where the selected paths cross one another (and where each crosses itself, with `selfCrossings`), or with `cut` also cuts them there: a path of one subpath becomes a path per piece. Paths that meet at a shared anchor don't cross there; at most 10,000 segments at once. +- `addon.pathtools.divideDashes {dash?, gap?, fit?, removeGaps?}` cuts the selected paths into separate open paths + along the curve, each `dash` long (0.01 to 1,000,000 pt, 10 by default) with `gap` between them (0 to 1,000,000 pt, + 0 by default: the pieces touch), every piece keeping the path's appearance, as one undo step. The gap pieces are left + out unless `removeGaps` is false. With direct-selected segments (or anchors) only those runs are divided, the + pattern running on across segments that follow one another; the rest of such a path stays as pieces of its own. + With `fit`, every run between corners and ends holds a whole number of dashes, all stretched or squeezed alike so it + starts and ends on a dash (a closed path with no corner holds whole periods); otherwise the lengths are exact and the + last piece of each run is what is left. The pieces are selected; more than 100,000 is refused. → `{ids, dashes}`. + Divide into Dashes… opens a dialog (`ui.menuDialog {command}`, kind `divideDashes`) whose fields are these + parameters, with Preview. - `addon.pathtools.cornerSet {ids?, anchors?, items?, radius, kind?}` cuts live corners, the ones Direct Selection's corner widgets and the Corners dialog edit, as one undo step. `ids` (default: the selection) are the paths and `anchors` the anchor indices of each path's outline with no corners cut; without `anchors`, a path's direct-selected diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1a0fe7d618..2f2a226425 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Arrange Tools add-on: Group Overlapping Objects, #4928; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Path Precision Tools add-on: Divide into Dashes, #4950; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -1403,10 +1403,15 @@ dialogs, Preview and Cancel, Zoom to Selection) and `command_sweep`. Commands: ` A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the top-level selected objects wherever their visual bounds overlap or touch, chains included (A overlapping B and B overlapping C makes one group of three), only among objects of the same layer or group; objects that overlap nothing stay as they are, each new group takes its frontmost member's place in the stacking order, and the groups and the loose objects stay selected. One undo step; at most 20000 objects, compared by a sweep along x with union-find. Tests: `group_overlapping_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (chains, loners, stacking order, layers kept apart, visual bounds, no step when nothing overlaps, many objects), `group_overlapping_objects_runs_directly` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +## Path Precision Tools add-on: Divide into Dashes (2026-11-01) + +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Divide into Dashes… cuts the selected paths into separate open paths along the curve (arc length, not straight distance): each `dash` long (0.01 to 1000000 pt, 10 by default) with `gap` between them (0 by default: the pieces touch); the gap pieces are left out unless Remove Gaps is off. With direct-selected segments (or anchors) only those runs are divided, the pattern running on across segments that follow one another, and the rest of such a path stays as pieces of its own. Fit to Corners and Ends gives every run between corners and ends a whole number of dashes, all stretched or squeezed alike so it starts and ends on a dash (a closed path without corners holds whole periods); otherwise the lengths are exact and each run's last piece is what is left. Every piece keeps the path's appearance and is selected; one undo step; at most 100000 pieces (more is refused). The dialog takes lengths in any unit and previews on the canvas. Tests: `dashes::tests` in `vectorcraft-pathops` (exact and fitted lengths, curves measured along them, picked segments on open and closed paths, the piece cap and bad patterns), `divide_into_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (gaps removed or kept, fitted lengths, the stroke kept, one undo step, selected segments only, bad params and too many pieces refused), `divide_into_dashes_opens_its_dialog_previews_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. + ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Path Precision Tools add-on (a VectorCraft addition): Divide into Dashes (#4950); evidence added; scores unchanged. | | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Group Overlapping Objects (#4928); evidence added; scores unchanged. | | 2026-11-01 | minor | Type core: a Language per character (Character panel › Language, `text.setFormat` / `text.setRangeStyle {language}`, character styles), new type in the document's language; text is shaped in its language so fonts use their language forms (OpenType `locl`: Turkish `fi`, #4940, #4946); Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu in the language list (#4943); scores unchanged | | 2026-10-31 | minor | Selection tools: with Alt held at the press, a Direct Selection marquee selects every path it touches whole and keeps the Group Selection pointer (#4890); a press on a selected object's centre point selects the object whole and a drag from it moves it (#4891); regression tests in `direct/tests.rs`; scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 6672e0f94f..6c31deb0a5 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Arrange Tools add-on: Group Overlapping Objects, #4928) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Path Precision Tools add-on: Divide into Dashes, #4950) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -332,6 +332,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | | Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its seven tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its four tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/shape.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its six tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | @@ -382,6 +383,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Path Precision Tools add-on (a VectorCraft addition): Divide into Dashes (#4950); scores and estimates unchanged | | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Group Overlapping Objects (#4928); scores and estimates unchanged | | 2026-11-01 | minor | Character panel › Language: the selected characters' language, from Document Setup's list, which gains Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu (#4946, #4943); the Digits menu's numeral names keep their own translations; scores unchanged | | 2026-11-01 | minor | VectorCraft Options' Version is a menu of the versions VectorCraft writes, each named by the releases that read it, and an uncompressible version turns Use Compression off (#4931); a save refused before writing shows the Can't save alert with the reason (#4933); About › Contributors' table keeps its header row above the scrolling rows (#4944); the Gradient panel's freeform point swatch opens the point's popover (#4953); scores unchanged | From 916b60898a5f5de5179e37239d4637a829b0cc8d Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 02:42:19 +0700 Subject: [PATCH 171/260] Fix #4927: Save a Timestamped Copy --- ROADMAP.md | 4 +- crates/engine/src/cmd/addons.rs | 2 + crates/engine/src/cmd/addons/document.rs | 73 ++++++++++++++ .../engine/src/cmd/addons/document/tests.rs | 98 +++++++++++++++++++ crates/engine/src/cmd/fileio.rs | 1 + crates/engine/src/cmd/fileio/save.rs | 2 +- crates/engine/tests/command_sweep.rs | 3 + crates/ui-egui/src/addons.rs | 2 + crates/ui-egui/src/addons/document.rs | 30 ++++++ crates/ui-egui/src/addons/document/tests.rs | 63 ++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 7 ++ crates/ui-egui/src/i18n/bs.tsv | 7 ++ crates/ui-egui/src/i18n/ca.tsv | 7 ++ crates/ui-egui/src/i18n/cs.tsv | 7 ++ crates/ui-egui/src/i18n/da.tsv | 7 ++ crates/ui-egui/src/i18n/de.tsv | 7 ++ crates/ui-egui/src/i18n/el.tsv | 7 ++ crates/ui-egui/src/i18n/es.tsv | 7 ++ crates/ui-egui/src/i18n/fi.tsv | 7 ++ crates/ui-egui/src/i18n/fr.tsv | 7 ++ crates/ui-egui/src/i18n/hu.tsv | 7 ++ crates/ui-egui/src/i18n/id.tsv | 7 ++ crates/ui-egui/src/i18n/it.tsv | 7 ++ crates/ui-egui/src/i18n/ja.tsv | 7 ++ crates/ui-egui/src/i18n/ka.tsv | 7 ++ crates/ui-egui/src/i18n/ko.tsv | 7 ++ crates/ui-egui/src/i18n/nl.tsv | 7 ++ crates/ui-egui/src/i18n/pl.tsv | 7 ++ crates/ui-egui/src/i18n/pt-br.tsv | 7 ++ crates/ui-egui/src/i18n/ru.tsv | 7 ++ crates/ui-egui/src/i18n/sv.tsv | 7 ++ crates/ui-egui/src/i18n/tr.tsv | 7 ++ crates/ui-egui/src/i18n/uk.tsv | 7 ++ crates/ui-egui/src/i18n/vi.tsv | 7 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 7 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 7 ++ crates/ui-egui/src/menus/run.rs | 1 + docs/mcp.md | 18 ++++ docs/target-app-parity.md | 7 +- docs/ui-parity.md | 4 +- 40 files changed, 486 insertions(+), 4 deletions(-) create mode 100644 crates/engine/src/cmd/addons/document.rs create mode 100644 crates/engine/src/cmd/addons/document/tests.rs create mode 100644 crates/ui-egui/src/addons/document.rs create mode 100644 crates/ui-egui/src/addons/document/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index b8365d0f0f..d61922cbe9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -9,7 +9,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for Divide into Dashes in the Path Precision Tools add-on; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Document Tools add-on's Save a Timestamped Copy; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<name>_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. @@ -206,6 +207,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Progress log row for the Document Tools add-on's Save a Timestamped Copy (#4926); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for Divide into Dashes (Path Precision Tools add-on, #4950); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for Group Overlapping Objects (Arrange Tools add-on, #4928); headline numbers unchanged. | | 2026-10-31 | minor | Progress log row for Export for Screens laid out as the reference app's (#4895) and the 2026-10-31 community landings; headline numbers unchanged. | diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 2e153491b1..21d73cc4f8 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -4,6 +4,7 @@ mod arrange; mod cleanup; mod color; +mod document; mod pathtools; mod pen; @@ -14,6 +15,7 @@ pub fn specs() -> Vec<CommandSpec> { let mut v = arrange::specs(); v.extend(cleanup::specs()); v.extend(color::specs()); + v.extend(document::specs()); v.extend(pathtools::specs()); v.extend(pen::specs()); v diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs new file mode 100644 index 0000000000..b4911e4759 --- /dev/null +++ b/crates/engine/src/cmd/addons/document.rs @@ -0,0 +1,73 @@ +//! Document Tools (`addon.document.*`), a built-in add-on: Save a Timestamped Copy writes a copy of +//! the document named with the date and time through File › Save a Copy's save. Its submenu +//! (Object › Plug-ins › Document Tools) is the UI's. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; + +use super::super::fileio::{self, SaveMode}; +use super::super::{CommandSpec, bad, clock_date, cmd, date_param, has_doc, str_param}; +use crate::{Result, Session}; + +/// The most numbers (`-2`, `-3`…) tried after a timestamped name that is taken. +const MAX_NUMBER: u32 = 999; + +pub fn specs() -> Vec<CommandSpec> { + vec![cmd!( + "addon.document.saveTimestampedCopy", + "Save a Timestamped Copy", + ["Object", "Plug-ins", "Document Tools"], + None, + "{folder? (default: the document's own folder; needed for a document never saved), format?: vectorcraft|pdf|svg|svgz|ai|eps (default: the document's own, else vectorcraft), time?: Unix seconds (default: now)} write a copy of the document named <name>_YYYY-MM-DD_HH-MM.<ext> (the date and time in UTC; -2, -3… added when that name is taken) as File › Save a Copy writes it: the document keeps its path, title and modified state, and no undo step is made. Off where there is no clock (the web) → {path, format, bytes, warnings}", + has_clock, + save_timestamped_copy + )] +} + +/// A document is open and the time can be told. +fn has_clock(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + vectorcraft_doc::metadata::output_time().map(|_| ()).ok_or_else(|| "there is no clock here".into()) +} + +/// `<base>.<ext>`, then `<base>-2.<ext>`… in `folder`: the first that `taken` doesn't hold. +fn free_name(folder: &str, base: &str, ext: &str, taken: impl Fn(&str) -> bool) -> Option<String> { + (1..=MAX_NUMBER) + .map(|i| { + let name = if i == 1 { format!("{base}.{ext}") } else { format!("{base}-{i}.{ext}") }; + std::path::Path::new(folder).join(name).to_string_lossy().into_owned() + }) + .find(|path| !taken(path)) +} + +fn save_timestamped_copy(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "addon.document.saveTimestampedCopy"; + let st = s.doc()?; + let format = match str_param(p, "format") { + Some(f) => fileio::save_format(Some(f), None), + // A document opened from a format Save doesn't write (a picture, a drawing) copies as native. + None => fileio::save_format(Some(st.format), None).or_else(|_| fileio::save_format(None, None)), + } + .map_err(|e| bad(C, e))?; + let folder = match str_param(p, "folder").filter(|f| !f.trim().is_empty()) { + Some(f) => f.to_string(), + None => st + .path + .as_deref() + .and_then(|path| std::path::Path::new(path).parent()) + .map(|f| f.to_string_lossy().into_owned()) + .filter(|f| !f.is_empty()) + .ok_or_else(|| bad(C, "the document has never been saved: give `folder`"))?, + }; + let stem = fileio::file_stem(st.path.as_deref().unwrap_or(&st.doc.title)); + let given = date_param(p, "time", C)?; + let t = clock_date(s, "time", given).ok_or_else(|| bad(C, "there is no clock here: give `time` (Unix seconds)"))?; + let [y, mo, d, h, mi, _] = vectorcraft_doc::metadata::civil(t); + let base = format!("{stem}_{y:04}-{mo:02}-{d:02}_{h:02}-{mi:02}"); + // Only whether something is there: the write itself goes through the automation roots. + let path = free_name(&folder, &base, format.extensions[0], |p| std::path::Path::new(p).exists()) + .ok_or_else(|| bad(C, "every numbered name for the copy is taken"))?; + fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id })) +} diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs new file mode 100644 index 0000000000..362ea1a43b --- /dev/null +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -0,0 +1,98 @@ +//! Document Tools' commands: the copy's name and place, the document left as it was, and bad +//! params refused. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::Session; + +/// 2026-10-05 14:03:00 UTC. +const TIME: i64 = 1_791_208_980; + +/// A new, empty folder of its own for test `name`. +fn folder(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("vc-addon-document-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + s +} + +fn stamp(s: &mut Session, p: Value) -> crate::Result<Value> { + s.execute("addon.document.saveTimestampedCopy", &p) +} + +#[test] +fn a_timestamped_copy_goes_next_to_the_document_which_stays_as_it_was() { + let dir = folder("next-to"); + let mut s = session(); + let own = dir.join("poster.vectorcraft"); + s.execute("document.save", &json!({"path": own})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + let (steps, title) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().doc.title.clone()); + let r = stamp(&mut s, json!({"time": TIME})).unwrap(); + let copy = dir.join("poster_2026-10-05_14-03.vectorcraft"); + assert_eq!(Path::new(r["path"].as_str().unwrap()), copy); + assert!(copy.is_file()); + let st = s.doc().unwrap(); + assert_eq!(st.path.as_deref().map(Path::new), Some(own.as_path()), "the document keeps its path"); + assert_eq!((st.history.undo.len(), &st.doc.title, st.is_dirty()), (steps, &title, true), "no step; still modified"); + // The copy holds the document as it is now: the ellipse too. + let mut other = Session::new(); + other.execute("document.open", &json!({"path": copy})).unwrap(); + assert_eq!(other.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); + // The same minute again: numbered. + let r = stamp(&mut s, json!({"time": TIME})).unwrap(); + assert!(r["path"].as_str().unwrap().ends_with("poster_2026-10-05_14-03-2.vectorcraft"), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_unsaved_document_needs_a_folder_and_other_formats_take_their_extension() { + let dir = folder("unsaved"); + let mut s = session(); + let before = s.doc().unwrap().doc.clone(); + assert!(stamp(&mut s, json!({"time": TIME})).is_err(), "no folder to put it in"); + let r = stamp(&mut s, json!({"time": TIME, "folder": dir, "format": "svg"})).unwrap(); + let name = Path::new(r["path"].as_str().unwrap()).file_name().unwrap().to_string_lossy().into_owned(); + assert!(name.ends_with("_2026-10-05_14-03.svg") && dir.join(&name).is_file(), "{name}"); + let st = s.doc().unwrap(); + assert!(st.path.is_none() && *st.doc == *before, "the document is unchanged"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn bad_params_are_refused_and_writes_stay_inside_the_automation_roots() { + let dir = folder("bad"); + let mut s = session(); + for p in [ + json!({"folder": dir, "format": "png"}), + json!({"folder": dir, "format": "dxf"}), + json!({"folder": dir, "time": "now"}), + json!({"folder": dir, "time": 1.5}), + json!({"folder": dir.join("missing").join("deeper"), "time": TIME}), + ] { + assert!(stamp(&mut s, p.clone()).is_err(), "{p}"); + } + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "nothing written"); + let allowed = dir.join("allowed"); + std::fs::create_dir_all(&allowed).unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[&dir], &[&allowed]).unwrap(); + let outside = crate::file_access::confine(roots.as_ref(), || stamp(&mut s, json!({"folder": dir, "time": TIME}))); + assert!(outside.is_err(), "outside the write root"); + let inside = crate::file_access::confine(roots.as_ref(), || stamp(&mut s, json!({"folder": allowed, "time": TIME}))); + assert!(inside.is_ok(), "{inside:?}"); + assert!(!enabled_without_document(), "off with no document"); + let _ = std::fs::remove_dir_all(&dir); +} + +fn enabled_without_document() -> bool { + Session::new().commands().into_iter().find(|c| c.id == "addon.document.saveTimestampedCopy").unwrap().enabled +} diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 7471ffb56a..e41bdd9b2a 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -75,6 +75,7 @@ pub(crate) use native::preview_png; pub use native::with_compression_pref; pub use pdfimport::{LoadOptions, page_document}; pub(crate) use save::job_for; +pub(crate) use save::save as save_document; pub use save::{ SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, export_folder, reads_option as save_reads_option, remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates, template_filters, templates_dialog_folder, diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 4a8d564218..a38c4b93ce 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -897,7 +897,7 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8]) } /// A save command: plan, then write with the file system (a native file as it is encoded). -fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value> { +pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value> { let plan = save_plan(s, mode, p)?; let job = save_job(s, plan)?; let uid = s.doc()?.uid; diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 36fe6401d5..c53f51b2ac 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -592,6 +592,9 @@ fn structured_junk() { ("addon.pathtools.divideDashes", json!({"dash": 1e-308, "gap": -1e308, "fit": "x"})), ("addon.pathtools.divideDashes", json!({"dash": 0.01, "gap": 1e6, "fit": true, "removeGaps": false})), ("addon.pathtools.divideDashes", json!({"dash": f64::MAX, "gap": [0], "removeGaps": null})), + // Refused before anything is written: no format of that name, a time that is no time. + ("addon.document.saveTimestampedCopy", json!({"format": "png", "folder": 7})), + ("addon.document.saveTimestampedCopy", json!({"format": "svg", "time": [1e308], "folder": null})), // Smart Pen add-on. ("addon.pen.append", json!({"id": 2, "x": 1e308, "y": 0, "in": [1e308, -1e308]})), ("addon.pen.append", json!({"id": 2, "subpath": u64::MAX, "x": 0, "y": 0, "segment": "curved"})), diff --git a/crates/ui-egui/src/addons.rs b/crates/ui-egui/src/addons.rs index 4d148ff586..65210c6d22 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -4,6 +4,7 @@ pub mod arrange; pub mod cleanup; pub mod color; +pub mod document; pub mod pathtools; pub mod pen; @@ -15,6 +16,7 @@ pub fn plugin_menu() -> Vec<Item> { Item::Sub("Arrange Tools", arrange::menu()), Item::Sub("Artwork Cleanup", cleanup::menu()), Item::Sub("Color Effects", color::menu()), + Item::Sub("Document Tools", document::menu()), Item::Sub("Path Precision Tools", pathtools::menu()), Item::Sub("Smart Pen", pen::menu()), Item::Sep, diff --git a/crates/ui-egui/src/addons/document.rs b/crates/ui-egui/src/addons/document.rs new file mode 100644 index 0000000000..a948749692 --- /dev/null +++ b/crates/ui-egui/src/addons/document.rs @@ -0,0 +1,30 @@ +//! Document Tools in the interface: its submenu (Object › Plug-ins › Document Tools). Save a +//! Timestamped Copy of a document never saved asks for the folder to put it in ([`save_copy`]). + +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::menus::Item; + +/// Save a Timestamped Copy. +pub const SAVE_COPY: &str = "addon.document.saveTimestampedCopy"; + +/// Object › Plug-ins › Document Tools. +pub fn menu() -> Vec<Item> { + vec![Item::Cmd("Save a Timestamped Copy", SAVE_COPY, json!({}))] +} + +/// Save a Timestamped Copy with params `p`: a document never saved, given no `folder`, goes in the +/// folder picked. The status bar says where the copy went. +pub(crate) fn save_copy(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { + let mut p = if p.is_object() { p.clone() } else { json!({}) }; + if p.get("folder").is_none() && app.session.active().is_some_and(|st| st.path.is_none()) { + p["folder"] = json!(crate::picks::folder(app).ok_or("cancelled")?); + } + let r = app.session.execute(SAVE_COPY, &p).map_err(|e| e.to_string())?; + crate::io::report_saved(app, r["path"].as_str().unwrap_or_default(), &r); + Ok(r) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/document/tests.rs b/crates/ui-egui/src/addons/document/tests.rs new file mode 100644 index 0000000000..cf43d59e1c --- /dev/null +++ b/crates/ui-egui/src/addons/document/tests.rs @@ -0,0 +1,63 @@ +use std::path::PathBuf; + +use serde_json::json; +use vectorcraft_engine::Session; + +use super::SAVE_COPY; +use crate::{VectorcraftApp, menus}; + +/// A new, empty folder of its own for test `name`. +fn folder(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("vc-ui-document-tools-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app +} + +/// Click the Document Tools item `label`. +fn click(app: &mut VectorcraftApp, label: &str) { + let entries = menus::menu_entries(app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Document Tools"] && e.label == label).expect(label); + let (id, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(app, &id, p); +} + +fn files(dir: &PathBuf) -> Vec<String> { + std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect() +} + +#[test] +fn save_a_timestamped_copy_writes_beside_the_document() { + let dir = folder("beside"); + let mut app = app(); + app.run("document.save", json!({"path": dir.join("card.vectorcraft")})).unwrap(); + assert_eq!(menus::menu_entries(&app).iter().find(|e| e.label == "Save a Timestamped Copy").and_then(|e| e.command.as_deref()), Some(SAVE_COPY)); + click(&mut app, "Save a Timestamped Copy"); + let names = files(&dir); + assert_eq!(names.len(), 2, "{names:?}"); + assert!(names.iter().any(|n| n.starts_with("card_20") && n.ends_with(".vectorcraft")), "{names:?}"); + assert!(app.ui.status.starts_with("Saved "), "{}", app.ui.status); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_unsaved_document_asks_for_a_folder() { + let dir = folder("picked"); + let mut app = app(); + let picked = dir.to_string_lossy().into_owned(); + app.services.pick_folder = Some(Box::new(move || Some(picked.clone()))); + click(&mut app, "Save a Timestamped Copy"); + assert_eq!(files(&dir).len(), 1); + assert!(app.session.doc().unwrap().path.is_none(), "the document stays unsaved"); + // No folder picked: nothing written. + app.services.pick_folder = Some(Box::new(|| None)); + assert_eq!(app.run(SAVE_COPY, json!({})).unwrap_err(), "cancelled"); + assert_eq!(files(&dir).len(), 1); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index e92164cde9..519247e09c 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5938,6 +5938,13 @@ breakText Glyphs Глифи Remove Gaps Премахване на разстоянията @msg that makes too many pieces (at most 100000): make the dashes longer така се получават твърде много части (най-много 100000): удължете тиретата @msg select paths, or segments, to divide изберете пътища или сегменти за разделяне +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Инструменти за документи + Save a Timestamped Copy Запазване на копие с дата и час +@msg there is no clock here тук няма часовник +@msg there is no clock here: give `time` (Unix seconds) тук няма часовник: задайте `time` (Unix секунди) +@msg the document has never been saved: give `folder` документът никога не е запазван: задайте `folder` +@msg every numbered name for the copy is taken всички номерирани имена за копието са заети Marathi Маратхи Gujarati Гуджарати Bengali Бенгалски diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 68745fa1a9..5910e59045 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5972,6 +5972,13 @@ shape Open Otvoren Remove Gaps Ukloni razmake @msg that makes too many pieces (at most 100000): make the dashes longer to daje previše dijelova (najviše 100000): produžite crtice @msg select paths, or segments, to divide odaberite putanje ili segmente za dijeljenje +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Alati za dokument + Save a Timestamped Copy Sačuvaj kopiju s datumom i vremenom +@msg there is no clock here ovdje nema sata +@msg there is no clock here: give `time` (Unix seconds) ovdje nema sata: navedite `time` (Unix sekunde) +@msg the document has never been saved: give `folder` dokument nikad nije sačuvan: navedite `folder` +@msg every numbered name for the copy is taken sva numerisana imena za kopiju su zauzeta Marathi Marathi Gujarati Gudžarati Bengali Bengalski diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 3186093437..6c2ccc29a0 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6045,6 +6045,13 @@ breakText Glyphs Glifs Remove Gaps Elimina les separacions @msg that makes too many pieces (at most 100000): make the dashes longer això fa massa trossos (com a màxim 100000): allargueu els guions @msg select paths, or segments, to divide seleccioneu camins o segments per dividir +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Eines del document + Save a Timestamped Copy Desa una còpia amb data i hora +@msg there is no clock here aquí no hi ha rellotge +@msg there is no clock here: give `time` (Unix seconds) aquí no hi ha rellotge: indiqueu `time` (segons Unix) +@msg the document has never been saved: give `folder` el document no s’ha desat mai: indiqueu `folder` +@msg every numbered name for the copy is taken tots els noms numerats per a la còpia estan ocupats Marathi Marathi Gujarati Gujarati Bengali Bengalí diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 838906c888..cc0fbfa1bd 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6055,6 +6055,13 @@ breakText Glyphs Glyfy Remove Gaps Odstranit mezery @msg that makes too many pieces (at most 100000): make the dashes longer tím vznikne příliš mnoho dílů (nejvýše 100000): prodlužte čárky @msg select paths, or segments, to divide vyberte cesty nebo segmenty k rozdělení +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Nástroje dokumentu + Save a Timestamped Copy Uložit kopii s datem a časem +@msg there is no clock here nejsou k dispozici hodiny +@msg there is no clock here: give `time` (Unix seconds) nejsou k dispozici hodiny: zadejte `time` (sekundy Unix) +@msg the document has never been saved: give `folder` dokument nebyl nikdy uložen: zadejte `folder` +@msg every numbered name for the copy is taken všechny číslované názvy kopie jsou obsazené Marathi Maráthština Gujarati Gudžarátština Bengali Bengálština diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index bdde0358b4..e77983fcb8 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5952,6 +5952,13 @@ breakText Glyphs Glyffer Remove Gaps Fjern mellemrum @msg that makes too many pieces (at most 100000): make the dashes longer det giver for mange stykker (højst 100000): gør stregerne længere @msg select paths, or segments, to divide vælg stier eller segmenter, der skal opdeles +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Dokumentværktøjer + Save a Timestamped Copy Gem en kopi med dato og klokkeslæt +@msg there is no clock here der er intet ur her +@msg there is no clock here: give `time` (Unix seconds) der er intet ur her: angiv `time` (Unix-sekunder) +@msg the document has never been saved: give `folder` dokumentet er aldrig blevet gemt: angiv `folder` +@msg every numbered name for the copy is taken alle nummererede navne til kopien er optaget Marathi Marathi Gujarati Gujarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index a4d2ec778b..5a3bf8ef52 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5640,6 +5640,13 @@ breakText Glyphs Glyphen Remove Gaps Lücken entfernen @msg that makes too many pieces (at most 100000): make the dashes longer das ergibt zu viele Teile (höchstens 100000): machen Sie die Striche länger @msg select paths, or segments, to divide wählen Sie Pfade oder Segmente zum Aufteilen aus +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Dokumentwerkzeuge + Save a Timestamped Copy Kopie mit Zeitstempel speichern +@msg there is no clock here hier gibt es keine Uhr +@msg there is no clock here: give `time` (Unix seconds) hier gibt es keine Uhr: geben Sie `time` an (Unix-Sekunden) +@msg the document has never been saved: give `folder` das Dokument wurde nie gespeichert: geben Sie `folder` an +@msg every numbered name for the copy is taken alle nummerierten Namen für die Kopie sind vergeben Marathi Marathi Gujarati Gujarati Bengali Bengalisch diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e602041396..686376775b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6007,6 +6007,13 @@ breakText Glyphs Γλύφοι Remove Gaps Αφαίρεση κενών @msg that makes too many pieces (at most 100000): make the dashes longer αυτό δίνει πάρα πολλά κομμάτια (το πολύ 100000): κάντε τις παύλες μεγαλύτερες @msg select paths, or segments, to divide επιλέξτε διαδρομές ή τμήματα για διαίρεση +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Εργαλεία εγγράφου + Save a Timestamped Copy Αποθήκευση αντιγράφου με ημερομηνία και ώρα +@msg there is no clock here δεν υπάρχει ρολόι εδώ +@msg there is no clock here: give `time` (Unix seconds) δεν υπάρχει ρολόι εδώ: δώστε `time` (δευτερόλεπτα Unix) +@msg the document has never been saved: give `folder` το έγγραφο δεν έχει αποθηκευτεί ποτέ: δώστε `folder` +@msg every numbered name for the copy is taken όλα τα αριθμημένα ονόματα για το αντίγραφο είναι πιασμένα Marathi Μαραθικά Gujarati Γκουγιαράτι Bengali Βεγγαλικά diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 8ce984b1d8..e99c15f651 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5997,6 +5997,13 @@ breakText Glyphs Glifos Remove Gaps Quitar separaciones @msg that makes too many pieces (at most 100000): make the dashes longer eso da demasiados trozos (como máximo 100000): alargue los guiones @msg select paths, or segments, to divide seleccione trazados o segmentos para dividir +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Herramientas de documento + Save a Timestamped Copy Guardar una copia con fecha y hora +@msg there is no clock here aquí no hay reloj +@msg there is no clock here: give `time` (Unix seconds) aquí no hay reloj: indique `time` (segundos Unix) +@msg the document has never been saved: give `folder` el documento nunca se ha guardado: indique `folder` +@msg every numbered name for the copy is taken todos los nombres numerados para la copia están ocupados Marathi Maratí Gujarati Guyaratí Bengali Bengalí diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 0380746599..7a4f5e6566 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6085,6 +6085,13 @@ breakText Glyphs Merkit Remove Gaps Poista välit @msg that makes too many pieces (at most 100000): make the dashes longer siitä tulee liian monta osaa (enintään 100000): pidennä viivoja @msg select paths, or segments, to divide valitse jaettavat polut tai segmentit +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Asiakirjatyökalut + Save a Timestamped Copy Tallenna kopio aikaleimalla +@msg there is no clock here täällä ei ole kelloa +@msg there is no clock here: give `time` (Unix seconds) täällä ei ole kelloa: anna `time` (Unix-sekunteina) +@msg the document has never been saved: give `folder` asiakirjaa ei ole koskaan tallennettu: anna `folder` +@msg every numbered name for the copy is taken kaikki kopion numeroidut nimet ovat varattuja Marathi Marathi Gujarati Gudžarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 135abca40c..81326659d7 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6052,6 +6052,13 @@ breakText Glyphs Glyphes Remove Gaps Supprimer les écarts @msg that makes too many pieces (at most 100000): make the dashes longer cela donne trop de morceaux (100000 au plus) : allongez les tirets @msg select paths, or segments, to divide sélectionnez des tracés ou des segments à diviser +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Outils de document + Save a Timestamped Copy Enregistrer une copie horodatée +@msg there is no clock here il n’y a pas d’horloge ici +@msg there is no clock here: give `time` (Unix seconds) il n’y a pas d’horloge ici : indiquez `time` (secondes Unix) +@msg the document has never been saved: give `folder` le document n’a jamais été enregistré : indiquez `folder` +@msg every numbered name for the copy is taken tous les noms numérotés pour la copie sont pris Marathi Marathi Gujarati Goudjarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9e64f5f39a..498ed78e7f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6041,6 +6041,13 @@ breakText Glyphs Glifák Remove Gaps Hézagok eltávolítása @msg that makes too many pieces (at most 100000): make the dashes longer ez túl sok darabot adna (legfeljebb 100000): hosszabbítsa meg a szaggatásokat @msg select paths, or segments, to divide jelöljön ki felosztandó útvonalakat vagy szakaszokat +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Dokumentumeszközök + Save a Timestamped Copy Másolat mentése időbélyeggel +@msg there is no clock here itt nincs óra +@msg there is no clock here: give `time` (Unix seconds) itt nincs óra: adja meg a `time` értéket (Unix-másodperc) +@msg the document has never been saved: give `folder` a dokumentum még nem volt mentve: adja meg a `folder` értéket +@msg every numbered name for the copy is taken a másolat összes számozott neve foglalt Marathi Maráthi Gujarati Gudzsaráti Bengali Bengáli diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 0ec84f9948..197b69455d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5952,6 +5952,13 @@ breakText Glyphs Glif Remove Gaps Hapus celah @msg that makes too many pieces (at most 100000): make the dashes longer itu menghasilkan terlalu banyak potongan (paling banyak 100000): perpanjang garisnya @msg select paths, or segments, to divide pilih jalur atau segmen yang akan dibagi +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Alat dokumen + Save a Timestamped Copy Simpan salinan bercap waktu +@msg there is no clock here tidak ada jam di sini +@msg there is no clock here: give `time` (Unix seconds) tidak ada jam di sini: berikan `time` (detik Unix) +@msg the document has never been saved: give `folder` dokumen belum pernah disimpan: berikan `folder` +@msg every numbered name for the copy is taken semua nama bernomor untuk salinan sudah dipakai Marathi Marathi Gujarati Gujarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 863fa08e8d..54d16513f7 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5674,6 +5674,13 @@ breakText Glyphs Glifi Remove Gaps Rimuovi le distanze @msg that makes too many pieces (at most 100000): make the dashes longer così si ottengono troppi pezzi (al massimo 100000): allunga i trattini @msg select paths, or segments, to divide seleziona tracciati o segmenti da dividere +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Strumenti documento + Save a Timestamped Copy Salva una copia con data e ora +@msg there is no clock here qui non c’è un orologio +@msg there is no clock here: give `time` (Unix seconds) qui non c’è un orologio: indica `time` (secondi Unix) +@msg the document has never been saved: give `folder` il documento non è mai stato salvato: indica `folder` +@msg every numbered name for the copy is taken tutti i nomi numerati per la copia sono già usati Marathi Marathi Gujarati Gujarati Bengali Bengalese diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c6e9c62fb9..f94365ca3f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5741,6 +5741,13 @@ breakText Glyphs 字形 Remove Gaps 間隔を削除 @msg that makes too many pieces (at most 100000): make the dashes longer 分割数が多すぎます(最大 100000):ダッシュを長くしてください @msg select paths, or segments, to divide 分割するパスまたはセグメントを選択してください +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools ドキュメントツール + Save a Timestamped Copy 日時付きのコピーを保存 +@msg there is no clock here ここには時計がありません +@msg there is no clock here: give `time` (Unix seconds) ここには時計がありません:`time`(Unix 秒)を指定してください +@msg the document has never been saved: give `folder` ドキュメントは一度も保存されていません:`folder` を指定してください +@msg every numbered name for the copy is taken コピー用の番号付きの名前はすべて使用されています Marathi マラーティー語 Gujarati グジャラート語 Bengali ベンガル語 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index c37dceb8ea..e948b44edd 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6044,6 +6044,13 @@ breakText Glyphs გლიფები Remove Gaps ღრეჩოების მოცილება @msg that makes too many pieces (at most 100000): make the dashes longer ეს ძალიან ბევრ ნაწილს იძლევა (მაქსიმუმ 100000): გაზარდეთ ტირეების სიგრძე @msg select paths, or segments, to divide აირჩიეთ დასაყოფი კონტურები ან სეგმენტები +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools დოკუმენტის ხელსაწყოები + Save a Timestamped Copy ასლის შენახვა თარიღითა და დროით +@msg there is no clock here აქ საათი არ არის +@msg there is no clock here: give `time` (Unix seconds) აქ საათი არ არის: მიუთითეთ `time` (Unix წამები) +@msg the document has never been saved: give `folder` დოკუმენტი არასოდეს შენახულა: მიუთითეთ `folder` +@msg every numbered name for the copy is taken ასლის ყველა დანომრილი სახელი დაკავებულია Marathi მარათჰი Gujarati გუჯარათი Bengali ბენგალური diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 0d03c7496e..e3b4f24016 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5637,6 +5637,13 @@ breakText Glyphs 글리프 Remove Gaps 간격 제거 @msg that makes too many pieces (at most 100000): make the dashes longer 조각이 너무 많아집니다(최대 100000개). 대시를 더 길게 하십시오 @msg select paths, or segments, to divide 나눌 패스나 세그먼트를 선택하십시오 +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools 문서 도구 + Save a Timestamped Copy 날짜와 시간이 붙은 사본 저장 +@msg there is no clock here 여기에는 시계가 없습니다 +@msg there is no clock here: give `time` (Unix seconds) 여기에는 시계가 없습니다. `time`(Unix 초)을 지정하십시오 +@msg the document has never been saved: give `folder` 문서를 저장한 적이 없습니다. `folder`를 지정하십시오 +@msg every numbered name for the copy is taken 사본에 쓸 번호 붙은 이름이 모두 사용 중입니다 Marathi 마라티어 Gujarati 구자라트어 Bengali 벵골어 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index acecce2dcb..e68a49a8e4 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5996,6 +5996,13 @@ breakText Glyphs Glyphs Remove Gaps Tussenruimten verwijderen @msg that makes too many pieces (at most 100000): make the dashes longer dat geeft te veel stukken (hoogstens 100000): maak de streepjes langer @msg select paths, or segments, to divide selecteer paden of segmenten om te verdelen +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Documentgereedschappen + Save a Timestamped Copy Een kopie met tijdstempel opslaan +@msg there is no clock here er is hier geen klok +@msg there is no clock here: give `time` (Unix seconds) er is hier geen klok: geef `time` op (Unix-seconden) +@msg the document has never been saved: give `folder` het document is nooit opgeslagen: geef `folder` op +@msg every numbered name for the copy is taken alle genummerde namen voor de kopie zijn bezet Marathi Marathi Gujarati Gujarati Bengali Bengaals diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 4b42f1e2d3..aa7f7b8780 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5910,6 +5910,13 @@ breakText Glyphs Glify Remove Gaps Usuń odstępy @msg that makes too many pieces (at most 100000): make the dashes longer to daje za dużo części (najwyżej 100000): wydłuż kreski @msg select paths, or segments, to divide zaznacz ścieżki lub segmenty do podzielenia +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Narzędzia dokumentu + Save a Timestamped Copy Zapisz kopię z datą i godziną +@msg there is no clock here brak tu zegara +@msg there is no clock here: give `time` (Unix seconds) brak tu zegara: podaj `time` (sekundy Unix) +@msg the document has never been saved: give `folder` dokument nigdy nie został zapisany: podaj `folder` +@msg every numbered name for the copy is taken wszystkie numerowane nazwy kopii są zajęte Marathi Marathi Gujarati Gudżarati Bengali Bengalski diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 86518877a3..3305725b5a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5974,6 +5974,13 @@ breakText Glyphs Glifos Remove Gaps Remover distâncias @msg that makes too many pieces (at most 100000): make the dashes longer isso gera peças demais (no máximo 100000): aumente os traços @msg select paths, or segments, to divide selecione demarcadores ou segmentos para dividir +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Ferramentas de Documento + Save a Timestamped Copy Salvar uma Cópia com Data e Hora +@msg there is no clock here não há relógio aqui +@msg there is no clock here: give `time` (Unix seconds) não há relógio aqui: informe `time` (segundos Unix) +@msg the document has never been saved: give `folder` o documento nunca foi salvo: informe `folder` +@msg every numbered name for the copy is taken todos os nomes numerados para a cópia estão em uso Marathi Marati Gujarati Guzerate Bengali Bengali diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 2b0b85161c..d272670889 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6032,6 +6032,13 @@ breakText Glyphs Глифы Remove Gaps Убрать зазоры @msg that makes too many pieces (at most 100000): make the dashes longer так получится слишком много частей (не более 100000): удлините штрихи @msg select paths, or segments, to divide выделите контуры или сегменты для разделения +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Инструменты документа + Save a Timestamped Copy Сохранить копию с датой и временем +@msg there is no clock here здесь нет часов +@msg there is no clock here: give `time` (Unix seconds) здесь нет часов: укажите `time` (секунды Unix) +@msg the document has never been saved: give `folder` документ ни разу не сохранялся: укажите `folder` +@msg every numbered name for the copy is taken все нумерованные имена для копии заняты Marathi Маратхи Gujarati Гуджарати Bengali Бенгальский diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e6ab913806..754962d2e8 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6107,6 +6107,13 @@ breakText Glyphs Glyfer Remove Gaps Ta bort mellanrum @msg that makes too many pieces (at most 100000): make the dashes longer det blir för många delar (högst 100000): gör strecken längre @msg select paths, or segments, to divide markera banor eller segment att dela upp +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Dokumentverktyg + Save a Timestamped Copy Spara en kopia med tidsstämpel +@msg there is no clock here det finns ingen klocka här +@msg there is no clock here: give `time` (Unix seconds) det finns ingen klocka här: ange `time` (Unix-sekunder) +@msg the document has never been saved: give `folder` dokumentet har aldrig sparats: ange `folder` +@msg every numbered name for the copy is taken alla numrerade namn för kopian är upptagna Marathi Marathi Gujarati Gujarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c4b924a012..8d682e7859 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6012,6 +6012,13 @@ breakText Glyphs Glifler Remove Gaps Boşlukları Kaldır @msg that makes too many pieces (at most 100000): make the dashes longer bu çok fazla parça oluşturur (en fazla 100000): tireleri uzatın @msg select paths, or segments, to divide bölünecek yolları veya bölümleri seçin +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Belge Araçları + Save a Timestamped Copy Zaman Damgalı Bir Kopya Kaydet +@msg there is no clock here burada saat yok +@msg there is no clock here: give `time` (Unix seconds) burada saat yok: `time` verin (Unix saniyesi) +@msg the document has never been saved: give `folder` belge hiç kaydedilmedi: `folder` verin +@msg every numbered name for the copy is taken kopya için tüm numaralı adlar kullanılıyor Marathi Marathi dili Gujarati Gücerat dili Bengali Bengalce diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d22468de3b..b5ac2dc5a7 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5654,6 +5654,13 @@ breakText Glyphs Гліфи Remove Gaps Прибрати проміжки @msg that makes too many pieces (at most 100000): make the dashes longer так вийде забагато частин (не більше 100000): подовжте штрихи @msg select paths, or segments, to divide виділіть контури або сегменти для розділення +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Інструменти документа + Save a Timestamped Copy Зберегти копію з датою і часом +@msg there is no clock here тут немає годинника +@msg there is no clock here: give `time` (Unix seconds) тут немає годинника: укажіть `time` (секунди Unix) +@msg the document has never been saved: give `folder` документ жодного разу не зберігався: укажіть `folder` +@msg every numbered name for the copy is taken усі нумеровані назви для копії зайняті Marathi Маратхі Gujarati Гуджараті Bengali Бенгальська diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f6b12617a0..49885e57d6 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5657,6 +5657,13 @@ breakText Glyphs Glyph Remove Gaps Gỡ các khoảng hở @msg that makes too many pieces (at most 100000): make the dashes longer như vậy tạo ra quá nhiều mảnh (tối đa 100000): hãy kéo dài nét @msg select paths, or segments, to divide chọn các đường dẫn hoặc đoạn để chia +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools Công cụ tài liệu + Save a Timestamped Copy Lưu bản sao có ngày giờ +@msg there is no clock here ở đây không có đồng hồ +@msg there is no clock here: give `time` (Unix seconds) ở đây không có đồng hồ: hãy cho `time` (giây Unix) +@msg the document has never been saved: give `folder` tài liệu chưa từng được lưu: hãy cho `folder` +@msg every numbered name for the copy is taken mọi tên đánh số cho bản sao đều đã dùng Marathi Tiếng Marathi Gujarati Tiếng Gujarati Bengali Tiếng Bengali diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 9381523e5e..2c767f6392 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5897,6 +5897,13 @@ breakText Glyphs 字形 Remove Gaps 移除间隙 @msg that makes too many pieces (at most 100000): make the dashes longer 这会产生过多片段(最多 100000 个):请加长短划线 @msg select paths, or segments, to divide 请选择要分割的路径或线段 +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools 文档工具 + Save a Timestamped Copy 保存带时间戳的副本 +@msg there is no clock here 此处没有时钟 +@msg there is no clock here: give `time` (Unix seconds) 此处没有时钟:请提供 `time`(Unix 秒) +@msg the document has never been saved: give `folder` 文档从未保存过:请提供 `folder` +@msg every numbered name for the copy is taken 副本的所有编号名称均已被占用 Marathi 马拉地语 Gujarati 古吉拉特语 Bengali 孟加拉语 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 0d6ae8b2b4..651a1293ce 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5694,6 +5694,13 @@ breakText Glyphs 字符 Remove Gaps 移除間隙 @msg that makes too many pieces (at most 100000): make the dashes longer 這會產生過多片段(最多 100000 個):請加長短破折號 @msg select paths, or segments, to divide 請選取要分割的路徑或線段 +# Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. + Document Tools 文件工具 + Save a Timestamped Copy 儲存附時間戳記的拷貝 +@msg there is no clock here 此處沒有時鐘 +@msg there is no clock here: give `time` (Unix seconds) 此處沒有時鐘:請提供 `time`(Unix 秒) +@msg the document has never been saved: give `folder` 文件從未儲存過:請提供 `folder` +@msg every numbered name for the copy is taken 拷貝的所有編號名稱均已被佔用 Marathi 馬拉地文 Gujarati 古吉拉特文 Bengali 孟加拉文 diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 5b83dc25b8..f85b25d704 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -530,6 +530,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result< crate::addons::pathtools::corner::COMMAND => crate::addons::pathtools::corner::open(app), crate::addons::pathtools::shared_edge::COMMAND => crate::addons::pathtools::shared_edge::open(app), crate::addons::arrange::ZOOM => crate::addons::arrange::zoom(app), + crate::addons::document::SAVE_COPY => crate::addons::document::save_copy(app, p), "tool.setOption" => app.session.set_tool_option_cmd(p), "effect.dialog" => crate::dialogs::open_effect_dialog(app, p), "ui.recolorDialog" => crate::dialogs::recolor::open(app, p), diff --git a/docs/mcp.md b/docs/mcp.md index 8c1d1f907a..ec441b7362 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6274,3 +6274,21 @@ command's parameters, with Preview; Set Size of Each's `__width` and `__height` {"name":"run_command","arguments":{"command":"addon.arrange.replace","params":{"fit":"proportional"}}} {"name":"run_command","arguments":{"command":"addon.arrange.size","params":{"width":72,"proportional":true}}} ``` + +## Document Tools add-on + +Document Tools is a built-in add-on for whole-document chores: its commands are `addon.document.*`, and in the desktop +app it lives in Object › Plug-ins › Document Tools. + +`addon.document.saveTimestampedCopy {folder?, format?, time?}` writes a copy of the document named +`<name>_YYYY-MM-DD_HH-MM.<ext>`, with `-2`, `-3`… added when that name is taken. The date and time are `time` (Unix +seconds; now by default) in UTC. The copy goes in the document's own folder, or in `folder`, which a document never +saved needs (the desktop app asks for one with the folder picker); `format` is a save format (`vectorcraft`, `pdf`, +`svg`, `svgz`, `ai`, `eps`; the document's own by default). It is written as `file.saveCopy` writes, inside the +automation roots in force: the document keeps its path, title and modified state, and no undo step is made. The +command is off where there is no clock (the web). → `{path, format, bytes, warnings}` + +```json +{"name":"run_command","arguments":{"command":"addon.document.saveTimestampedCopy","params":{}}} +{"name":"run_command","arguments":{"command":"addon.document.saveTimestampedCopy","params":{"folder":"/Users/me/Versions","format":"pdf"}}} +``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2f2a226425..99e2d7b2b6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Path Precision Tools add-on: Divide into Dashes, #4950; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Document Tools add-on: Save a Timestamped Copy, #4926; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -1407,10 +1407,15 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Divide into Dashes… cuts the selected paths into separate open paths along the curve (arc length, not straight distance): each `dash` long (0.01 to 1000000 pt, 10 by default) with `gap` between them (0 by default: the pieces touch); the gap pieces are left out unless Remove Gaps is off. With direct-selected segments (or anchors) only those runs are divided, the pattern running on across segments that follow one another, and the rest of such a path stays as pieces of its own. Fit to Corners and Ends gives every run between corners and ends a whole number of dashes, all stretched or squeezed alike so it starts and ends on a dash (a closed path without corners holds whole periods); otherwise the lengths are exact and each run's last piece is what is left. Every piece keeps the path's appearance and is selected; one undo step; at most 100000 pieces (more is refused). The dialog takes lengths in any unit and previews on the canvas. Tests: `dashes::tests` in `vectorcraft-pathops` (exact and fitted lengths, curves measured along them, picked segments on open and closed paths, the piece cap and bad patterns), `divide_into_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (gaps removed or kept, fitted lengths, the stroke kept, one undo step, selected segments only, bad params and too many pieces refused), `divide_into_dashes_opens_its_dialog_previews_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. +## Document Tools add-on: Save a Timestamped Copy (2026-11-01) + +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Document Tools › Save a Timestamped Copy writes a copy of the document named `<name>_YYYY-MM-DD_HH-MM.<ext>` (the date and time in UTC, through chrono; `-2`, `-3`… added when that name is taken) next to the document, or into a folder picked (the folder picker) when it was never saved, in the document's own format or another save format. It writes through File › Save a Copy's save, so the document keeps its path, title and modified state, no undo step is made, and the write stays inside the automation roots in force. It is off on the web, which has no clock. Tests: `cmd::addons::document::tests` in `vectorcraft-engine` (the name and place, numbered names, the document unchanged and its content in the copy, an unsaved document needing a folder, other formats, bad params refused, automation roots), `addons::document::tests` in `vectorcraft-ui-egui` (the submenu, beside the document, the folder picked or cancelled) and `command_sweep`. Commands: `docs/mcp.md` › Document Tools add-on. + ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): Save a Timestamped Copy (#4926); evidence added; scores unchanged. | | 2026-11-01 | minor | Path Precision Tools add-on (a VectorCraft addition): Divide into Dashes (#4950); evidence added; scores unchanged. | | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Group Overlapping Objects (#4928); evidence added; scores unchanged. | | 2026-11-01 | minor | Type core: a Language per character (Character panel › Language, `text.setFormat` / `text.setRangeStyle {language}`, character styles), new type in the document's language; text is shaped in its language so fonts use their language forms (OpenType `locl`: Turkish `fi`, #4940, #4946); Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu in the language list (#4943); scores unchanged | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 6c31deb0a5..51578bb921 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Path Precision Tools add-on: Divide into Dashes, #4950) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Document Tools add-on: Save a Timestamped Copy, #4926) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -330,6 +330,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | +| Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `<name>_YYYY-MM-DD_HH-MM.<ext>` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its seven tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.rs` and their tests; not a feature of the reference app, so it is not scored | @@ -383,6 +384,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): Save a Timestamped Copy (#4926); scores and estimates unchanged | | 2026-11-01 | minor | Path Precision Tools add-on (a VectorCraft addition): Divide into Dashes (#4950); scores and estimates unchanged | | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Group Overlapping Objects (#4928); scores and estimates unchanged | | 2026-11-01 | minor | Character panel › Language: the selected characters' language, from Document Setup's list, which gains Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu (#4946, #4943); the Digits menu's numeral names keep their own translations; scores unchanged | From 68391bdde4ffbd06feaa0f8d98740203bef6cf19 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 02:42:20 +0700 Subject: [PATCH 172/260] Fix #4926: New Symbols from Layers --- ROADMAP.md | 4 +- crates/engine/src/cmd/addons/document.rs | 119 ++++++++++++++++-- .../engine/src/cmd/addons/document/tests.rs | 102 ++++++++++++++- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/symbols.rs | 34 +++-- crates/engine/tests/command_sweep.rs | 3 + crates/ui-egui/src/addons/document.rs | 15 ++- crates/ui-egui/src/addons/document/tests.rs | 21 ++++ crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/vi.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + docs/mcp.md | 12 ++ docs/target-app-parity.md | 7 +- docs/ui-parity.md | 4 +- 37 files changed, 393 insertions(+), 34 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index d61922cbe9..0206168ac1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -9,7 +9,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Document Tools add-on's Save a Timestamped Copy; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Document Tools add-on's New Symbols from Layers; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<name>_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. @@ -207,6 +208,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Progress log row for the Document Tools add-on's New Symbols from Layers (#4927); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Document Tools add-on's Save a Timestamped Copy (#4926); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for Divide into Dashes (Path Precision Tools add-on, #4950); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for Group Overlapping Objects (Arrange Tools add-on, #4928); headline numbers unchanged. | diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index b4911e4759..38aa8fab3c 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -1,29 +1,45 @@ //! Document Tools (`addon.document.*`), a built-in add-on: Save a Timestamped Copy writes a copy of -//! the document named with the date and time through File › Save a Copy's save. Its submenu -//! (Object › Plug-ins › Document Tools) is the UI's. +//! the document named with the date and time through File › Save a Copy's save; New Symbols from +//! Layers makes a symbol of each layer's art as New Symbol does. Its submenu (Object › Plug-ins › +//! Document Tools) is the UI's. #[cfg(test)] mod tests; -use serde_json::{Value, json}; +use std::sync::Arc; +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolRegistration}; + +use super::super::brushsym::{instance_in_place, normalize, place_xf, store_symbol}; use super::super::fileio::{self, SaveMode}; -use super::super::{CommandSpec, bad, clock_date, cmd, date_param, has_doc, str_param}; +use super::super::{CommandSpec, bad, checked_ids_param, clock_date, cmd, date_param, has_doc, str_param, switch_or}; use crate::{Result, Session}; /// The most numbers (`-2`, `-3`…) tried after a timestamped name that is taken. const MAX_NUMBER: u32 = 999; pub fn specs() -> Vec<CommandSpec> { - vec![cmd!( - "addon.document.saveTimestampedCopy", - "Save a Timestamped Copy", - ["Object", "Plug-ins", "Document Tools"], - None, - "{folder? (default: the document's own folder; needed for a document never saved), format?: vectorcraft|pdf|svg|svgz|ai|eps (default: the document's own, else vectorcraft), time?: Unix seconds (default: now)} write a copy of the document named <name>_YYYY-MM-DD_HH-MM.<ext> (the date and time in UTC; -2, -3… added when that name is taken) as File › Save a Copy writes it: the document keeps its path, title and modified state, and no undo step is made. Off where there is no clock (the web) → {path, format, bytes, warnings}", - has_clock, - save_timestamped_copy - )] + vec![ + cmd!( + "addon.document.saveTimestampedCopy", + "Save a Timestamped Copy", + ["Object", "Plug-ins", "Document Tools"], + None, + "{folder? (default: the document's own folder; needed for a document never saved), format?: vectorcraft|pdf|svg|svgz|ai|eps (default: the document's own, else vectorcraft), time?: Unix seconds (default: now)} write a copy of the document named <name>_YYYY-MM-DD_HH-MM.<ext> (the date and time in UTC; -2, -3… added when that name is taken) as File › Save a Copy writes it: the document keeps its path, title and modified state, and no undo step is made. Off where there is no clock (the web) → {path, format, bytes, warnings}", + has_clock, + save_timestamped_copy + ), + cmd!( + "addon.document.symbolsFromLayers", + "New Symbols from Layers", + ["Object", "Plug-ins", "Document Tools"], + None, + "{layers?: [layer id…] (top-level layers; default: those highlighted in the Layers panel when two or more are, else every one), replace?: bool (false: the art stays; true: each layer's art is replaced by an instance of its symbol in the same place)} make one symbol of each layer's art as symbol.new makes one (registration in the centre), named after the layer (with a number added when a symbol has that name), as one undo step. Layers with no art are skipped, and with replace so are locked layers; with replace the instances are selected → {symbols: [name…], ids: [instance id…] (with replace), skipped: [{layer, name, reason: \"empty\"|\"locked\"}…]}", + has_doc, + symbols_from_layers + ), + ] } /// A document is open and the time can be told. @@ -71,3 +87,80 @@ fn save_timestamped_copy(s: &mut Session, p: &Value) -> Result<Value> { .ok_or_else(|| bad(C, "every numbered name for the copy is taken"))?; fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id })) } + +/// `n` with each layer in it, and itself, made a group of the same art and clipping (a symbol holds +/// no layers). +fn without_layers(n: &Node) -> Node { + let mut n = n.clone(); + if let NodeKind::Layer { children, clip, .. } = &n.kind { + n.kind = NodeKind::Group { children: children.clone(), clip: *clip }; + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut().filter(|c| matches!(c.kind, NodeKind::Layer { .. })) { + *c = Arc::new(without_layers(c)); + } + } + n +} + +fn symbols_from_layers(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "addon.document.symbolsFromLayers"; + let replace = switch_or(p, "replace", false, C)?; + let st = s.doc()?; + let d = &st.doc; + let layers: Vec<NodeId> = match p.get("layers").filter(|v| !v.is_null()) { + // The layers highlighted in the Layers panel when two or more are (one is mostly just the + // current layer), else every one. + None => { + let rows = st.highlighted_rows(); + let picked: Vec<NodeId> = d.layers.iter().map(|l| l.id).filter(|id| rows.contains(id)).collect(); + if picked.len() > 1 { picked } else { d.layers.iter().map(|l| l.id).collect() } + } + Some(_) => { + let ids = checked_ids_param(s, p, "layers", C)?; + if let Some(NodeId(id)) = ids.iter().find(|id| !d.layers.iter().any(|l| l.id == **id)) { + return Err(bad(C, format!("{id} is no top-level layer"))); + } + d.layers.iter().map(|l| l.id).filter(|id| ids.contains(id)).collect() + } + }; + // Each layer with art: its id and name, the art's roots, and the art ready for a symbol. + let (mut made, mut skipped) = (vec![], vec![]); + for layer in layers.iter().filter_map(|id| d.layers.iter().find(|l| l.id == *id)) { + let name = layer.display_name(); + let roots: Vec<NodeId> = layer.children().map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default(); + let art = match layer.children().map(Vec::as_slice).unwrap_or_default() { + [] => None, + [one] => Some(without_layers(one)), + many => Some(without_layers(&Node::group(NodeId(0), many.to_vec()))), + }; + let reason = if replace && layer.locked { Some("locked") } else { None }; + let ready = art.and_then(|mut art| { + crate::cmd::threads::keep_shown_text(d, &mut art); + normalize(art).ok() + }); + match (reason, ready) { + (None, Some(ready)) => made.push((name, roots, ready)), + (reason, _) => skipped.push(json!({ "layer": layer.id.0, "name": name, "reason": reason.unwrap_or("empty") })), + } + } + if made.is_empty() { + return Ok(json!({ "symbols": [], "ids": [], "skipped": skipped })); + } + let (names, ids) = s.edit("New Symbols from Layers", |d, sel| { + let (mut names, mut ids) = (vec![], vec![]); + for (name, roots, (art, size, center)) in &made { + let name = d.unique_symbol_name(name); + store_symbol(d, art, &name, *size); + if replace { + ids.push(instance_in_place(d, roots, &name, place_xf(*center, *size, SymbolRegistration::CENTER))?); + } + names.push(name); + } + if replace { + sel.set(ids.iter().copied()); + } + Ok((names, ids)) + })?; + Ok(json!({ "symbols": names, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "skipped": skipped })) +} diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index 362ea1a43b..a67fcd5ae0 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -1,9 +1,10 @@ -//! Document Tools' commands: the copy's name and place, the document left as it was, and bad -//! params refused. +//! Document Tools' commands: the timestamped copy's name and place with the document left as it +//! was, symbols made of layers, and bad params refused. use std::path::{Path, PathBuf}; use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; use crate::Session; @@ -96,3 +97,100 @@ fn bad_params_are_refused_and_writes_stay_inside_the_automation_roots() { fn enabled_without_document() -> bool { Session::new().commands().into_iter().find(|c| c.id == "addon.document.saveTimestampedCopy").unwrap().enabled } + +fn layer_ids(s: &Session) -> Vec<u64> { + s.doc().unwrap().doc.layers.iter().map(|l| l.id.0).collect() +} + +fn symbol_names(s: &Session) -> Vec<String> { + s.doc().unwrap().doc.symbols.iter().map(|x| x.name.clone()).collect() +} + +/// A document of three layers: `Layer 1` with two rectangles, an empty one, and `Icons` with one +/// ellipse. +fn layered() -> Session { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("layer.new", &json!({})).unwrap(); + s.execute("layer.new", &json!({"name": "Icons"})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 0, "y": 100, "width": 40, "height": 20})).unwrap(); + s +} + +#[test] +fn a_symbol_is_made_of_each_layer_and_empty_layers_are_reported() { + let mut s = layered(); + let before = symbol_names(&s).len(); + let n = s.doc().unwrap().history.undo.len(); + let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), n + 1, "one undo step"); + let names: Vec<String> = serde_json::from_value(r["symbols"].clone()).unwrap(); + assert_eq!(names.len(), 2, "{r}"); + assert!(names.contains(&"Icons".to_string())); + assert_eq!(symbol_names(&s).len(), before + 2); + assert_eq!(r["skipped"].as_array().unwrap().len(), 1, "the empty layer: {r}"); + assert_eq!(r["skipped"][0]["reason"], json!("empty")); + assert_eq!(r["ids"], json!([]), "without replace the art stays"); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); + // Again: the names are taken, so they get numbers. + let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap(); + assert!(r["symbols"].as_array().unwrap().contains(&json!("Icons 2")), "{r}"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(symbol_names(&s).len(), before); +} + +#[test] +fn replace_puts_an_instance_where_the_layers_art_was() { + let mut s = layered(); + let first = layer_ids(&s)[0]; + let bounds = |s: &Session, id: NodeId| s.doc().unwrap().doc.bounds_of(&[id], false).unwrap(); + let layer = NodeId(first); + let art = bounds(&s, layer); + let r = s.execute("addon.document.symbolsFromLayers", &json!({"layers": [first], "replace": true})).unwrap(); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1); + let inst = NodeId(ids[0].as_u64().unwrap()); + let st = s.doc().unwrap(); + let kids = st.doc.layers[0].children().unwrap(); + assert_eq!(kids.len(), 1); + assert!(matches!(&kids[0].kind, NodeKind::SymbolInstance { .. })); + assert_eq!(st.selection.objects, [inst]); + let now = bounds(&s, layer); + assert!((now.x0 - art.x0).abs() < 1e-6 && (now.y1 - art.y1).abs() < 1e-6 && (now.width() - art.width()).abs() < 1e-6, "{art:?} {now:?}"); + assert_eq!(s.doc().unwrap().doc.layers.len(), 3, "the other layers untouched"); +} + +#[test] +fn locked_layers_keep_their_art_and_bad_layers_are_refused() { + let mut s = layered(); + let ids = layer_ids(&s); + s.execute("layer.setProps", &json!({"id": ids[2], "locked": true})).unwrap(); + let r = s.execute("addon.document.symbolsFromLayers", &json!({"replace": true})).unwrap(); + let skipped: Vec<&str> = r["skipped"].as_array().unwrap().iter().map(|k| k["reason"].as_str().unwrap()).collect(); + assert_eq!(skipped, ["empty", "locked"]); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let rect = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0; + for p in [json!({"layers": [rect]}), json!({"layers": [u64::MAX]}), json!({"layers": "all"}), json!({"layers": [-1]}), json!({"replace": "yes"})] + { + assert!(s.execute("addon.document.symbolsFromLayers", &p).is_err(), "{p}"); + } + assert!(*s.doc().unwrap().doc == *before.0 && s.doc().unwrap().history.undo.len() == before.1); + // Only an empty layer: nothing made, no step. + let r = s.execute("addon.document.symbolsFromLayers", &json!({"layers": [ids[1]]})).unwrap(); + assert_eq!((r["symbols"].clone(), s.doc().unwrap().history.undo.len()), (json!([]), before.1)); +} + +#[test] +fn the_layers_highlighted_in_the_layers_panel_are_the_default() { + let mut s = layered(); + let ids = layer_ids(&s); + // One highlighted row is just the current layer: every layer. + s.execute("layer.setCurrent", &json!({"id": ids[0]})).unwrap(); + let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap(); + assert_eq!(r["symbols"].as_array().unwrap().len(), 2); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("layer.highlight", &json!({"ids": [ids[1], ids[2]]})).unwrap(); + let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap(); + assert_eq!((r["symbols"].clone(), r["skipped"].as_array().unwrap().len()), (json!(["Icons"]), 1)); +} diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 3b9a476d42..2124667ced 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -32,7 +32,7 @@ use brushes::{ brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_remove, brush_selection_art, brush_set_current, brush_unused, expand_brush, }; -pub(crate) use symbols::{natural_size, normalize, place_xf, set_natural_size}; +pub(crate) use symbols::{instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol}; use symbols::{ symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_edit, symbol_list, symbol_new, symbol_options, symbol_place, symbol_replace, symbol_select_instances, symbol_set_current, symbol_spray, symbol_update, diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 8e8ba163ee..d1ce429a04 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -134,6 +134,25 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> { Ok(json!({ "symbols": list, "current": current_symbol(d).or_else(|| symbol_names(d).into_iter().next()) })) } +/// Store `art` ([`normalize`]d, of natural size `size`) as symbol `name`, which becomes the +/// current symbol. +pub(crate) fn store_symbol(d: &mut Document, art: &Node, name: &str, size: (f64, f64)) { + let art = d.reid(art); + d.symbols.push(Symbol { name: name.into(), art: Arc::new(art) }); + set_natural_size(d, name, Some(size)); + d.unknown.insert(CURRENT_SYMBOL.into(), json!(name)); +} + +/// Replace the root nodes `ids` with one instance of symbol `name` (already stored) placed by +/// `xf`. Frames of threaded text among them leave their threads with the text they show. Returns +/// the instance's id. +pub(crate) fn instance_in_place(d: &mut Document, ids: &[NodeId], name: &str, xf: Affine) -> Result<NodeId> { + let threaded = crate::cmd::threads::frames(d); + let id = replace_with_instance(d, ids, name, xf)?; + crate::cmd::threads::leave_threads(d, &threaded); + Ok(id) +} + /// Replace the root nodes `ids` with one instance of `name` (art already stored). Returns the id. fn replace_with_instance(d: &mut Document, ids: &[NodeId], name: &str, xf: Affine) -> Result<NodeId> { let top = *ids.last().ok_or_else(|| EngineError::Other("nothing selected".into()))?; @@ -163,17 +182,11 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> { // Keep the art where it was: the geometric centre stays at `c`, whatever the registration is. let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg); let id = s.edit("New Symbol", |d, sel| { - let art = d.reid(&art); - d.symbols.push(Symbol { name: name.clone(), art: Arc::new(art) }); - set_natural_size(d, &name, Some(size)); + store_symbol(d, &art, &name, size); d.set_symbol_registration(&name, reg); d.set_symbol_export_type(&name, export); d.set_symbol_nine_slice(&name, nine); - d.unknown.insert(CURRENT_SYMBOL.into(), json!(name)); - let threaded = crate::cmd::threads::frames(d); - let id = replace_with_instance(d, &ids, &name, place)?; - // Frames of threaded text in the symbol leave their threads with the text they show. - crate::cmd::threads::leave_threads(d, &threaded); + let id = instance_in_place(d, &ids, &name, place)?; sel.set([id]); Ok(id) })?; @@ -370,10 +383,7 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> { } } let reg = d.symbol_registration(&name); - let threaded = crate::cmd::threads::frames(d); - let id = replace_with_instance(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?; - // Frames of threaded text in the symbol leave their threads with the text they show. - crate::cmd::threads::leave_threads(d, &threaded); + let id = instance_in_place(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?; sel.set([id]); Ok(id) })?; diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index c53f51b2ac..ae69993f7a 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -595,6 +595,9 @@ fn structured_junk() { // Refused before anything is written: no format of that name, a time that is no time. ("addon.document.saveTimestampedCopy", json!({"format": "png", "folder": 7})), ("addon.document.saveTimestampedCopy", json!({"format": "svg", "time": [1e308], "folder": null})), + ("addon.document.symbolsFromLayers", json!({"layers": "x", "replace": 3})), + ("addon.document.symbolsFromLayers", json!({"layers": [1e308, -1, null, u64::MAX], "replace": true})), + ("addon.document.symbolsFromLayers", json!({"layers": [], "replace": true})), // Smart Pen add-on. ("addon.pen.append", json!({"id": 2, "x": 1e308, "y": 0, "in": [1e308, -1e308]})), ("addon.pen.append", json!({"id": 2, "subpath": u64::MAX, "x": 0, "y": 0, "segment": "curved"})), diff --git a/crates/ui-egui/src/addons/document.rs b/crates/ui-egui/src/addons/document.rs index a948749692..47ea442f46 100644 --- a/crates/ui-egui/src/addons/document.rs +++ b/crates/ui-egui/src/addons/document.rs @@ -1,5 +1,7 @@ -//! Document Tools in the interface: its submenu (Object › Plug-ins › Document Tools). Save a -//! Timestamped Copy of a document never saved asks for the folder to put it in ([`save_copy`]). +//! Document Tools in the interface: its submenu (Object › Plug-ins › Document Tools), which runs +//! Save a Timestamped Copy, New Symbols from Layers and Convert Layers to Symbols (the same, with +//! each layer's art replaced by an instance). Save a Timestamped Copy of a document never saved +//! asks for the folder to put it in ([`save_copy`]). use serde_json::{Value, json}; @@ -8,10 +10,17 @@ use crate::menus::Item; /// Save a Timestamped Copy. pub const SAVE_COPY: &str = "addon.document.saveTimestampedCopy"; +/// New Symbols from Layers (Convert Layers to Symbols: with their art replaced by instances). +const SYMBOLS: &str = "addon.document.symbolsFromLayers"; /// Object › Plug-ins › Document Tools. pub fn menu() -> Vec<Item> { - vec![Item::Cmd("Save a Timestamped Copy", SAVE_COPY, json!({}))] + vec![ + Item::Cmd("Save a Timestamped Copy", SAVE_COPY, json!({})), + Item::Sep, + Item::Cmd("New Symbols from Layers", SYMBOLS, json!({})), + Item::Cmd("Convert Layers to Symbols", SYMBOLS, json!({ "replace": true })), + ] } /// Save a Timestamped Copy with params `p`: a document never saved, given no `folder`, goes in the diff --git a/crates/ui-egui/src/addons/document/tests.rs b/crates/ui-egui/src/addons/document/tests.rs index cf43d59e1c..5221c84147 100644 --- a/crates/ui-egui/src/addons/document/tests.rs +++ b/crates/ui-egui/src/addons/document/tests.rs @@ -61,3 +61,24 @@ fn an_unsaved_document_asks_for_a_folder() { assert_eq!(files(&dir).len(), 1); let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn new_symbols_from_layers_and_convert_layers_to_symbols() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 30})).unwrap(); + app.run("layer.new", json!({"name": "Badges"})).unwrap(); + app.run("shape.ellipse", json!({"x": 100, "y": 10, "width": 40, "height": 40})).unwrap(); + let symbols = |app: &VectorcraftApp| app.session.doc().unwrap().doc.symbols.iter().map(|s| s.name.clone()).collect::<Vec<_>>(); + let before = symbols(&app).len(); + click(&mut app, "New Symbols from Layers"); + assert_eq!(symbols(&app).len(), before + 2); + assert!(symbols(&app).contains(&"Badges".to_string())); + app.run("edit.undo", json!({})).unwrap(); + click(&mut app, "Convert Layers to Symbols"); + let doc = &app.session.doc().unwrap().doc; + assert!( + doc.layers + .iter() + .all(|l| matches!(l.children().unwrap()[..], [ref one] if matches!(one.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. }))) + ); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 519247e09c..177f87058c 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5945,6 +5945,10 @@ breakText Glyphs Глифи @msg there is no clock here: give `time` (Unix seconds) тук няма часовник: задайте `time` (Unix секунди) @msg the document has never been saved: give `folder` документът никога не е запазван: задайте `folder` @msg every numbered name for the copy is taken всички номерирани имена за копието са заети +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Нови символи от слоевете + Convert Layers to Symbols Превръщане на слоевете в символи +@msg {id} is no top-level layer {id} не е слой от най-горно ниво Marathi Маратхи Gujarati Гуджарати Bengali Бенгалски diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 5910e59045..1cdf807f02 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5979,6 +5979,10 @@ shape Open Otvoren @msg there is no clock here: give `time` (Unix seconds) ovdje nema sata: navedite `time` (Unix sekunde) @msg the document has never been saved: give `folder` dokument nikad nije sačuvan: navedite `folder` @msg every numbered name for the copy is taken sva numerisana imena za kopiju su zauzeta +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Novi simboli iz slojeva + Convert Layers to Symbols Pretvori slojeve u simbole +@msg {id} is no top-level layer {id} nije sloj najvišeg nivoa Marathi Marathi Gujarati Gudžarati Bengali Bengalski diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 6c2ccc29a0..c2c363ebd2 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6052,6 +6052,10 @@ breakText Glyphs Glifs @msg there is no clock here: give `time` (Unix seconds) aquí no hi ha rellotge: indiqueu `time` (segons Unix) @msg the document has never been saved: give `folder` el document no s’ha desat mai: indiqueu `folder` @msg every numbered name for the copy is taken tots els noms numerats per a la còpia estan ocupats +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Símbols nous a partir de les capes + Convert Layers to Symbols Converteix les capes en símbols +@msg {id} is no top-level layer {id} no és una capa de primer nivell Marathi Marathi Gujarati Gujarati Bengali Bengalí diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index cc0fbfa1bd..42f1c3977c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6062,6 +6062,10 @@ breakText Glyphs Glyfy @msg there is no clock here: give `time` (Unix seconds) nejsou k dispozici hodiny: zadejte `time` (sekundy Unix) @msg the document has never been saved: give `folder` dokument nebyl nikdy uložen: zadejte `folder` @msg every numbered name for the copy is taken všechny číslované názvy kopie jsou obsazené +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Nové symboly z vrstev + Convert Layers to Symbols Převést vrstvy na symboly +@msg {id} is no top-level layer {id} není vrstva nejvyšší úrovně Marathi Maráthština Gujarati Gudžarátština Bengali Bengálština diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index e77983fcb8..5b64d2758f 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5959,6 +5959,10 @@ breakText Glyphs Glyffer @msg there is no clock here: give `time` (Unix seconds) der er intet ur her: angiv `time` (Unix-sekunder) @msg the document has never been saved: give `folder` dokumentet er aldrig blevet gemt: angiv `folder` @msg every numbered name for the copy is taken alle nummererede navne til kopien er optaget +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Nye symboler fra lag + Convert Layers to Symbols Konvertér lag til symboler +@msg {id} is no top-level layer {id} er ikke et lag på øverste niveau Marathi Marathi Gujarati Gujarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 5a3bf8ef52..32f8ee3f85 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5647,6 +5647,10 @@ breakText Glyphs Glyphen @msg there is no clock here: give `time` (Unix seconds) hier gibt es keine Uhr: geben Sie `time` an (Unix-Sekunden) @msg the document has never been saved: give `folder` das Dokument wurde nie gespeichert: geben Sie `folder` an @msg every numbered name for the copy is taken alle nummerierten Namen für die Kopie sind vergeben +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Neue Symbole aus Ebenen + Convert Layers to Symbols Ebenen in Symbole umwandeln +@msg {id} is no top-level layer {id} ist keine Ebene der obersten Stufe Marathi Marathi Gujarati Gujarati Bengali Bengalisch diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 686376775b..2ce1d6b853 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6014,6 +6014,10 @@ breakText Glyphs Γλύφοι @msg there is no clock here: give `time` (Unix seconds) δεν υπάρχει ρολόι εδώ: δώστε `time` (δευτερόλεπτα Unix) @msg the document has never been saved: give `folder` το έγγραφο δεν έχει αποθηκευτεί ποτέ: δώστε `folder` @msg every numbered name for the copy is taken όλα τα αριθμημένα ονόματα για το αντίγραφο είναι πιασμένα +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Νέα σύμβολα από επίπεδα + Convert Layers to Symbols Μετατροπή επιπέδων σε σύμβολα +@msg {id} is no top-level layer το {id} δεν είναι επίπεδο ανώτατου επιπέδου Marathi Μαραθικά Gujarati Γκουγιαράτι Bengali Βεγγαλικά diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index e99c15f651..277af453f6 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6004,6 +6004,10 @@ breakText Glyphs Glifos @msg there is no clock here: give `time` (Unix seconds) aquí no hay reloj: indique `time` (segundos Unix) @msg the document has never been saved: give `folder` el documento nunca se ha guardado: indique `folder` @msg every numbered name for the copy is taken todos los nombres numerados para la copia están ocupados +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Nuevos símbolos a partir de capas + Convert Layers to Symbols Convertir capas en símbolos +@msg {id} is no top-level layer {id} no es una capa de nivel superior Marathi Maratí Gujarati Guyaratí Bengali Bengalí diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 7a4f5e6566..5ff14b7d9f 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6092,6 +6092,10 @@ breakText Glyphs Merkit @msg there is no clock here: give `time` (Unix seconds) täällä ei ole kelloa: anna `time` (Unix-sekunteina) @msg the document has never been saved: give `folder` asiakirjaa ei ole koskaan tallennettu: anna `folder` @msg every numbered name for the copy is taken kaikki kopion numeroidut nimet ovat varattuja +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Uudet symbolit tasoista + Convert Layers to Symbols Muunna tasot symboleiksi +@msg {id} is no top-level layer {id} ei ole ylimmän tason taso Marathi Marathi Gujarati Gudžarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 81326659d7..76717dd003 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6059,6 +6059,10 @@ breakText Glyphs Glyphes @msg there is no clock here: give `time` (Unix seconds) il n’y a pas d’horloge ici : indiquez `time` (secondes Unix) @msg the document has never been saved: give `folder` le document n’a jamais été enregistré : indiquez `folder` @msg every numbered name for the copy is taken tous les noms numérotés pour la copie sont pris +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Nouveaux symboles à partir des calques + Convert Layers to Symbols Convertir les calques en symboles +@msg {id} is no top-level layer {id} n’est pas un calque de premier niveau Marathi Marathi Gujarati Goudjarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 498ed78e7f..c391405c46 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6048,6 +6048,10 @@ breakText Glyphs Glifák @msg there is no clock here: give `time` (Unix seconds) itt nincs óra: adja meg a `time` értéket (Unix-másodperc) @msg the document has never been saved: give `folder` a dokumentum még nem volt mentve: adja meg a `folder` értéket @msg every numbered name for the copy is taken a másolat összes számozott neve foglalt +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Új szimbólumok rétegekből + Convert Layers to Symbols Rétegek átalakítása szimbólumokká +@msg {id} is no top-level layer a(z) {id} nem legfelső szintű réteg Marathi Maráthi Gujarati Gudzsaráti Bengali Bengáli diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 197b69455d..a49fcb3e35 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5959,6 +5959,10 @@ breakText Glyphs Glif @msg there is no clock here: give `time` (Unix seconds) tidak ada jam di sini: berikan `time` (detik Unix) @msg the document has never been saved: give `folder` dokumen belum pernah disimpan: berikan `folder` @msg every numbered name for the copy is taken semua nama bernomor untuk salinan sudah dipakai +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Simbol baru dari lapisan + Convert Layers to Symbols Ubah lapisan menjadi simbol +@msg {id} is no top-level layer {id} bukan lapisan tingkat atas Marathi Marathi Gujarati Gujarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 54d16513f7..0816ef0c7c 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5681,6 +5681,10 @@ breakText Glyphs Glifi @msg there is no clock here: give `time` (Unix seconds) qui non c’è un orologio: indica `time` (secondi Unix) @msg the document has never been saved: give `folder` il documento non è mai stato salvato: indica `folder` @msg every numbered name for the copy is taken tutti i nomi numerati per la copia sono già usati +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Nuovi simboli dai livelli + Convert Layers to Symbols Converti livelli in simboli +@msg {id} is no top-level layer {id} non è un livello di primo livello Marathi Marathi Gujarati Gujarati Bengali Bengalese diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index f94365ca3f..795b48730d 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5748,6 +5748,10 @@ breakText Glyphs 字形 @msg there is no clock here: give `time` (Unix seconds) ここには時計がありません:`time`(Unix 秒)を指定してください @msg the document has never been saved: give `folder` ドキュメントは一度も保存されていません:`folder` を指定してください @msg every numbered name for the copy is taken コピー用の番号付きの名前はすべて使用されています +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers レイヤーから新規シンボル + Convert Layers to Symbols レイヤーをシンボルに変換 +@msg {id} is no top-level layer {id} は最上位のレイヤーではありません Marathi マラーティー語 Gujarati グジャラート語 Bengali ベンガル語 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index e948b44edd..2eec1b66f9 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6051,6 +6051,10 @@ breakText Glyphs გლიფები @msg there is no clock here: give `time` (Unix seconds) აქ საათი არ არის: მიუთითეთ `time` (Unix წამები) @msg the document has never been saved: give `folder` დოკუმენტი არასოდეს შენახულა: მიუთითეთ `folder` @msg every numbered name for the copy is taken ასლის ყველა დანომრილი სახელი დაკავებულია +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers ახალი სიმბოლოები შრეებიდან + Convert Layers to Symbols შრეების სიმბოლოებად გარდაქმნა +@msg {id} is no top-level layer {id} არ არის ზედა დონის შრე Marathi მარათჰი Gujarati გუჯარათი Bengali ბენგალური diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e3b4f24016..05f3a02a1c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5644,6 +5644,10 @@ breakText Glyphs 글리프 @msg there is no clock here: give `time` (Unix seconds) 여기에는 시계가 없습니다. `time`(Unix 초)을 지정하십시오 @msg the document has never been saved: give `folder` 문서를 저장한 적이 없습니다. `folder`를 지정하십시오 @msg every numbered name for the copy is taken 사본에 쓸 번호 붙은 이름이 모두 사용 중입니다 +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers 레이어에서 새 심볼 만들기 + Convert Layers to Symbols 레이어를 심볼로 변환 +@msg {id} is no top-level layer {id}은(는) 최상위 레이어가 아닙니다 Marathi 마라티어 Gujarati 구자라트어 Bengali 벵골어 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index e68a49a8e4..0828772479 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6003,6 +6003,10 @@ breakText Glyphs Glyphs @msg there is no clock here: give `time` (Unix seconds) er is hier geen klok: geef `time` op (Unix-seconden) @msg the document has never been saved: give `folder` het document is nooit opgeslagen: geef `folder` op @msg every numbered name for the copy is taken alle genummerde namen voor de kopie zijn bezet +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Nieuwe symbolen van lagen + Convert Layers to Symbols Lagen omzetten in symbolen +@msg {id} is no top-level layer {id} is geen laag op het hoogste niveau Marathi Marathi Gujarati Gujarati Bengali Bengaals diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index aa7f7b8780..38f3949710 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5917,6 +5917,10 @@ breakText Glyphs Glify @msg there is no clock here: give `time` (Unix seconds) brak tu zegara: podaj `time` (sekundy Unix) @msg the document has never been saved: give `folder` dokument nigdy nie został zapisany: podaj `folder` @msg every numbered name for the copy is taken wszystkie numerowane nazwy kopii są zajęte +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Nowe symbole z warstw + Convert Layers to Symbols Konwertuj warstwy na symbole +@msg {id} is no top-level layer {id} nie jest warstwą najwyższego poziomu Marathi Marathi Gujarati Gudżarati Bengali Bengalski diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 3305725b5a..ed4568edcf 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5981,6 +5981,10 @@ breakText Glyphs Glifos @msg there is no clock here: give `time` (Unix seconds) não há relógio aqui: informe `time` (segundos Unix) @msg the document has never been saved: give `folder` o documento nunca foi salvo: informe `folder` @msg every numbered name for the copy is taken todos os nomes numerados para a cópia estão em uso +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Novos Símbolos a partir de Camadas + Convert Layers to Symbols Converter Camadas em Símbolos +@msg {id} is no top-level layer {id} não é uma camada de nível superior Marathi Marati Gujarati Guzerate Bengali Bengali diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d272670889..a829cbf0d3 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6039,6 +6039,10 @@ breakText Glyphs Глифы @msg there is no clock here: give `time` (Unix seconds) здесь нет часов: укажите `time` (секунды Unix) @msg the document has never been saved: give `folder` документ ни разу не сохранялся: укажите `folder` @msg every numbered name for the copy is taken все нумерованные имена для копии заняты +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Новые символы из слоёв + Convert Layers to Symbols Преобразовать слои в символы +@msg {id} is no top-level layer {id} — не слой верхнего уровня Marathi Маратхи Gujarati Гуджарати Bengali Бенгальский diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 754962d2e8..182dee7b57 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6114,6 +6114,10 @@ breakText Glyphs Glyfer @msg there is no clock here: give `time` (Unix seconds) det finns ingen klocka här: ange `time` (Unix-sekunder) @msg the document has never been saved: give `folder` dokumentet har aldrig sparats: ange `folder` @msg every numbered name for the copy is taken alla numrerade namn för kopian är upptagna +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Nya symboler från lager + Convert Layers to Symbols Konvertera lager till symboler +@msg {id} is no top-level layer {id} är inget lager på översta nivån Marathi Marathi Gujarati Gujarati Bengali Bengali diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 8d682e7859..ae2a8b933f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6019,6 +6019,10 @@ breakText Glyphs Glifler @msg there is no clock here: give `time` (Unix seconds) burada saat yok: `time` verin (Unix saniyesi) @msg the document has never been saved: give `folder` belge hiç kaydedilmedi: `folder` verin @msg every numbered name for the copy is taken kopya için tüm numaralı adlar kullanılıyor +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Katmanlardan Yeni Semboller + Convert Layers to Symbols Katmanları Sembollere Dönüştür +@msg {id} is no top-level layer {id} üst düzey bir katman değil Marathi Marathi dili Gujarati Gücerat dili Bengali Bengalce diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index b5ac2dc5a7..f96a15dc6a 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5661,6 +5661,10 @@ breakText Glyphs Гліфи @msg there is no clock here: give `time` (Unix seconds) тут немає годинника: укажіть `time` (секунди Unix) @msg the document has never been saved: give `folder` документ жодного разу не зберігався: укажіть `folder` @msg every numbered name for the copy is taken усі нумеровані назви для копії зайняті +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Нові символи з шарів + Convert Layers to Symbols Перетворити шари на символи +@msg {id} is no top-level layer {id} — не шар верхнього рівня Marathi Маратхі Gujarati Гуджараті Bengali Бенгальська diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 49885e57d6..559dbe0996 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5664,6 +5664,10 @@ breakText Glyphs Glyph @msg there is no clock here: give `time` (Unix seconds) ở đây không có đồng hồ: hãy cho `time` (giây Unix) @msg the document has never been saved: give `folder` tài liệu chưa từng được lưu: hãy cho `folder` @msg every numbered name for the copy is taken mọi tên đánh số cho bản sao đều đã dùng +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers Ký hiệu mới từ các lớp + Convert Layers to Symbols Chuyển các lớp thành ký hiệu +@msg {id} is no top-level layer {id} không phải là lớp cấp cao nhất Marathi Tiếng Marathi Gujarati Tiếng Gujarati Bengali Tiếng Bengali diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 2c767f6392..cc619b472b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5904,6 +5904,10 @@ breakText Glyphs 字形 @msg there is no clock here: give `time` (Unix seconds) 此处没有时钟:请提供 `time`(Unix 秒) @msg the document has never been saved: give `folder` 文档从未保存过:请提供 `folder` @msg every numbered name for the copy is taken 副本的所有编号名称均已被占用 +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers 从图层新建符号 + Convert Layers to Symbols 将图层转换为符号 +@msg {id} is no top-level layer {id} 不是顶层图层 Marathi 马拉地语 Gujarati 古吉拉特语 Bengali 孟加拉语 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 651a1293ce..d2134afdc8 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5701,6 +5701,10 @@ breakText Glyphs 字符 @msg there is no clock here: give `time` (Unix seconds) 此處沒有時鐘:請提供 `time`(Unix 秒) @msg the document has never been saved: give `folder` 文件從未儲存過:請提供 `folder` @msg every numbered name for the copy is taken 拷貝的所有編號名稱均已被佔用 +# Document Tools add-on: New Symbols from Layers and Convert Layers to Symbols. + New Symbols from Layers 從圖層新增符號 + Convert Layers to Symbols 將圖層轉換為符號 +@msg {id} is no top-level layer {id} 不是最上層圖層 Marathi 馬拉地文 Gujarati 古吉拉特文 Bengali 孟加拉文 diff --git a/docs/mcp.md b/docs/mcp.md index ec441b7362..ee1f9a9233 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6292,3 +6292,15 @@ command is off where there is no clock (the web). → `{path, format, bytes, war {"name":"run_command","arguments":{"command":"addon.document.saveTimestampedCopy","params":{}}} {"name":"run_command","arguments":{"command":"addon.document.saveTimestampedCopy","params":{"folder":"/Users/me/Versions","format":"pdf"}}} ``` + +`addon.document.symbolsFromLayers {layers?, replace?}` makes one symbol of each top-level layer's art, as `symbol.new` +makes one (registration in the centre), named after the layer with a number added when a symbol has that name, as +one undo step. `layers` lists layer ids (top-level layers only; anything else is refused); by default it takes the +layers highlighted in the Layers panel when two or more are, else every layer. With `replace` (Convert Layers to +Symbols in the menu) each layer's art is replaced by an instance of its symbol at the same place and size, the +instances are selected, and locked layers are skipped. Layers with no art are skipped too; with nothing to make +there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{layer, name, reason: "empty" | "locked"}…]}` + +```json +{"name":"run_command","arguments":{"command":"addon.document.symbolsFromLayers","params":{"replace":true}}} +``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 99e2d7b2b6..8e145f25aa 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Document Tools add-on: Save a Timestamped Copy, #4926; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Document Tools add-on: New Symbols from Layers, #4927; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -1411,10 +1411,15 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Document Tools › Save a Timestamped Copy writes a copy of the document named `<name>_YYYY-MM-DD_HH-MM.<ext>` (the date and time in UTC, through chrono; `-2`, `-3`… added when that name is taken) next to the document, or into a folder picked (the folder picker) when it was never saved, in the document's own format or another save format. It writes through File › Save a Copy's save, so the document keeps its path, title and modified state, no undo step is made, and the write stays inside the automation roots in force. It is off on the web, which has no clock. Tests: `cmd::addons::document::tests` in `vectorcraft-engine` (the name and place, numbered names, the document unchanged and its content in the copy, an unsaved document needing a folder, other formats, bad params refused, automation roots), `addons::document::tests` in `vectorcraft-ui-egui` (the submenu, beside the document, the folder picked or cancelled) and `command_sweep`. Commands: `docs/mcp.md` › Document Tools add-on. +## Document Tools add-on: New Symbols from Layers (2026-11-01) + +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Document Tools › New Symbols from Layers makes one symbol of each top-level layer's art (the layers given, else those highlighted in the Layers panel when two or more are, else every layer), named after the layer (a number added when a symbol has that name), with New Symbol's own steps: the art normalized to its natural size, registration in the centre, threaded text keeping the text it shows, and sublayers held as groups. Convert Layers to Symbols does the same and puts an instance of each symbol in place of its layer's art, at the same place and size, selecting the instances; locked layers are skipped then. Empty layers are skipped and reported, all in one undo step (none when nothing is made). Tests: `cmd::addons::document::tests` in `vectorcraft-engine` (a symbol per layer, unique names, empty and locked layers reported, replacement in place, the highlighted layers as the default, bad layer ids refused, one undo step), `new_symbols_from_layers_and_convert_layers_to_symbols` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Document Tools add-on. + ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): New Symbols from Layers (#4927); evidence added; scores unchanged. | | 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): Save a Timestamped Copy (#4926); evidence added; scores unchanged. | | 2026-11-01 | minor | Path Precision Tools add-on (a VectorCraft addition): Divide into Dashes (#4950); evidence added; scores unchanged. | | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Group Overlapping Objects (#4928); evidence added; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 51578bb921..e05eeafa8c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Document Tools add-on: Save a Timestamped Copy, #4926) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Document Tools add-on: New Symbols from Layers, #4927) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -331,6 +331,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `<name>_YYYY-MM-DD_HH-MM.<ext>` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | +| Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › New Symbols from Layers makes a symbol of each layer's art named after the layer (the highlighted layers when two or more are, else all); Convert Layers to Symbols also replaces each layer's art with an instance in place; empty layers skipped, one undo step | done | #4927; `addon.document.symbolsFromLayers`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its seven tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.rs` and their tests; not a feature of the reference app, so it is not scored | @@ -384,6 +385,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): New Symbols from Layers and Convert Layers to Symbols (#4927); scores and estimates unchanged | | 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): Save a Timestamped Copy (#4926); scores and estimates unchanged | | 2026-11-01 | minor | Path Precision Tools add-on (a VectorCraft addition): Divide into Dashes (#4950); scores and estimates unchanged | | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Group Overlapping Objects (#4928); scores and estimates unchanged | From b8365d6197cf6b67f36ce2cfb0af20ea86705152 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 03:09:17 +0700 Subject: [PATCH 173/260] Fix #4942: native Indic digits in the Digits menu --- crates/doc/src/text/char_style.rs | 73 +++++++++++++++++++- crates/doc/src/text/tests.rs | 33 +++++++++ crates/engine/src/cmd/panelcmds.rs | 2 +- crates/engine/src/cmd/textedit.rs | 19 ++--- crates/engine/src/cmd/typecmd/area_tests.rs | 47 +++++++++++++ crates/text/src/tests/bidi.rs | 41 +++++++++++ crates/ui-egui/src/i18n/bg.tsv | 9 +++ crates/ui-egui/src/i18n/bs.tsv | 9 +++ crates/ui-egui/src/i18n/ca.tsv | 9 +++ crates/ui-egui/src/i18n/cs.tsv | 9 +++ crates/ui-egui/src/i18n/da.tsv | 9 +++ crates/ui-egui/src/i18n/de.tsv | 9 +++ crates/ui-egui/src/i18n/el.tsv | 9 +++ crates/ui-egui/src/i18n/es.tsv | 9 +++ crates/ui-egui/src/i18n/fi.tsv | 9 +++ crates/ui-egui/src/i18n/fr.tsv | 9 +++ crates/ui-egui/src/i18n/hu.tsv | 9 +++ crates/ui-egui/src/i18n/id.tsv | 9 +++ crates/ui-egui/src/i18n/it.tsv | 9 +++ crates/ui-egui/src/i18n/ja.tsv | 9 +++ crates/ui-egui/src/i18n/ka.tsv | 9 +++ crates/ui-egui/src/i18n/ko.tsv | 9 +++ crates/ui-egui/src/i18n/nl.tsv | 9 +++ crates/ui-egui/src/i18n/pl.tsv | 9 +++ crates/ui-egui/src/i18n/pt-br.tsv | 9 +++ crates/ui-egui/src/i18n/ru.tsv | 9 +++ crates/ui-egui/src/i18n/sv.tsv | 9 +++ crates/ui-egui/src/i18n/tests.rs | 16 +++++ crates/ui-egui/src/i18n/tr.tsv | 9 +++ crates/ui-egui/src/i18n/uk.tsv | 9 +++ crates/ui-egui/src/i18n/vi.tsv | 9 +++ crates/ui-egui/src/i18n/zh-hans.tsv | 9 +++ crates/ui-egui/src/i18n/zh-hant.tsv | 9 +++ crates/ui-egui/src/panels/character.rs | 54 +++++++++++---- crates/ui-egui/src/panels/character/tests.rs | 13 ++++ docs/mcp.md | 13 ++-- docs/type-parity.md | 5 +- 37 files changed, 516 insertions(+), 34 deletions(-) diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index 26c8b3c4f8..d53c99e6c6 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -123,8 +123,9 @@ pub struct CharStyle { } /// The numeral system digits are drawn in ([`CharStyle::digits`]): as typed, or every digit of -/// the Western, Arabic-Indic and Eastern Arabic-Indic sets drawn in one of them. The text keeps -/// the digits that were typed; only the glyphs change (like All Caps). +/// the Western, Arabic-Indic and Eastern Arabic-Indic sets drawn in one of them or in the digits +/// of an Indic script. The text keeps the digits that were typed; only the glyphs change (like +/// All Caps). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum Digits { @@ -137,9 +138,68 @@ pub enum Digits { Hindi, /// Eastern Arabic-Indic digits ۰–۹ (U+06F0–U+06F9), used in Persian and Urdu. Farsi, + /// Devanagari digits ०–९ (U+0966–U+096F), used in Hindi, Marathi, Nepali and Sanskrit. + Devanagari, + /// Bengali digits ০–৯ (U+09E6–U+09EF), used in Bengali and Assamese. + Bengali, + /// Gurmukhi digits ੦–੯ (U+0A66–U+0A6F), used in Punjabi. + Gurmukhi, + /// Gujarati digits ૦–૯ (U+0AE6–U+0AEF). + Gujarati, + /// Odia digits ୦–୯ (U+0B66–U+0B6F). + Odia, + /// Tamil digits ௦–௯ (U+0BE6–U+0BEF). + Tamil, + /// Telugu digits ౦–౯ (U+0C66–U+0C6F). + Telugu, + /// Kannada digits ೦–೯ (U+0CE6–U+0CEF). + Kannada, + /// Malayalam digits ൦–൯ (U+0D66–U+0D6F). + Malayalam, } impl Digits { + /// Every numeral system, in menu order. + pub const ALL: [Digits; 13] = [ + Digits::Default, + Digits::Arabic, + Digits::Hindi, + Digits::Farsi, + Digits::Devanagari, + Digits::Bengali, + Digits::Gurmukhi, + Digits::Gujarati, + Digits::Odia, + Digits::Tamil, + Digits::Telugu, + Digits::Kannada, + Digits::Malayalam, + ]; + + /// The name files and commands give this numeral system (as it is saved). + pub fn id(self) -> &'static str { + match self { + Digits::Default => "default", + Digits::Arabic => "arabic", + Digits::Hindi => "hindi", + Digits::Farsi => "farsi", + Digits::Devanagari => "devanagari", + Digits::Bengali => "bengali", + Digits::Gurmukhi => "gurmukhi", + Digits::Gujarati => "gujarati", + Digits::Odia => "odia", + Digits::Tamil => "tamil", + Digits::Telugu => "telugu", + Digits::Kannada => "kannada", + Digits::Malayalam => "malayalam", + } + } + + /// The numeral system [`Digits::id`] names; `None` for any other name. + pub fn from_id(id: &str) -> Option<Digits> { + Digits::ALL.into_iter().find(|d| d.id() == id) + } + /// The digit `c` is drawn as in this numeral system: the same digit in the chosen set, or `c` /// itself when `c` isn't a digit of the Western, Arabic-Indic or Eastern Arabic-Indic set. pub fn map(self, c: char) -> char { @@ -154,6 +214,15 @@ impl Digits { Digits::Arabic => '0' as u32, Digits::Hindi => 0x660, Digits::Farsi => 0x6F0, + Digits::Devanagari => 0x966, + Digits::Bengali => 0x9E6, + Digits::Gurmukhi => 0xA66, + Digits::Gujarati => 0xAE6, + Digits::Odia => 0xB66, + Digits::Tamil => 0xBE6, + Digits::Telugu => 0xC66, + Digits::Kannada => 0xCE6, + Digits::Malayalam => 0xD66, }; char::from_u32(base + value).unwrap_or(c) } diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 25e46a0490..89a2591a93 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -60,6 +60,39 @@ fn digits_map_between_the_numeral_systems() { assert_eq!(serde_json::from_value::<CharStyle>(serde_json::to_value(&farsi).unwrap()).unwrap(), farsi); } +/// Each Indic numeral system draws 0–9 (and the Arabic-Indic sets) as the ten digits of its +/// script's block; every system saves under its id, which reads back, and other names are refused. +#[test] +fn indic_digits_map_to_their_scripts_block() { + let map = |d: Digits, s: &str| -> String { s.chars().map(|c| d.map(c)).collect() }; + for (d, zero) in [ + (Digits::Devanagari, 0x966), + (Digits::Bengali, 0x9E6), + (Digits::Gurmukhi, 0xA66), + (Digits::Gujarati, 0xAE6), + (Digits::Odia, 0xB66), + (Digits::Tamil, 0xBE6), + (Digits::Telugu, 0xC66), + (Digits::Kannada, 0xCE6), + (Digits::Malayalam, 0xD66), + ] { + let block: String = (zero..zero + 10).map(|u| char::from_u32(u).unwrap()).collect(); + assert!(block.chars().all(char::is_numeric), "{d:?}: {block}"); + for s in ["0123456789", "٠١٢٣٤٥٦٧٨٩", "۰۱۲۳۴۵۶۷۸۹"] { + assert_eq!(map(d, s), block, "{d:?}"); + } + assert_eq!(map(d, "a-Z ٪"), "a-Z ٪"); + } + assert_eq!(map(Digits::Devanagari, "page 12"), "page १२"); + for d in Digits::ALL { + assert_eq!(serde_json::to_value(d).unwrap(), d.id()); + assert_eq!(serde_json::from_value::<Digits>(d.id().into()).unwrap(), d); + assert_eq!(Digits::from_id(d.id()), Some(d)); + } + assert_eq!(Digits::from_id("roman"), None); + assert!(serde_json::from_value::<Digits>("roman".into()).is_err()); +} + /// Language is saved only when set; styles written before it existed read as the default. #[test] fn language_is_saved_only_when_set() { diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 081678341b..163d543772 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", has_doc, set_format ), diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 0efc70bc6b..1797873ae3 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -339,17 +339,18 @@ pub(crate) fn char_direction_param(p: &Value, cmd: &str) -> Result<Option<Option })) } -/// `digits: "default"|"arabic"|"hindi"|"farsi"` → the numeral system the digits are drawn in. +/// `digits: "default"|"arabic"|"hindi"|"farsi"|"devanagari"|…` ([`Digits::id`]) → the numeral +/// system the digits are drawn in. +/// +/// [`Digits::id`]: vectorcraft_doc::Digits::id pub(crate) fn digits_param(p: &Value, cmd: &str) -> Result<Option<vectorcraft_doc::Digits>> { use vectorcraft_doc::Digits; let Some(v) = p.get("digits").filter(|v| !v.is_null()) else { return Ok(None) }; - Ok(Some(match v.as_str() { - Some("default") => Digits::Default, - Some("arabic") => Digits::Arabic, - Some("hindi") => Digits::Hindi, - Some("farsi") => Digits::Farsi, - _ => return Err(bad(cmd, "`digits` must be \"default\", \"arabic\", \"hindi\" or \"farsi\"")), - })) + let Some(d) = v.as_str().and_then(Digits::from_id) else { + let ids: Vec<String> = Digits::ALL.iter().map(|d| format!("\"{}\"", d.id())).collect(); + return Err(bad(cmd, format!("`digits` must be one of {}", ids.join(", ")))); + }; + Ok(Some(d)) } /// `language: name|tag` (one of Document Setup's languages, case-insensitive) → the language to diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index 1f93079ace..1dae041d90 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -1268,6 +1268,53 @@ fn digits_are_a_character_attribute_saved_only_when_set() { assert_eq!(set, [("صفحة ".to_string(), Digits::Default), ("12".to_string(), Digits::Farsi)]); } +/// The Indic digits (#4942): each set by its id through text.setFormat and text.setRangeStyle, +/// saved under it, kept by save and reopen and by character styles; the text stays as typed. +#[test] +fn indic_digits_round_trip_through_the_commands_and_the_file() { + use vectorcraft_doc::Digits; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "page 12"})).unwrap()["id"].as_u64().unwrap(); + let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("text"), + }; + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let indic = [ + Digits::Devanagari, + Digits::Bengali, + Digits::Gurmukhi, + Digits::Gujarati, + Digits::Odia, + Digits::Tamil, + Digits::Telugu, + Digits::Kannada, + Digits::Malayalam, + ]; + for d in indic { + s.execute("text.setFormat", &json!({"digits": d.id()})).unwrap(); + assert!(runs(&s).iter().all(|r| r.style.digits == d), "{d:?}"); + assert_eq!(serde_json::to_value(&runs(&s)[0].style).unwrap()["digits"], d.id()); + assert_eq!(runs(&s).iter().map(|r| r.text.as_str()).collect::<String>(), "page 12"); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") }; + assert!(t.runs.iter().all(|r| r.style.digits == d), "{d:?} after reopening"); + } + s.execute("text.setRangeStyle", &json!({"id": id, "start": 5, "end": 7, "digits": "gujarati"})).unwrap(); + let set: Vec<_> = runs(&s).iter().map(|r| (r.text.clone(), r.style.digits)).collect(); + assert_eq!(set, [("page ".to_string(), Digits::Malayalam), ("12".to_string(), Digits::Gujarati)]); + assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[1].style)["digits"], "gujarati"); + s.execute("charStyle.new", &json!({"name": "Tamil digits", "attrs": {"digits": "tamil"}})).unwrap(); + let listed = s.execute("charStyle.list", &json!({})).unwrap(); + let tamil = listed["styles"].as_array().unwrap().iter().find(|st| st["name"] == "Tamil digits").unwrap(); + assert_eq!(tamil["attrs"]["digits"], "tamil"); + for wrong in [json!("oriya"), json!("Devanagari"), json!(3)] { + let err = s.execute("text.setFormat", &json!({ "digits": wrong })).unwrap_err().to_string(); + assert!(err.contains("`digits` must be one of") && err.contains("\"malayalam\""), "{err}"); + } +} + /// Language (Character panel, #4946): a character attribute set by name or tag, saved as the tag /// only when set, kept by save and reopen and by character styles; new type takes the document's. #[test] diff --git a/crates/text/src/tests/bidi.rs b/crates/text/src/tests/bidi.rs index 1ec51d15ac..a48d2c020d 100644 --- a/crates/text/src/tests/bidi.rs +++ b/crates/text/src/tests/bidi.rs @@ -591,6 +591,47 @@ fn digits_draw_every_digit_in_the_styles_numeral_system() { assert_ne!(gids(&lay("3 ٣ ۳", Digits::Default)), gids(&lay("3 ٣ ۳", Digits::Hindi))); } +/// The Indic digits (#4942): typed Western digits are drawn with the glyphs of the script's own +/// digits, on the typed text's clusters. A font lacking them still lays the text out, in the +/// fallback face that has them or as missing glyphs, with the clusters as typed. Each script +/// needs an installed font with its digits; one without is skipped. +#[test] +fn indic_digits_draw_the_scripts_own_digits() { + use vectorcraft_doc::Digits; + let indic = [ + (Digits::Devanagari, '३'), + (Digits::Bengali, '৩'), + (Digits::Gurmukhi, '੩'), + (Digits::Gujarati, '૩'), + (Digits::Odia, '୩'), + (Digits::Tamil, '௩'), + (Digits::Telugu, '౩'), + (Digits::Kannada, '೩'), + (Digits::Malayalam, '൩'), + ]; + let clusters = |l: &TextLayout| l.glyphs.iter().map(|g| (g.byte, g.len)).collect::<Vec<_>>(); + let gids = |l: &TextLayout| l.glyphs.iter().map(|g| (g.gid, g.font_id)).collect::<Vec<_>>(); + // Bundled fonts only: the digits may have no face at all, and nothing panics. + let bundled = FontDb::with_font_dirs(vec![]); + for (d, _) in indic { + let lay = |s: &str, digits: Digits| layout(&bundled, &TextObject::point(Point::ZERO, s, CharStyle { digits, ..CharStyle::default() })); + assert_eq!(clusters(&lay("page 30", d)), clusters(&lay("page 30", Digits::Default)), "{d:?}"); + } + let db = FontDb::global(); + for (d, three) in indic { + let Some(face) = db.face_covering(three) else { + eprintln!("SKIPPED: indic_digits_draw_the_scripts_own_digits for {d:?}; no installed font covers {three}"); + continue; + }; + eprintln!("ASSERTIONS RUN: indic_digits_draw_the_scripts_own_digits for {d:?}; {} {}", face.family, face.style); + let st = |digits: Digits| CharStyle { digits, ..arabic_style(&face) }; + let lay = |s: &str, digits: Digits| layout(db, &TextObject::point(Point::ZERO, s, st(digits))); + let drawn = lay("3", d); + assert_eq!(gids(&drawn), gids(&lay(&three.to_string(), Digits::Default)), "{d:?}"); + assert_eq!(clusters(&drawn), clusters(&lay("3", Digits::Default)), "{d:?}"); + } +} + /// Right-to-left type on a path that overflows shows the start of its text, as a line of area /// type does, not whatever comes first in visual order. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 177f87058c..f47d5b7b63 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2401,6 +2401,15 @@ font-technology Variable Променливи Arabic Арабски Hindi Хинди Farsi Фарси +digits Devanagari Деванагари +digits Bengali Бенгалски +digits Gurmukhi Гурмукхи +digits Gujarati Гуджарати +digits Odia Ория +digits Tamil Тамилски +digits Telugu Телугу +digits Kannada Каннада +digits Malayalam Малаялам Proportional Oldstyle Пропорционални стари цифри Pucker & Bloat… Свиване и раздуване… Pucker Tool Инструмент „Свиване“ diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 1cdf807f02..584d4cf407 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1421,6 +1421,15 @@ lighting Light Svjetlo Arabic Arapski Hindi Hindi Farsi Farsi +digits Devanagari Devanagari +digits Bengali Bengalski +digits Gurmukhi Gurmukhi +digits Gujarati Gudžarati +digits Odia Odija +digits Tamil Tamilski +digits Telugu Telugu +digits Kannada Kanada +digits Malayalam Malajalam Reset Panel Vrati panel na početno Roman Baseline Latinična osnovna linija Select a text object to edit its character attributes. Odaberite tekstualni objekat da uredite njegove atribute znakova. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c2c363ebd2..02c98c1b5c 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1488,6 +1488,15 @@ Eyedropper: click the art to sample the key color Comptagotes: fes clic a l’art per mostrejar el color clau Eyedropper: click the art to sample the stop's colour Comptagotes: fes clic a l’art per mostrejar el color de la parada Farsi Persa +digits Devanagari Devanagari +digits Bengali Bengalí +digits Gurmukhi Gurmukhi +digits Gujarati Gujarati +digits Odia Oriya +digits Tamil Tàmil +digits Telugu Telugu +digits Kannada Kannada +digits Malayalam Malaiàlam Favorites Preferits Feather Ploma Feather… Ploma… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 42f1c3977c..2f21d51d86 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1445,6 +1445,15 @@ lighting Light Světlo Hindi Hindština digits Hindi Hindské Farsi Perské +digits Devanagari Dévanágarské +digits Bengali Bengálské +digits Gurmukhi Gurmukhské +digits Gujarati Gudžarátské +digits Odia Urijské +digits Tamil Tamilské +digits Telugu Telugské +digits Kannada Kannadské +digits Malayalam Malajálamské Reset Panel Obnovit panel Roman Baseline Latinková účaří Select a text object to edit its character attributes. Vyberte textový objekt, abyste mohli upravit atributy jeho znaků. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 5b64d2758f..df8c467e15 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1359,6 +1359,15 @@ lighting Light Lys Arabic Arabisk Hindi Hindi Farsi Farsi +digits Devanagari Devanagari +digits Bengali Bengali +digits Gurmukhi Gurmukhi +digits Gujarati Gujarati +digits Odia Oriya +digits Tamil Tamil +digits Telugu Telugu +digits Kannada Kannada +digits Malayalam Malayalam Reset Panel Nulstil panel Roman Baseline Romersk grundlinje Select a text object to edit its character attributes. Markér et tekstobjekt for at redigere dets tegnattributter. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 32f8ee3f85..95439eea61 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2420,6 +2420,15 @@ mark-style Japanese Japanisch Arabic Arabisch Hindi Hindi Farsi Farsi +digits Devanagari Devanagari +digits Bengali Bengalisch +digits Gurmukhi Gurmukhi +digits Gujarati Gujarati +digits Odia Oriya +digits Tamil Tamil +digits Telugu Telugu +digits Kannada Kannada +digits Malayalam Malayalam Proportional Oldstyle Proportionale Mediävalziffern Pucker & Bloat… Zusammenziehen und aufblasen… Pucker Tool Zusammenziehen-Werkzeug diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 2ce1d6b853..91f441adaa 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3059,6 +3059,15 @@ theme Appearance Εμφάνιση Arabic Αραβικά Hindi Χίντι Farsi Περσικά +digits Devanagari Ντεβαναγκάρι +digits Bengali Βεγγαλικά +digits Gurmukhi Γκουρμούκι +digits Gujarati Γκουγιαράτι +digits Odia Όντια +digits Tamil Ταμιλικά +digits Telugu Τελούγκου +digits Kannada Κανάντα +digits Malayalam Μαλαγιάλαμ Proportional Oldstyle Αναλογικοί παλαιοτυπικοί αριθμοί Pucker & Bloat… Συρρίκνωση και διόγκωση… Pucker Tool Συρρίκνωση (Pucker Tool) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 277af453f6..8fe2d8401f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2458,6 +2458,15 @@ font-technology Variable Variables Arabic Árabes Hindi Hindi Farsi Farsi +digits Devanagari Devanagari +digits Bengali Bengalí +digits Gurmukhi Gurmukhi +digits Gujarati Guyaratí +digits Odia Oriya +digits Tamil Tamil +digits Telugu Telugu +digits Kannada Canarés +digits Malayalam Malayálam Proportional Oldstyle Estilo antiguo proporcional Pucker & Bloat… Fruncir y engordar… Pucker Tool Herramienta Fruncir diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 5ff14b7d9f..5fbec069ad 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1419,6 +1419,15 @@ lighting Light Valo Arabic Arabia Hindi Hindi Farsi Farsi +digits Devanagari Devanagari +digits Bengali Bengali +digits Gurmukhi Gurmukhi +digits Gujarati Gudžarati +digits Odia Orija +digits Tamil Tamili +digits Telugu Telugu +digits Kannada Kannada +digits Malayalam Malajalam Reset Panel Palauta paneeli Roman Baseline Latinalainen perusviiva Select a text object to edit its character attributes. Valitse tekstiobjekti, jonka merkkimääritteitä haluat muokata. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 76717dd003..d6ec59b6cd 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2456,6 +2456,15 @@ font-technology Variable Variables Arabic Arabes Hindi Hindi Farsi Farsi +digits Devanagari Dévanagari +digits Bengali Bengali +digits Gurmukhi Gurmukhi +digits Gujarati Goudjarati +digits Odia Odia +digits Tamil Tamoul +digits Telugu Télougou +digits Kannada Kannada +digits Malayalam Malayalam Proportional Oldstyle Elzévirien proportionnel Pucker & Bloat… Contraction et dilatation… Pucker Tool Outil Contraction diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c391405c46..fe56efa822 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1375,6 +1375,15 @@ font-technology Variable Változó Eyedropper: click the art to sample the stop's colour Pipetta: kattints a grafikára a pont színének mintavételéhez Eyedropper: click the art to sample the key color Pipetta: kattints a grafikára a kulcsszín mintavételéhez Farsi Perzsa +digits Devanagari Dévanágari +digits Bengali Bengáli +digits Gurmukhi Gurmukhi +digits Gujarati Gudzsaráti +digits Odia Odia +digits Tamil Tamil +digits Telugu Telugu +digits Kannada Kannada +digits Malayalam Malajálam Favorites Kedvencek Feather Tollazat Feather… Elmosott szél… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index a49fcb3e35..a37491b992 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1359,6 +1359,15 @@ lighting Light Cahaya Arabic Arab Hindi Hindi Farsi Farsi +digits Devanagari Dewanagari +digits Bengali Bengali +digits Gurmukhi Gurmukhi +digits Gujarati Gujarati +digits Odia Oriya +digits Tamil Tamil +digits Telugu Telugu +digits Kannada Kannada +digits Malayalam Malayalam Reset Panel Setel ulang panel Roman Baseline Baseline Romawi Select a text object to edit its character attributes. Pilih objek teks untuk mengedit atribut karakternya. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 0816ef0c7c..dbf755d31d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2489,6 +2489,15 @@ mark-style Japanese Giapponese Arabic Arabe Hindi Hindi Farsi Farsi +digits Devanagari Devanagari +digits Bengali Bengalese +digits Gurmukhi Gurmukhi +digits Gujarati Gujarati +digits Odia Odia +digits Tamil Tamil +digits Telugu Telugu +digits Kannada Kannada +digits Malayalam Malayalam Proportional Oldstyle Proporzionali stile antico Pucker & Bloat… Contrai e gonfia… Pucker Tool Strumento Contrai diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 795b48730d..54e53749be 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -49,6 +49,15 @@ font-technology Variable バリアブル Hindi ヒンディー語 digits Hindi ヒンディー数字 Farsi ペルシャ数字 +digits Devanagari デーヴァナーガリー数字 +digits Bengali ベンガル数字 +digits Gurmukhi グルムキー数字 +digits Gujarati グジャラート数字 +digits Odia オディア数字 +digits Tamil タミル数字 +digits Telugu テルグ数字 +digits Kannada カンナダ数字 +digits Malayalam マラヤーラム数字 Favorites お気に入り Flip 反転 Japanese 日本語 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 2eec1b66f9..a5f844aba6 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1276,6 +1276,15 @@ lighting Light სინათლე Arabic არაბული Hindi ჰინდი Farsi სპარსული +digits Devanagari დევანაგარი +digits Bengali ბენგალური +digits Gurmukhi გურმუხი +digits Gujarati გუჯარათი +digits Odia ორია +digits Tamil ტამილური +digits Telugu ტელუგუ +digits Kannada კანადა +digits Malayalam მალაიალამური Reset Panel პანელის ჩამოყრა Roman Baseline ლათინური საბაზისო ხაზი Select a text object to edit its character attributes. სიმბოლოების ატრიბუტების რედაქტირებისთვის მონიშნეთ ტექსტური ობიექტი. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 05f3a02a1c..5dd77eaba7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -42,6 +42,15 @@ font-technology Variable 가변 Arabic 아라비아어 Hindi 힌디어 Farsi 페르시아어 +digits Devanagari 데바나가리 +digits Bengali 벵골어 +digits Gurmukhi 구르무키 +digits Gujarati 구자라트어 +digits Odia 오리야어 +digits Tamil 타밀어 +digits Telugu 텔루구어 +digits Kannada 칸나다어 +digits Malayalam 말라얄람어 Favorites 즐겨찾기 Flip 뒤집기 Japanese 일본어 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 0828772479..4c60e73589 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1373,6 +1373,15 @@ lighting Light Licht Arabic Arabisch Hindi Hindi Farsi Farsi +digits Devanagari Devanagari +digits Bengali Bengaals +digits Gurmukhi Gurmukhi +digits Gujarati Gujarati +digits Odia Odia +digits Tamil Tamil +digits Telugu Telugu +digits Kannada Kannada +digits Malayalam Malayalam Reset Panel Paneel herstellen Roman Baseline Romeinse basislijn Select a text object to edit its character attributes. Selecteer een tekstobject om de tekenkenmerken ervan te bewerken. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 38f3949710..593f7d2ab3 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1358,6 +1358,15 @@ lighting Light Światło Arabic Arabskie Hindi Hindi Farsi Perskie +digits Devanagari Dewanagari +digits Bengali Bengalskie +digits Gurmukhi Gurmukhi +digits Gujarati Gudżarati +digits Odia Orija +digits Tamil Tamilskie +digits Telugu Telugu +digits Kannada Kannada +digits Malayalam Malajalam Reset Panel Resetuj panel Roman Baseline Linia bazowa łacińska Select a text object to edit its character attributes. Zaznacz obiekt tekstowy, aby edytować atrybuty znaków. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index ed4568edcf..e6e4599be4 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2027,6 +2027,15 @@ Arabic Arábicos Hindi Hindi Farsi Farsi +digits Devanagari Devanágari +digits Bengali Bengali +digits Gurmukhi Gurmukhi +digits Gujarati Guzerate +digits Odia Oriá +digits Tamil Tâmil +digits Telugu Télugo +digits Kannada Canarim +digits Malayalam Malaiala Pucker & Bloat… Encolher e Inchar… Pucker Tool Ferramenta Encolher Punctuation Space Espaço de Pontuação diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a829cbf0d3..fa9e68b5d7 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2485,6 +2485,15 @@ mark-style Japanese Японский Arabic Арабские Hindi Хинди Farsi Фарси +digits Devanagari Деванагари +digits Bengali Бенгальские +digits Gurmukhi Гурмукхи +digits Gujarati Гуджарати +digits Odia Ория +digits Tamil Тамильские +digits Telugu Телугу +digits Kannada Каннада +digits Malayalam Малаялам Proportional Oldstyle Пропорциональные старого стиля Pucker & Bloat… Сморщивание и раздувание… Pucker Tool Инструмент «Сморщивание» diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 182dee7b57..23aa4028ba 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2401,6 +2401,15 @@ font-technology Variable Variabla Arabic Arabiska Hindi Hindi Farsi Farsi +digits Devanagari Devanagari +digits Bengali Bengali +digits Gurmukhi Gurmukhi +digits Gujarati Gujarati +digits Odia Oriya +digits Tamil Tamil +digits Telugu Telugu +digits Kannada Kannada +digits Malayalam Malayalam Proportional Oldstyle Proportionella medievalsiffror Pucker & Bloat… Dra ihop och svullna… Pucker Tool Verktyget Dra ihop diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index f1d4bc04f5..c3e3345a02 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1985,3 +1985,19 @@ fn polish_plurals_have_three_forms() { } assert!(count >= 13, "Polish plural rows missing"); } + +/// Every catalog names each numeral system of Character panel menu › Digits, in the `digits` +/// context (where the language's name would read wrong) or with its plain row (#4942). +#[test] +fn every_catalog_names_the_digits_menus_numeral_systems() { + let mut missing = Vec::new(); + for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { + let cat = l.catalog(); + for (label, _) in crate::panels::character::DIGITS { + if cat.contextual("digits", label).is_none() && cat.plain(label).is_none() { + missing.push(format!("{}: {label}", l.code)); + } + } + } + assert!(missing.is_empty(), "Digits menu labels without a row:\n{}", missing.join("\n")); +} diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ae2a8b933f..c9a3175cb3 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2280,6 +2280,15 @@ shape Open Açık Arabic Arapça Hindi Hintçe Farsi Farsça +digits Devanagari Devanagari +digits Bengali Bengalce +digits Gurmukhi Gurmukhi +digits Gujarati Gücerat +digits Odia Oriya +digits Tamil Tamilce +digits Telugu Telugu +digits Kannada Kannada +digits Malayalam Malayalam Proportional Oldstyle Orantılı Eski Stil Pucker & Bloat… Büzüşme ve Şişkinlik… Pucker Tool Büzme Aracı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index f96a15dc6a..39303f0a2f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2481,6 +2481,15 @@ mark-style Japanese Японський Arabic Арабські Hindi Гінді Farsi Фарсі +digits Devanagari Деванагарі +digits Bengali Бенгальські +digits Gurmukhi Гурмукхі +digits Gujarati Гуджараті +digits Odia Одія +digits Tamil Тамільські +digits Telugu Телугу +digits Kannada Каннада +digits Malayalam Малаялам Proportional Oldstyle Пропорційні цифри старого стилю Pucker & Bloat… Зморщування та роздування … Pucker Tool Інструмент «Зморщування» diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 559dbe0996..bc4d856aa9 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1252,6 +1252,15 @@ font-technology Variable Biến thiên Eyedropper: click the art to sample the stop's colour Ống hút màu: bấm vào tác phẩm để lấy mẫu màu điểm dừng Eyedropper: click the art to sample the key color Ống hút màu: bấm vào tác phẩm để lấy mẫu màu chủ Farsi Farsi +digits Devanagari Devanagari +digits Bengali Bengali +digits Gurmukhi Gurmukhi +digits Gujarati Gujarati +digits Odia Odia +digits Tamil Tamil +digits Telugu Telugu +digits Kannada Kannada +digits Malayalam Malayalam Favorites Yêu thích Feather… Làm mờ dần… Feet Feet diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index cc619b472b..00839e4ef7 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2361,6 +2361,15 @@ font-script Japanese 汉字 Hindi 印地语 digits Hindi 印地数字 Farsi 波斯数字 +digits Devanagari 天城数字 +digits Bengali 孟加拉数字 +digits Gurmukhi 古木基数字 +digits Gujarati 古吉拉特数字 +digits Odia 奥里亚数字 +digits Tamil 泰米尔数字 +digits Telugu 泰卢固数字 +digits Kannada 卡纳达数字 +digits Malayalam 马拉雅拉姆数字 Proportional Oldstyle 比例旧式数字 Pucker & Bloat… 缩拢与膨胀… Pucker Tool 收缩工具 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d2134afdc8..1385a52c7e 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3302,6 +3302,15 @@ font-script Japanese 漢字 Hindi 印地文 digits Hindi 印地數字 Farsi 波斯數字 +digits Devanagari 天城數字 +digits Bengali 孟加拉數字 +digits Gurmukhi 古木基數字 +digits Gujarati 古吉拉特數字 +digits Odia 歐利亞數字 +digits Tamil 坦米爾數字 +digits Telugu 泰盧固數字 +digits Kannada 坎那達數字 +digits Malayalam 馬來亞拉姆數字 Proportional Oldstyle 比例舊式數字 Pucker & Bloat… 縮攏與膨脹… Pucker Tool 縮攏工具 diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index ebd80f1ed2..bf5788d985 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -1016,6 +1016,44 @@ fn char_direction_items(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// The numeral systems Character panel menu › Digits lists after Default, with their English +/// labels, translated in the `digits` context (Hindi, Bengali, Tamil… are also languages): the +/// Arabic-script ones, then the Indic scripts' own digits from Devanagari on. +pub(crate) const DIGITS: [(&str, vectorcraft_doc::Digits); 12] = { + use vectorcraft_doc::Digits; + [ + ("Arabic", Digits::Arabic), + ("Hindi", Digits::Hindi), + ("Farsi", Digits::Farsi), + ("Devanagari", Digits::Devanagari), + ("Bengali", Digits::Bengali), + ("Gurmukhi", Digits::Gurmukhi), + ("Gujarati", Digits::Gujarati), + ("Odia", Digits::Odia), + ("Tamil", Digits::Tamil), + ("Telugu", Digits::Telugu), + ("Kannada", Digits::Kannada), + ("Malayalam", Digits::Malayalam), + ] +}; + +/// Character panel menu › Digits; `digits`: the selected characters' (`None` when they differ). +fn digits_items(app: &mut VectorcraftApp, ui: &mut Ui, digits: Option<vectorcraft_doc::Digits>) { + use vectorcraft_doc::Digits; + let mut item = |ui: &mut Ui, label: &str, d: Digits| { + if menu_item(ui, label, true, digits == Some(d)) { + format(app, json!({"digits": d.id()})); + } + }; + item(ui, tl!("Default"), Digits::Default); + for (label, d) in DIGITS { + if d == Digits::Devanagari { + ui.separator(); + } + item(ui, crate::i18n::tr_ctx(crate::i18n::current(), "digits", label), d); + } +} + pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let st = text_style(app); let has = st.is_some(); @@ -1089,21 +1127,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if app.session.prefs.show_indic_options { let digits = s.as_ref().map(|s| s.digits); ui.add_enabled_ui(has, |ui| { - ui.menu_button(format!(" {}", tl!("Digits")), |ui| { - use vectorcraft_doc::Digits; - // The numeral systems, in the digits context: Hindi is also a language. - let digits_label = |s| crate::i18n::tr_ctx(crate::i18n::current(), "digits", s); - for (label, d, key) in [ - (tl!("Default"), Digits::Default, "default"), - (digits_label("Arabic"), Digits::Arabic, "arabic"), - (digits_label("Hindi"), Digits::Hindi, "hindi"), - (digits_label("Farsi"), Digits::Farsi, "farsi"), - ] { - if menu_item(ui, label, true, digits == Some(d)) { - format(app, json!({"digits": key})); - } - } - }); + ui.menu_button(format!(" {}", tl!("Digits")), |ui| digits_items(app, ui, digits)); }); ui.add_enabled_ui(has, |ui| { ui.menu_button(format!(" {}", tl!("Character Direction")), |ui| char_direction_items(app, ui)); diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 61ec42a218..8f02228b5b 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -540,6 +540,19 @@ fn digits_show_with_the_indic_options() { assert!(shown(&mut app)); } +/// The Digits submenu lists Default, the Arabic-script numeral systems and the Indic scripts' +/// digits (#4942), and checks the selected characters' system. +#[test] +fn digits_submenu_lists_the_indic_scripts_and_checks_the_selection() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| digits_items(app, ui, Some(vectorcraft_doc::Digits::Tamil))); + let items: Vec<_> = text.lines().map(|l| l.trim().trim_start_matches("✓ ")).collect(); + let want = + ["Default", "Arabic", "Hindi", "Farsi", "Devanagari", "Bengali", "Gurmukhi", "Gujarati", "Odia", "Tamil", "Telugu", "Kannada", "Malayalam"]; + assert!(want.iter().all(|w| items.contains(w)), "{items:?}"); + assert_eq!(text.lines().filter_map(|l| l.strip_prefix("✓ ")).collect::<Vec<_>>(), ["Tamil"]); +} + /// Character Direction is in the panel menu with the Middle Eastern (Indic) options, beside /// Digits. Its submenu checks the direction the characters the panel acts on share: the /// selected type's, or the range the Type tool has selected. It checks no item when they differ. diff --git a/docs/mcp.md b/docs/mcp.md index ee1f9a9233..4c893cff82 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5022,11 +5022,14 @@ command is one undo step. ## Digits -`text.setFormat {digits: "default"|"arabic"|"hindi"|"farsi"}` (the selected type, or `ids`) and `text.setRangeStyle {id, -start, end, digits}` (a range) set the numeral system the characters' digits are drawn in, as the Character panel menu's -Digits does with the Middle Eastern (Indic) options shown: `arabic` draws every digit as the Western 0–9, `hindi` as the -Arabic-Indic ٠–٩ (U+0660–U+0669) and `farsi` as the Eastern Arabic-Indic ۰–۹ (U+06F0–U+06F9), whichever of the three sets -was typed; `default` leaves each digit as typed. The text keeps the digits that were typed (`text.getRange`, search, +`text.setFormat {digits: "default"|"arabic"|"hindi"|"farsi"|"devanagari"|"bengali"|"gurmukhi"|"gujarati"|"odia"|"tamil"|"telugu"|"kannada"|"malayalam"}` +(the selected type, or `ids`) and `text.setRangeStyle {id, start, end, digits}` (a range) set the numeral system the +characters' digits are drawn in, as the Character panel menu's Digits does with the Middle Eastern (Indic) options shown: +`arabic` draws every digit as the Western 0–9, `hindi` as the Arabic-Indic ٠–٩ (U+0660–U+0669) and `farsi` as the Eastern +Arabic-Indic ۰–۹ (U+06F0–U+06F9), whichever of the three sets was typed; the Indic ones draw them as their script's own +digits (#4942): `devanagari` ०–९ (U+0966–U+096F), `bengali` ০–৯ (U+09E6), `gurmukhi` ੦–੯ (U+0A66), `gujarati` ૦–૯ +(U+0AE6), `odia` ୦–୯ (U+0B66), `tamil` ௦–௯ (U+0BE6), `telugu` ౦–౯ (U+0C66), `kannada` ೦–೯ (U+0CE6) and `malayalam` ൦–൯ +(U+0D66); `default` leaves each digit as typed. Any other value is refused. The text keeps the digits that were typed (`text.getRange`, search, the caret and selection are unchanged); only the glyphs change, as with All Caps, and SVG export writes the digits as drawn. A digit the font lacks comes from a fallback font. Default and saved only when set. One undo step. diff --git a/docs/type-parity.md b/docs/type-parity.md index 3d76581f90..f6c4a2c7b3 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Language per character: text is shaped in its language, Character panel › Language, Indian languages; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Digits: the native digits of the Indic scripts, #4942; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -53,7 +53,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds (`Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232) | | Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web | | Middle Eastern: bidirectional layout, Paragraph Direction | done | | -| Middle Eastern: digit types (Character panel menu › Digits: Default, Arabic, Hindi, Farsi) | done | `text.setFormat` / `text.setRangeStyle {digits}`; the text keeps the typed digits, the glyphs and SVG export follow the style | +| Middle Eastern and Indic: digit types (Character panel menu › Digits: Default, Arabic, Hindi, Farsi; Devanagari, Bengali, Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada, Malayalam) | done | `text.setFormat` / `text.setRangeStyle {digits}` (`"devanagari"`, `"bengali"`, `"gurmukhi"`, `"gujarati"`, `"odia"`, `"tamil"`, `"telugu"`, `"kannada"`, `"malayalam"` added, #4942); the text keeps the typed digits, the glyphs and SVG export follow the style; carried by character styles. Not yet: `.ai` export of the setting; Indic digits typed as such stay as typed under another system. Evidence: `text::tests::indic_digits_map_to_their_scripts_block`, `tests::bidi::indic_digits_draw_the_scripts_own_digits`, `typecmd::area_tests::indic_digits_round_trip_through_the_commands_and_the_file` | | Middle Eastern: Character Direction, kashidas, Middle Eastern composers, split caret | missing | | | CJK: input methods (marked text, candidate window) | done | | | CJK: kinsoku (Hard, Soft, None), Line-end Punctuation Half Width, tate-chu-yoko (auto) | done / partial | custom kinsoku sets, the Mojikumi Settings dialog and the other mojikumi sets missing | @@ -72,6 +72,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Digits (#4942): the native digits of Devanagari, Bengali, Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada and Malayalam in the Character panel menu › Digits and `{digits}`; scores unchanged | | 2026-11-01 | minor | Language per character (#4946): Character panel › Language, `text.setFormat` / `text.setRangeStyle {language}`, character styles; text is shaped in its language (`locl`, #4940); new type takes the document's; Indian languages in the list (#4943); scores unchanged | | 2026-10-31 | minor | PDF import finds an installed font whose PDF name holds hyphens (`Noto-Sans-Bold` is Noto Sans, Bold: the longest part before a hyphen that names an installed family) and a composite font by its CIDFont's name rather than its base name, which ends in the CMap's (`Name-Identity-H`, [ISO 32000-1 §9.7.6.1](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)); a missing font is split only before a style part (`Helvetica-BoldOblique`), so it is reported as `MS PGothic`, not `MS`; scores unchanged | | 2026-10-31 | minor | Highlight Alternate Glyphs: an optional feature (such as `salt`) that changes a lam-alef ligature is highlighted again, only the required ligature staying clear, and a lam-alef with any combining mark (Arabic Extended-A/B/C included) counts as the ligature (#394); scores unchanged | From 3146ca513bb77f35692d8eac02580d4f0c02c681 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 03:18:25 +0700 Subject: [PATCH 174/260] Fix #4939: Global Edit finds and edits groups like the selected one --- crates/engine/src/cmd/globaledit.rs | 257 ++++++++++++++++++-------- crates/engine/src/tests/globaledit.rs | 155 +++++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 2 +- crates/ui-egui/src/i18n/ca.tsv | 2 +- crates/ui-egui/src/i18n/cs.tsv | 2 +- crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 2 +- crates/ui-egui/src/i18n/el.tsv | 2 +- crates/ui-egui/src/i18n/es.tsv | 2 +- crates/ui-egui/src/i18n/fi.tsv | 2 +- crates/ui-egui/src/i18n/fr.tsv | 2 +- crates/ui-egui/src/i18n/hu.tsv | 2 +- crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 2 +- crates/ui-egui/src/i18n/ja.tsv | 2 +- crates/ui-egui/src/i18n/ka.tsv | 2 +- crates/ui-egui/src/i18n/ko.tsv | 2 +- crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 2 +- crates/ui-egui/src/i18n/pt-br.tsv | 2 +- crates/ui-egui/src/i18n/ru.tsv | 2 +- crates/ui-egui/src/i18n/sv.tsv | 2 +- crates/ui-egui/src/i18n/tr.tsv | 2 +- crates/ui-egui/src/i18n/uk.tsv | 2 +- crates/ui-egui/src/i18n/vi.tsv | 2 +- crates/ui-egui/src/i18n/zh-hans.tsv | 2 +- crates/ui-egui/src/i18n/zh-hant.tsv | 2 +- docs/gaps.md | 12 +- docs/mcp.md | 38 ++-- docs/target-app-parity.md | 9 +- docs/ui-parity.md | 5 +- 32 files changed, 389 insertions(+), 135 deletions(-) diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index c136878800..fe18309463 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -11,6 +11,15 @@ //! every artboard and the canvas around them by default; it can be limited to a range of //! artboards (`1, 3-5`) and can leave out the objects that lie on no artboard. Images, type, //! masks, linked files and selections of more than one object are not supported. +//! - The help page "Edit groups with similar objects" +//! (<https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html>): +//! with a group selected, Start Global Edit finds the groups like it, and an edit made to an +//! object inside one of them is made to the matching object in each of the others. Here a group +//! is like another when it holds as many objects, in the same order, each like the one at its +//! place (paths, compound paths, symbol instances and groups of them, clipping paths included), +//! and they lie the same way relative to each other: the group as a whole is moved or scaled. +//! With Appearance on, each of those objects must have the same fill and stroke too; with Size, +//! the groups the same width and height. //! - While Global Edit is on, an edit made to one of the found objects is made to all of them, //! each in proportion to its own size: halving the height of a 100 pt object halves a 20 pt //! match to 10 pt. Stop Global Edit (or Escape) ends it. @@ -42,8 +51,16 @@ //! takes the selection there is. Whenever the document is put back (Undo, Redo, a cancelled drag //! or scrub, an edit that failed), the members it lacks (or no longer supports) leave the Global //! Edit, and it ends when fewer than two are left ([`follow_history`]), so that an object made -//! later under a freed id is never edited. Rotated copies, groups (the help page "Edit groups with -//! similar objects") and excluding a member with a Shift-click are not covered. +//! later under a freed id is never edited. +//! +//! A member that is a group takes, of an edit made inside the model group, what changed about +//! each object in it, given by the same rules to the object at the same place in the member (its +//! hidden and locked objects are left as they are), and what changed about the group itself (its +//! opacity, blending, fills and effects). When the model group gains or loses objects, or one of +//! them becomes another kind of object, each member takes the model's objects at that level +//! whole, keeping its own ids in order. At most [`MAX_MEMBERS`] objects are taken, so that a huge +//! document can't stall the start or every edit. Rotated copies and excluding a member with a +//! Shift-click are not covered. use serde::Serialize; use serde_json::{Value, json}; @@ -55,6 +72,9 @@ use super::{CommandSpec, Result, Session, bad, bool_or, cmd, has_doc}; const C: &str = "select.globalEdit"; const OPTIONS: &str = "select.globalEditOptions"; +/// The most objects a Global Edit takes, the selected one included. +pub const MAX_MEMBERS: usize = 10_000; +const UNSUPPORTED: &str = "Global Edit works on paths, compound paths, symbol instances and groups of them"; pub fn specs() -> Vec<CommandSpec> { vec![ @@ -63,7 +83,7 @@ pub fn specs() -> Vec<CommandSpec> { "Start Global Edit", ["Select"], None, - "{appearance?: bool, size?: bool, artboards?: \"all\" | range such as \"1, 3-5\", includeCanvas?: bool} (each defaults to the Global Edit Options) while Global Edit is off: start it on the one selected object, with the objects of the same shape (and, with `appearance`, the same fill and stroke; with `size`, the same width and height) on the artboards given (and, with `includeCanvas`, off every artboard) → {active: true, count, ids}; while on: stop it (Escape does the same) → {active: false}", + "{appearance?: bool, size?: bool, artboards?: \"all\" | range such as \"1, 3-5\", includeCanvas?: bool} (each defaults to the Global Edit Options) while Global Edit is off: start it on the one selected object (a path, compound path, symbol instance or group of them), with the objects of the same shape (for a group: the groups holding objects like its own, at the same places) (and, with `appearance`, the same fill and stroke; with `size`, the same width and height) on the artboards given (and, with `includeCanvas`, off every artboard), at most 10000 → {active: true, count, ids}; while on: stop it (Escape does the same) → {active: false}", can_toggle, toggle ), @@ -144,10 +164,11 @@ pub struct GlobalEdit { } /// An outline reduced to its form: the anchors and handles placed in a unit box, with what tells -/// such outlines apart (kind, fill rule, subpaths and their anchor counts, open or closed). +/// such outlines apart (kind, fill rule, subpaths and their anchor counts, open or closed). A +/// group's is its objects' together, in order. struct Form { tag: Vec<u64>, - symbol: Option<String>, + symbols: Vec<String>, points: Vec<Point>, /// The unit box → the object. frame: Affine, @@ -155,62 +176,110 @@ struct Form { impl Form { fn of(n: &Node) -> Option<Self> { - let mut tag = vec![]; - let mut points = vec![]; - let mut symbol = None; - let mut push = |path: &PathData, tag: &mut Vec<u64>| { - tag.push(path.subpaths.len() as u64); - for sp in &path.subpaths { - tag.extend([u64::from(sp.closed), sp.anchors.len() as u64]); - points.extend(sp.anchors.iter().flat_map(|a| [a.p, a.h_in, a.h_out])); - } - }; - let rule = |r: vectorcraft_geom::FillRule| u64::from(r == vectorcraft_geom::FillRule::EvenOdd); - match &n.kind { - NodeKind::Path { path, rule: r, clipping: false, guide: false, .. } => { - tag.extend([0, rule(*r)]); - push(path, &mut tag); - } - NodeKind::Compound { children, rule: r } => { - tag.extend([1, rule(*r), children.len() as u64]); - for c in children { - push(c.path_data()?, &mut tag); - } - } - NodeKind::SymbolInstance { symbol: s, xf } => { - tag.push(2); - symbol = Some(s.clone()); - points.extend([*xf * Point::ZERO, *xf * Point::new(1.0, 0.0), *xf * Point::new(0.0, 1.0)]); - } - _ => return None, - } - let first = *points.first()?; - let b = points.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p)); + let mut f = Self { tag: vec![], symbols: vec![], points: vec![], frame: Affine::IDENTITY }; + f.add(n, 0)?; + let first = *f.points.first()?; + let b = f.points.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p)); let side = b.width().max(b.height()); if !(side.is_finite() && side > 1e-9) { return None; } - let frame = Affine::translate(b.origin().to_vec2()) * Affine::scale(side); - let back = frame.inverse(); - points.iter_mut().for_each(|p| *p = back * *p); - Some(Self { tag, symbol, points, frame }) + f.frame = Affine::translate(b.origin().to_vec2()) * Affine::scale(side); + let back = f.frame.inverse(); + f.points.iter_mut().for_each(|p| *p = back * *p); + Some(f) + } + + /// Add `n`, `depth` groups down from the selected object; `None` when it isn't supported. + fn add(&mut self, n: &Node, depth: usize) -> Option<()> { + let rule = |r: vectorcraft_geom::FillRule| u64::from(r == vectorcraft_geom::FillRule::EvenOdd); + match &n.kind { + // A clipping path only as part of a (clip) group. + NodeKind::Path { path, rule: r, clipping, guide: false, .. } if !*clipping || depth > 0 => { + self.tag.extend([0, rule(*r), u64::from(*clipping)]); + self.push(path); + } + NodeKind::Compound { children, rule: r } => { + self.tag.extend([1, rule(*r), children.len() as u64]); + for c in children { + self.push(c.path_data()?); + } + } + NodeKind::SymbolInstance { symbol, xf } => { + self.tag.push(2); + self.symbols.push(symbol.clone()); + self.points.extend([*xf * Point::ZERO, *xf * Point::new(1.0, 0.0), *xf * Point::new(0.0, 1.0)]); + } + // Documents are never deeper than `MAX_DEPTH`: the check only bounds the recursion. + NodeKind::Group { children, clip } if plain_group(n) && depth < vectorcraft_doc::MAX_DEPTH => { + self.tag.extend([3, u64::from(*clip), children.len() as u64]); + for c in children { + if c.extras().mask.is_some() { + return None; + } + self.add(c, depth + 1)?; + } + } + _ => return None, + } + Some(()) + } + + fn push(&mut self, path: &PathData) { + self.tag.push(path.subpaths.len() as u64); + for sp in &path.subpaths { + self.tag.extend([u64::from(sp.closed), sp.anchors.len() as u64]); + self.points.extend(sp.anchors.iter().flat_map(|a| [a.p, a.h_in, a.h_out])); + } } fn same(&self, o: &Form) -> bool { self.tag == o.tag - && self.symbol == o.symbol + && self.symbols == o.symbols && self.points.len() == o.points.len() && self.points.iter().zip(&o.points).all(|(a, b)| a.distance(*b) < 1e-6) } } -/// Global Edit supports paths, compound paths and symbol instances; not images, type, linked -/// files, objects with an opacity mask, clipping paths or guides (the help page lists images, -/// text, masks and links as unsupported). +/// Global Edit supports paths, compound paths, symbol instances and groups of them; not images, +/// type, linked files, objects with an opacity mask, clipping paths or guides (the help page lists +/// images, text, masks and links as unsupported). fn supported(n: &Node) -> bool { n.extras().mask.is_none() && Form::of(n).is_some() } +/// A plain group (a clip group too), not one that is live art (a graph, Shaper group, dimension, +/// objects on a path or a tracing). +fn plain_group(n: &Node) -> bool { + let x = n.extras(); + matches!(n.kind, NodeKind::Group { .. }) + && x.graph.is_none() + && x.shaper.is_none() + && x.dimension.is_none() + && x.objects_on_path.is_none() + && x.trace.is_none() +} + +/// Do `a` and `b` show the same fill and stroke, and so does each object in them (groups like each +/// other)? +fn same_look(a: &Node, b: &Node) -> bool { + let (sa, sb) = (stroke_of(a), stroke_of(b)); + super::select::same_paint(&fill_of(a), &fill_of(b), true) + && super::select::same_paint(&sa.0, &sb.0, true) + && close(sa.1, sb.1) + && match (&a.kind, &b.kind) { + (NodeKind::Group { children: x, .. }, NodeKind::Group { children: y, .. }) => x.iter().zip(y).all(|(p, q)| same_look(p, q)), + _ => true, + } +} + +/// Is `n`, or an object in it, among `ids`? +fn holds(n: &Node, ids: &[NodeId]) -> bool { + let mut found = false; + n.walk(&mut |c| found = found || ids.contains(&c.id)); + found +} + fn close(a: f64, b: f64) -> bool { (a - b).abs() <= 1e-6 * a.abs().max(b.abs()).max(1.0) } @@ -224,12 +293,12 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> { let key = d.node(*id).ok_or_else(|| bad(C, "nothing selected"))?; let form = match Form::of(key) { Some(f) if supported(key) => f, - _ => return Err(bad(C, "Global Edit works on paths, compound paths and symbol instances")), + _ => return Err(bad(C, UNSUPPORTED)), }; let symbols = d.symbol_boxes(); let size = |n: &Node| n.geometric_bounds_with(&symbols).map(|b| (b.width(), b.height())); let key_size = size(key); - let (fill, stroke) = (fill_of(key), stroke_of(key)); + let (group, count) = (matches!(key.kind, NodeKind::Group { .. }), key.children().map(Vec::len)); let boards: Option<Vec<Rect>> = match &o.artboards { None => None, Some(r) => Some( @@ -251,30 +320,31 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> { let mut out = vec![(*id, Affine::IDENTITY)]; let back = form.frame.inverse(); super::select::walk_selectable(d, st.isolation, |n| { - if n.id == *id { + if n.id == *id || out.len() >= MAX_MEMBERS { return false; } - match &n.kind { - // Look into layers and plain groups (clip groups too: their art, not their clipping path). + // Look into layers and plain groups (clip groups too: their art, not their clipping path). + let look_in = match &n.kind { NodeKind::Layer { .. } => return true, - NodeKind::Group { .. } => { - let x = n.extras(); - return x.graph.is_none() && x.shaper.is_none() && x.dimension.is_none() && x.objects_on_path.is_none() && x.trace.is_none(); - } - _ => {} - } - if let Some(f) = Form::of(n).filter(|f| f.same(&form) && supported(n)) + NodeKind::Group { .. } if !plain_group(n) => return false, + NodeKind::Group { .. } if !group => return true, + NodeKind::Group { .. } => true, + // Only groups are like a group. + _ if group => return false, + _ => false, + }; + // The object count first: it turns most objects down before their form is made. + if n.children().map(Vec::len) == count + && let Some(f) = Form::of(n).filter(|f| f.same(&form) && supported(n)) && (!o.size || matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2))) - && (!o.appearance || { - let (f2, s2) = (fill_of(n), stroke_of(n)); - super::select::same_paint(&fill, &f2, true) && super::select::same_paint(&stroke.0, &s2.0, true) && close(stroke.1, s2.1) - }) + && (!o.appearance || same_look(key, n)) && in_scope(n) { out.push((n.id, f.frame * back)); + // A group taken is taken whole, as compound paths, symbol instances and the others are. + return false; } - // Compound paths, symbol instances and the other objects are taken whole. - false + look_in }); Ok(out) } @@ -289,7 +359,7 @@ fn can_toggle(s: &Session) -> std::result::Result<(), String> { }; match st.doc.node(*id) { Some(n) if supported(n) => Ok(()), - _ => Err("Global Edit works on paths, compound paths and symbol instances".into()), + _ => Err(UNSUPPORTED.into()), } } @@ -535,36 +605,62 @@ fn renumber(children: &mut [std::sync::Arc<Node>], own: &[NodeId], d: &mut Docum } } +/// Give member `n` what changed from `a` to `b` (the model before and after the edit), with the +/// values of `m` (`b` placed on `n`): in a group that kept its objects (as many, the group still a +/// group of the same kind), each object's change to the shown and unlocked object at its place; +/// otherwise as one object, whose new children keep `n`'s ids in order. +fn give(a: &Node, b: &Node, mut m: Node, n: &mut Node, d: &mut Document) { + let mut changed = Changed::between(a, b); + let len = a.children().map(Vec::len); + let kept = matches!((&a.kind, &b.kind, &n.kind), (NodeKind::Group { clip: x, .. }, NodeKind::Group { clip: y, .. }, NodeKind::Group { .. }) if x == y) + && [b, &m, &*n].iter().all(|x| x.children().map(Vec::len) == len); + if kept { + if let (Some(ac), Some(bc), Some(mc), Some(nc)) = (a.children(), b.children(), m.children(), n.children_mut()) { + for (((p, q), mq), t) in ac.iter().zip(bc).zip(mc).zip(nc.iter_mut()) { + if !std::sync::Arc::ptr_eq(p, q) && t.visible && !t.locked { + give(p, q, (**mq).clone(), std::sync::Arc::make_mut(t), d); + } + } + } + if a.bbox_angle != b.bbox_angle { + n.bbox_angle = m.bbox_angle; + } + changed.outline = false; + } else if changed.outline { + let own: Vec<NodeId> = n.children().map(|c| c.iter().map(|c| c.id).collect()).unwrap_or_default(); + if let Some(ch) = m.children_mut() { + renumber(ch, &own, d); + } + } + changed.apply(m, n); +} + /// After an edit made while Global Edit is on (`before` → `d`): the first member selected before -/// or after the edit that it changed is the model, and every other member that is shown and -/// unlocked gets what changed about it, placed by the members' transforms. → the members it -/// changed so (which [`Session::edit`] checks stay within the canvas, as it checks the selection). +/// or after the edit (or holding an object that is) that it changed is the model, and every other +/// member that is shown and unlocked gets what changed about it, placed by the members' +/// transforms. → the members it changed so (which [`Session::edit`] checks stay within the canvas, +/// as it checks the selection). pub(crate) fn propagate(before: &Document, d: &mut Document, ge: &GlobalEdit, selected: [&[NodeId]; 2]) -> Vec<NodeId> { - let model = ge.members.iter().filter(|(id, _)| selected.iter().any(|s| s.contains(id))).find_map(|(id, xf)| { + let model = ge.members.iter().find_map(|(id, xf)| { let (a, b) = (before.node(*id)?, d.node(*id)?); - if std::ptr::eq(a, b) { + if std::ptr::eq(a, b) || !Changed::between(a, b).any() || !selected.iter().any(|s| holds(a, s) || holds(b, s)) { return None; } - let changed = Changed::between(a, b); - changed.any().then(|| (*id, *xf, changed, b.clone())) + Some((*id, *xf, a, b.clone())) }); - let Some((model_id, model_xf, changed, model)) = model else { return vec![] }; + let Some((model_id, model_xf, was, model)) = model else { return vec![] }; let back = model_xf.inverse(); let mut edited = vec![]; for (id, xf) in &ge.members { if *id == model_id || !editable(d, *id) { continue; } + let Some(mut n) = d.node(*id).cloned() else { continue }; let mut placed = model.clone(); placed.transform(*xf * back, Scaling::default()); - if changed.outline { - let own: Vec<NodeId> = d.node(*id).and_then(Node::children).map(|c| c.iter().map(|c| c.id).collect()).unwrap_or_default(); - if let Some(ch) = placed.children_mut() { - renumber(ch, &own, d); - } - } - if let Some(n) = d.node_mut(*id) { - changed.apply(placed, n); + give(was, &model, placed, &mut n, d); + if let Some(slot) = d.node_mut(*id) { + *slot = n; edited.push(*id); } } @@ -585,9 +681,8 @@ pub fn highlights(s: &Session) -> Outlines { let out: Vec<_> = ge .members .iter() - .filter(|(id, _)| !st.selection.contains(*id)) .filter_map(|(id, _)| { - let n = st.doc.node(*id)?; + let n = st.doc.node(*id).filter(|n| !holds(n, &st.selection.objects))?; let path = match n.stroke_path() { Some(p) => p, None => n.geometric_bounds_with(&symbols)?.to_path(0.1), diff --git a/crates/engine/src/tests/globaledit.rs b/crates/engine/src/tests/globaledit.rs index e6ad7fac96..fe87d57b31 100644 --- a/crates/engine/src/tests/globaledit.rs +++ b/crates/engine/src/tests/globaledit.rs @@ -287,16 +287,16 @@ fn global_edit_needs_one_supported_object() { let e = s.execute("select.globalEdit", &json!({})).unwrap_err().to_string(); assert!(e.contains("no similar objects") && e.contains("rotated"), "{e}"); assert!(s.doc().unwrap().global_edit.is_none()); - // A group of two squares is refused, though another such group exists. + // A group holding type is refused, though another such group exists. let group = |s: &mut Session, x: f64| { - let (p, q) = (rect(s, x, 100.0, 10.0, 10.0), rect(s, x + 20.0, 100.0, 10.0, 10.0)); - sel(s, &[p, q]); - NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()) + let p = rect(s, x, 100.0, 10.0, 10.0); + let t = NodeId(s.execute("text.create", &json!({"x": x, "y": 150, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + group_of(s, &[p, t]) }; let (g, _) = (group(&mut s, 600.0), group(&mut s, 700.0)); sel(&mut s, &[g]); let e = s.execute("select.globalEdit", &json!({})).unwrap_err(); - assert!(matches!(e, EngineError::Disabled(..)) && e.to_string().contains("paths, compound paths and symbol instances"), "{e}"); + assert!(matches!(e, EngineError::Disabled(..)) && e.to_string().contains("symbol instances and groups of them"), "{e}"); } #[test] @@ -443,3 +443,148 @@ fn an_edit_that_takes_a_member_past_the_canvas_is_refused_whole() { s.execute("object.move", &json!({"dx": 3000, "dy": 0})).unwrap(); assert!(close(bounds(&s, big), Rect::new(3.0e6, 0.0, 3.0e6 + 2000.0, 2000.0)), "{:?}", bounds(&s, big)); } + +fn group_of(s: &mut Session, objects: &[NodeId]) -> NodeId { + sel(s, objects); + NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()) +} + +/// A group of a square, a circle and a bar, `k` times the size, at `x` → the group and its objects. +fn card(s: &mut Session, x: f64, k: f64) -> (NodeId, [NodeId; 3]) { + let sq = rect(s, x, 0.0, 40.0 * k, 40.0 * k); + let dot = NodeId( + s.execute("shape.ellipse", &json!({"x": x + 50.0 * k, "y": 0, "width": 40.0 * k, "height": 40.0 * k})).unwrap()["id"].as_u64().unwrap(), + ); + let bar = rect(s, x, 50.0 * k, 90.0 * k, 20.0 * k); + (group_of(s, &[sq, dot, bar]), [sq, dot, bar]) +} + +fn kids(s: &Session, g: NodeId) -> Vec<NodeId> { + node(s, g).children().unwrap().iter().map(|c| c.id).collect() +} + +#[test] +fn start_global_edit_on_a_group_takes_the_groups_like_it() { + let mut s = session(); + let (g, [sq, ..]) = card(&mut s, 0.0, 1.0); + let (copy, _) = card(&mut s, 300.0, 1.0); + let (small, _) = card(&mut s, 500.0, 0.5); + // Two of the three objects; the same three with the bar moved; a lone square like the first. + let (p, q) = (rect(&mut s, 0.0, 300.0, 40.0, 40.0), rect(&mut s, 0.0, 400.0, 90.0, 20.0)); + let pair = group_of(&mut s, &[p, q]); + let (moved, [.., bar]) = card(&mut s, 300.0, 1.0); + sel(&mut s, &[bar]); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + rect(&mut s, 600.0, 300.0, 40.0, 40.0); + assert_eq!(start(&mut s, g, json!({})), [g, copy, small], "not the pair {pair} nor the group with the bar moved {moved}"); + // A group alone among groups of other contents: nothing to edit with it. + sel(&mut s, &[pair]); + s.execute("select.globalEdit", &json!({})).unwrap(); + let e = s.execute("select.globalEdit", &json!({})).unwrap_err().to_string(); + assert!(e.contains("no similar objects"), "{e}"); + // Size leaves out the smaller group; Appearance looks at each object in the groups. + assert_eq!(start(&mut s, g, json!({"size": true})), [g, copy]); + s.execute("select.globalEdit", &json!({})).unwrap(); + sel(&mut s, &[sq]); + s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap(); + sel(&mut s, &[g]); + let e = s.execute("select.globalEdit", &json!({"appearance": true})).unwrap_err().to_string(); + assert!(e.contains("no similar objects"), "the square in the first group has another fill now: {e}"); +} + +#[test] +fn an_edit_inside_one_group_reaches_the_same_object_in_the_others_as_one_undo_step() { + let mut s = session(); + let (g, [sq, dot, bar]) = card(&mut s, 0.0, 1.0); + let (copy, [csq, cdot, cbar]) = card(&mut s, 300.0, 1.0); + let (_, [ssq, sdot, _]) = card(&mut s, 500.0, 0.5); + start(&mut s, g, json!({})); + let before = (*s.doc().unwrap().doc).clone(); + let steps = s.doc().unwrap().history.undo.len(); + let (sq_fill, bar_fill) = (fill(&s, csq), fill(&s, cbar)); + // The circle inside the first group, selected on its own. + sel(&mut s, &[dot]); + assert_eq!(crate::cmd::globaledit::highlights(&s).len(), 2, "the other groups are highlighted, not the one being edited"); + s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap(); + assert_eq!((fill(&s, cdot), fill(&s, sdot)), ("#12ab34".to_string(), "#12ab34".to_string())); + assert_eq!((fill(&s, csq), fill(&s, cbar)), (sq_fill, bar_fill), "the other objects keep theirs"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + // The square's height halved from the top: each copy's in proportion. + sel(&mut s, &[sq]); + s.execute("object.setBounds", &json!({"height": 20, "reference": 0})).unwrap(); + assert!(close(bounds(&s, csq), Rect::new(300.0, 0.0, 340.0, 20.0)), "{:?}", bounds(&s, csq)); + assert!(close(bounds(&s, ssq), Rect::new(500.0, 0.0, 520.0, 10.0)), "{:?}", bounds(&s, ssq)); + assert!(placed(&s, bar, cbar, Affine::translate((300.0, 0.0))), "the bar is left alone"); + assert_eq!(kids(&s, copy), [csq, cdot, cbar], "each object keeps its id"); + s.execute("edit.undo", &json!({})).unwrap(); + crate::tests_large_edits::undo_gives_back(&mut s, &before); +} + +#[test] +fn an_object_added_to_the_group_is_added_to_the_others() { + let mut s = session(); + let (g, [sq, ..]) = card(&mut s, 0.0, 1.0); + let (copy, [csq, ..]) = card(&mut s, 300.0, 1.0); + let (small, _) = card(&mut s, 500.0, 0.5); + start(&mut s, g, json!({})); + sel(&mut s, &[sq]); + let added = s + .edit("add", |d, _| { + let id = d.alloc_id(); + let path = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 80.0, 10.0, 90.0)); + d.insert(Some(g), usize::MAX, Node::path(id, path, vectorcraft_doc::Appearance::default_art())) + .map_err(|e| EngineError::Other(e.to_string())) + }) + .unwrap(); + let (theirs, smalls) = (kids(&s, copy), kids(&s, small)); + assert_eq!((theirs.len(), smalls.len()), (4, 4)); + assert_eq!(theirs.first(), Some(&csq), "the member keeps its own ids in order"); + assert!(placed(&s, added, theirs[3], Affine::translate((300.0, 0.0)))); + assert!(placed(&s, added, smalls[3], Affine::translate((500.0, 0.0)) * Affine::scale(0.5))); +} + +#[test] +fn global_edit_takes_at_most_max_members() { + use crate::cmd::globaledit::MAX_MEMBERS; + let mut s = session(); + let first = s + .edit("many", |d, _| { + let layer = d.default_layer(); + let mut first = None; + for i in 0..MAX_MEMBERS + 5 { + let (x, y) = ((i % 70) as f64 * 10.0, (i / 70 % 50) as f64 * 10.0); + let id = d.alloc_id(); + let path = vectorcraft_geom::shapes::rectangle(Rect::new(x, y, x + 8.0, y + 8.0)); + d.insert(layer, usize::MAX, Node::path(id, path, vectorcraft_doc::Appearance::default_art())) + .map_err(|e| EngineError::Other(e.to_string()))?; + first.get_or_insert(id); + } + first.ok_or_else(|| EngineError::Other("none".into())) + }) + .unwrap(); + assert_eq!(start(&mut s, first, json!({})).len(), MAX_MEMBERS); +} + +#[test] +fn groups_nested_as_deep_as_a_document_allows_are_edited_together() { + let mut s = session(); + let nest = |s: &mut Session, x: f64| { + let inner = rect(s, x, 0.0, 10.0, 10.0); + let side = rect(s, x + 20.0, 0.0, 10.0, 10.0); + let mut top = group_of(s, &[inner, side]); + // Group until the document refuses to go deeper. + for _ in 0..2 * vectorcraft_doc::MAX_DEPTH { + sel(s, &[top]); + match s.execute("object.group", &json!({})) { + Ok(r) => top = NodeId(r["id"].as_u64().unwrap()), + Err(_) => break, + } + } + (top, inner) + }; + let ((g, inner), (other, other_inner)) = (nest(&mut s, 0.0), nest(&mut s, 300.0)); + assert_eq!(start(&mut s, g, json!({})), [g, other]); + sel(&mut s, &[inner]); + s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap(); + assert_eq!(fill(&s, other_inner), "#12ab34"); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index f47d5b7b63..a89d71c136 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5542,6 +5542,7 @@ axis Y Axis Y ос Create New Set Създаване на нов набор Stop Global Edit Край на глобалното редактиране Global Edit Options Опции за глобално редактиране +@msg Global Edit works on paths, compound paths, symbol instances and groups of them Глобалното редактиране работи с пътища, съставни пътища, екземпляри на символи и групи от тях Match Съвпадение On Artboards В работните области All Artboards Всички работни области diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 584d4cf407..e4ab0eac16 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5571,7 +5571,7 @@ axis Y Axis Y osa Include Objects On Canvas Uključi objekte na platnu Result(s): {count} Rezultati: {count} @msg select one object odaberite jedan objekat -@msg Global Edit works on paths, compound paths and symbol instances Globalno uređivanje radi na putanjama, složenim putanjama i instancama simbola +@msg Global Edit works on paths, compound paths, symbol instances and groups of them Globalno uređivanje radi na putanjama, složenim putanjama, instancama simbola i njihovim grupama @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nisu pronađeni slični objekti (rotirane ili zrcaljene kopije se ne podudaraju); promijenite opcije globalnog uređivanja i pokušajte ponovo @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ili raspon poput 1, 3-5, a ne {v} Add to Symbols Dodaj u simbole diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 02c98c1b5c..c4ecf209d7 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5004,7 +5004,7 @@ digits Malayalam Malaiàlam @msg give only one of onto, below and above doneu només un de onto, below i above @msg give the path `id` doneu l’`id` del traçat @msg give the path `id` and the width point `index` doneu el `id` del traçat i l’`index` del punt d’amplada -@msg Global Edit works on paths, compound paths and symbol instances L’edició global funciona amb traçats, traçats compostos i instàncies de símbol +@msg Global Edit works on paths, compound paths, symbol instances and groups of them L’edició global funciona amb traçats, traçats compostos, instàncies de símbol i grups d’aquests objectes @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it el degradat «{name}» no està definit al fitxer: en lloc seu es fa servir un color pla @msg group must be true or false group ha de ser true o false @msg guides are locked les guies estan bloquejades diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 2f21d51d86..dbbae87849 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5643,7 +5643,7 @@ axis Y Axis osa Y Include Objects On Canvas Zahrnout objekty na plátně Result(s): {count} Výsledky: {count} @msg select one object vyberte jeden objekt -@msg Global Edit works on paths, compound paths and symbol instances Globální úpravy pracují s cestami, složenými cestami a instancemi symbolů +@msg Global Edit works on paths, compound paths, symbol instances and groups of them Globální úpravy pracují s cestami, složenými cestami, instancemi symbolů a jejich skupinami @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nebyly nalezeny žádné podobné objekty (otočené a zrcadlené kopie se nevyhledávají); změňte možnosti globálních úprav a zkuste to znovu @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all nebo rozsah, například 1, 3-5, ne {v} Add to Symbols Přidat do symbolů diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index df8c467e15..21f9192ba8 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5557,6 +5557,7 @@ axis Y Axis Y-akse Create New Set Opret nyt sæt Stop Global Edit Stop global redigering Global Edit Options Indstillinger for global redigering +@msg Global Edit works on paths, compound paths, symbol instances and groups of them Global redigering virker på stier, sammensatte stier, symbolforekomster og grupper af dem Match Match On Artboards På tegneflader All Artboards Alle tegneflader diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 95439eea61..503a545858 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5224,7 +5224,7 @@ axis Y Axis Y-Achse Include Objects On Canvas Objekte auf der Leinwand einschließen Result(s): {count} Ergebnis(se): {count} @msg select one object wählen Sie ein Objekt aus -@msg Global Edit works on paths, compound paths and symbol instances Globale Bearbeitung funktioniert mit Pfaden, zusammengesetzten Pfaden und Symbolinstanzen +@msg Global Edit works on paths, compound paths, symbol instances and groups of them Globale Bearbeitung funktioniert mit Pfaden, zusammengesetzten Pfaden, Symbolinstanzen und Gruppen daraus @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again keine ähnlichen Objekte gefunden (gedrehte oder gespiegelte Kopien werden nicht erkannt); ändern Sie die Optionen für globale Bearbeitung und versuchen Sie es erneut @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all oder ein Bereich wie 1, 3-5, nicht {v} Add to Symbols Zu Symbolen hinzufügen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 91f441adaa..887bfe7d43 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5594,7 +5594,7 @@ axis Y Axis Άξονας Y Include Objects On Canvas Συμπερίληψη αντικειμένων στον καμβά Result(s): {count} Αποτέλεσμα(τα): {count} @msg select one object επιλέξτε ένα αντικείμενο -@msg Global Edit works on paths, compound paths and symbol instances Η καθολική επεξεργασία λειτουργεί σε διαδρομές, σύνθετες διαδρομές και παρουσίες συμβόλων +@msg Global Edit works on paths, compound paths, symbol instances and groups of them Η καθολική επεξεργασία λειτουργεί σε διαδρομές, σύνθετες διαδρομές, παρουσίες συμβόλων και ομάδες τους @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again δεν βρέθηκαν παρόμοια αντικείμενα (τα περιστραμμένα ή κατοπτρισμένα αντίγραφα δεν εντοπίζονται)· αλλάξτε τις επιλογές καθολικής επεξεργασίας και δοκιμάστε ξανά @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ή ένα εύρος όπως 1, 3-5, όχι {v} Add to Symbols Προσθήκη στα σύμβολα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 8fe2d8401f..78e3a7ce57 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5584,7 +5584,7 @@ axis Y Axis Eje Y Include Objects On Canvas Incluir objetos en el lienzo Result(s): {count} Resultado(s): {count} @msg select one object seleccione un objeto -@msg Global Edit works on paths, compound paths and symbol instances La edición global funciona con trazados, trazados compuestos e instancias de símbolos +@msg Global Edit works on paths, compound paths, symbol instances and groups of them La edición global funciona con trazados, trazados compuestos, instancias de símbolos y grupos de ellos @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again no se encontraron objetos similares (las copias giradas o reflejadas no coinciden); cambie las opciones de edición global e inténtelo de nuevo @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all o un intervalo como 1, 3-5, no {v} Add to Symbols Agregar a símbolos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 5fbec069ad..ca6db15365 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5673,7 +5673,7 @@ axis Y Axis Y-akseli Include Objects On Canvas Sisällytä kankaalla olevat objektit Result(s): {count} Tulokset: {count} @msg select one object valitse yksi objekti -@msg Global Edit works on paths, compound paths and symbol instances Yleismuokkaus toimii poluille, yhdistelmäpoluille ja symbolien esiintymille +@msg Global Edit works on paths, compound paths, symbol instances and groups of them Yleismuokkaus toimii poluille, yhdistelmäpoluille, symbolien esiintymille ja niiden ryhmille @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again samankaltaisia objekteja ei löytynyt (kierrettyjä tai peilattuja kopioita ei tunnisteta); muuta yleismuokkauksen asetuksia ja yritä uudelleen @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all tai alue, kuten 1, 3-5, ei {v} Add to Symbols Lisää symboleihin diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index d6ec59b6cd..0102a7ad70 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5640,7 +5640,7 @@ axis Y Axis Axe Y Include Objects On Canvas Inclure les objets sur la toile Result(s): {count} Résultat(s) : {count} @msg select one object sélectionnez un seul objet -@msg Global Edit works on paths, compound paths and symbol instances La modification globale s’applique aux tracés, aux tracés transparents et aux occurrences de symboles +@msg Global Edit works on paths, compound paths, symbol instances and groups of them La modification globale s’applique aux tracés, aux tracés transparents, aux occurrences de symboles et aux groupes de ces objets @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again aucun objet similaire trouvé (les copies pivotées ou symétriques ne sont pas reconnues) ; modifiez les options de modification globale et réessayez @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards` : all ou une plage telle que 1, 3-5, et non {v} Add to Symbols Ajouter aux symboles diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index fe56efa822..ce55ee09d4 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5628,7 +5628,7 @@ axis Y Axis Y tengely Include Objects On Canvas Vásznon lévő objektumok is Result(s): {count} Eredmény(ek): {count} @msg select one object jelöljön ki egy objektumot -@msg Global Edit works on paths, compound paths and symbol instances A globális szerkesztés útvonalakon, összetett útvonalakon és szimbólumpéldányokon működik +@msg Global Edit works on paths, compound paths, symbol instances and groups of them A globális szerkesztés útvonalakon, összetett útvonalakon, szimbólumpéldányokon és ezek csoportjain működik @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nem található hasonló objektum (az elforgatott vagy tükrözött másolatok nem számítanak egyezésnek); módosítsa a globális szerkesztés beállításait, és próbálja újra @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all vagy egy tartomány, például 1, 3-5, nem {v} Add to Symbols Hozzáadás a szimbólumokhoz diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index a37491b992..f111cc213c 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5557,6 +5557,7 @@ axis Y Axis Sumbu Y Create New Set Buat set baru Stop Global Edit Hentikan edit global Global Edit Options Opsi edit global +@msg Global Edit works on paths, compound paths, symbol instances and groups of them Edit global berfungsi pada jalur, jalur gabungan, instans simbol, dan grupnya Match Cocokkan On Artboards Di artboard All Artboards Semua artboard diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index dbf755d31d..d01f8ebad8 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5258,7 +5258,7 @@ axis Y Axis Asse Y Include Objects On Canvas Includi oggetti sulla tela Result(s): {count} Risultati: {count} @msg select one object selezionate un oggetto -@msg Global Edit works on paths, compound paths and symbol instances La modifica globale funziona su tracciati, tracciati composti e istanze di simboli +@msg Global Edit works on paths, compound paths, symbol instances and groups of them La modifica globale funziona su tracciati, tracciati composti, istanze di simboli e gruppi di essi @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nessun oggetto simile trovato (le copie ruotate o riflesse non vengono riconosciute); cambiate le opzioni di modifica globale e riprovate @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all o un intervallo come 1, 3-5, non {v} Add to Symbols Aggiungi ai simboli diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 54e53749be..f1738d56b2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5325,7 +5325,7 @@ axis Y Axis Y 軸 Include Objects On Canvas カンバス上のオブジェクトを含める Result(s): {count} 結果: {count} @msg select one object オブジェクトを 1 つ選択してください -@msg Global Edit works on paths, compound paths and symbol instances グローバル編集はパス、複合パス、シンボルインスタンスに使用できます +@msg Global Edit works on paths, compound paths, symbol instances and groups of them グローバル編集はパス、複合パス、シンボルインスタンスとそれらのグループに使用できます @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again 類似するオブジェクトが見つかりません(回転または反転したコピーは一致しません)。グローバル編集オプションを変更してもう一度試してください @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all または 1, 3-5 のような範囲を指定してください ({v} ではなく) Add to Symbols シンボルに追加 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a5f844aba6..5ea64087e7 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5558,7 +5558,7 @@ axis Y Axis Y ღერძი Include Objects On Canvas ტილოზე არსებული ობიექტების გათვალისწინება Result(s): {count} შედეგი: {count} @msg select one object მონიშნეთ ერთი ობიექტი -@msg Global Edit works on paths, compound paths and symbol instances გლობალური რედაქტირება მუშაობს ტრაექტორიებზე, შედგენილ ტრაექტორიებსა და სიმბოლოს ეგზემპლარებზე +@msg Global Edit works on paths, compound paths, symbol instances and groups of them გლობალური რედაქტირება მუშაობს ტრაექტორიებზე, შედგენილ ტრაექტორიებზე, სიმბოლოს ეგზემპლარებსა და მათ ჯგუფებზე @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again მსგავსი ობიექტები ვერ მოიძებნა (შემობრუნებული ან არეკლილი ასლები არ ემთხვევა); შეცვალეთ გლობალური რედაქტირების პარამეტრები და სცადეთ ხელახლა @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ან დიაპაზონი, მაგალითად 1, 3-5, და არა {v} Add to Symbols სიმბოლოებში დამატება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 5dd77eaba7..880456dee5 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5221,7 +5221,7 @@ axis Y Axis Y축 Include Objects On Canvas 캔버스의 개체 포함 Result(s): {count} 결과: {count} @msg select one object 개체 하나를 선택하십시오 -@msg Global Edit works on paths, compound paths and symbol instances 전체 편집은 패스, 컴파운드 패스, 심볼 인스턴스에서 작동합니다 +@msg Global Edit works on paths, compound paths, symbol instances and groups of them 전체 편집은 패스, 컴파운드 패스, 심볼 인스턴스 및 이들의 그룹에서 작동합니다 @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again 유사한 개체를 찾을 수 없습니다(회전하거나 반사한 복사본은 일치하지 않습니다). 전체 편집 옵션을 변경한 후 다시 시도하십시오 @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all 또는 1, 3-5 같은 범위여야 합니다({v}이(가) 아님) Add to Symbols 심볼에 추가 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 4c60e73589..0d1fe8b2e9 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5601,6 +5601,7 @@ axis Y Axis Y-as Create New Set Nieuwe set maken Stop Global Edit Globale bewerking stoppen Global Edit Options Opties voor globale bewerking +@msg Global Edit works on paths, compound paths, symbol instances and groups of them Globale bewerking werkt op paden, samengestelde paden, symboolinstanties en groepen daarvan Match Overeenkomst On Artboards Op tekengebieden All Artboards Alle tekengebieden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 593f7d2ab3..5fb2f16f10 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5496,7 +5496,7 @@ axis Y Axis Oś Y Include Objects On Canvas Uwzględnij obiekty na płótnie Result(s): {count} Wyniki: {count} @msg select one object zaznacz jeden obiekt -@msg Global Edit works on paths, compound paths and symbol instances Edycja globalna działa na ścieżkach, ścieżkach złożonych i wystąpieniach symboli +@msg Global Edit works on paths, compound paths, symbol instances and groups of them Edycja globalna działa na ścieżkach, ścieżkach złożonych, wystąpieniach symboli i ich grupach @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nie znaleziono podobnych obiektów (obrócone i odbite kopie nie są dopasowywane); zmień opcje edycji globalnej i spróbuj ponownie @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all lub zakres, np. 1, 3-5, a nie {v} Add to Symbols Dodaj do symboli diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e6e4599be4..8cefbc8d39 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5559,7 +5559,7 @@ axis Y Axis Eixo Y Include Objects On Canvas Incluir Objetos na Tela Result(s): {count} Resultado(s): {count} @msg select one object selecione um objeto -@msg Global Edit works on paths, compound paths and symbol instances A edição global funciona com demarcadores, demarcadores compostos e instâncias de símbolos +@msg Global Edit works on paths, compound paths, symbol instances and groups of them A edição global funciona com demarcadores, demarcadores compostos, instâncias de símbolos e grupos deles @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nenhum objeto semelhante encontrado (cópias giradas ou refletidas não são correspondidas); altere as opções de edição global e tente novamente @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ou um intervalo como 1, 3-5, não {v} Add to Symbols Adicionar aos Símbolos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index fa9e68b5d7..900f2361fd 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5254,7 +5254,7 @@ axis Y Axis Ось Y Include Objects On Canvas Включать объекты на холсте Result(s): {count} Результаты: {count} @msg select one object выберите один объект -@msg Global Edit works on paths, compound paths and symbol instances Глобальное редактирование работает с контурами, составными контурами и экземплярами символов +@msg Global Edit works on paths, compound paths, symbol instances and groups of them Глобальное редактирование работает с контурами, составными контурами, экземплярами символов и их группами @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again похожие объекты не найдены (повёрнутые или отражённые копии не учитываются); измените параметры глобального редактирования и повторите попытку @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all или диапазон, например 1, 3-5, а не {v} Add to Symbols Добавить в символы diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 23aa4028ba..ef1a8500ae 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5666,7 +5666,7 @@ axis Y Axis Y-axel Include Objects On Canvas Ta med objekt på arbetsytan Result(s): {count} Resultat: {count} @msg select one object markera ett objekt -@msg Global Edit works on paths, compound paths and symbol instances Global redigering fungerar på banor, sammansatta banor och symbolinstanser +@msg Global Edit works on paths, compound paths, symbol instances and groups of them Global redigering fungerar på banor, sammansatta banor, symbolinstanser och grupper av dem @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again inga liknande objekt hittades (roterade eller speglade kopior matchas inte); ändra alternativen för global redigering och försök igen @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all eller ett intervall som 1, 3-5, inte {v} Add to Symbols Lägg till i symboler diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c9a3175cb3..c4980e5e5c 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5600,7 +5600,7 @@ axis Y Axis Y ekseni Include Objects On Canvas Tuvaldeki Nesneleri Dahil Et Result(s): {count} Sonuç(lar): {count} @msg select one object bir nesne seçin -@msg Global Edit works on paths, compound paths and symbol instances Genel düzenleme yollar, bileşik yollar ve sembol örnekleri üzerinde çalışır +@msg Global Edit works on paths, compound paths, symbol instances and groups of them Genel düzenleme yollar, bileşik yollar, sembol örnekleri ve bunların grupları üzerinde çalışır @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again benzer nesne bulunamadı (döndürülmüş veya yansıtılmış kopyalar eşleşmez); Genel Düzenleme Seçeneklerini değiştirip yeniden deneyin @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ya da 1, 3-5 gibi bir aralık olmalı, {v} değil Add to Symbols Sembollere Ekle diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 39303f0a2f..daee9a6d5f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5238,7 +5238,7 @@ axis Y Axis Вісь Y Include Objects On Canvas Включати об’єкти на полотні Result(s): {count} Результати: {count} @msg select one object виберіть один об’єкт -@msg Global Edit works on paths, compound paths and symbol instances Глобальне редагування працює з контурами, складеними контурами та екземплярами символів +@msg Global Edit works on paths, compound paths, symbol instances and groups of them Глобальне редагування працює з контурами, складеними контурами, екземплярами символів та їхніми групами @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again схожих об’єктів не знайдено (повернуті чи віддзеркалені копії не враховуються); змініть параметри глобального редагування та спробуйте ще раз @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all або діапазон, наприклад 1, 3-5, а не {v} Add to Symbols Додати до символів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index bc4d856aa9..ab2dd4721c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5241,7 +5241,7 @@ axis Y Axis Trục Y Include Objects On Canvas Bao gồm đối tượng trên vùng vẽ Result(s): {count} Kết quả: {count} @msg select one object hãy chọn một đối tượng -@msg Global Edit works on paths, compound paths and symbol instances Chỉnh sửa toàn cục hoạt động trên đường dẫn, đường dẫn phức hợp và phiên bản biểu tượng +@msg Global Edit works on paths, compound paths, symbol instances and groups of them Chỉnh sửa toàn cục hoạt động trên đường dẫn, đường dẫn phức hợp, phiên bản biểu tượng và nhóm của chúng @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again không tìm thấy đối tượng tương tự (các bản sao đã xoay hoặc lật không được tính); hãy thay đổi tùy chọn chỉnh sửa toàn cục rồi thử lại @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all hoặc một phạm vi như 1, 3-5, không phải {v} Add to Symbols Thêm vào ký hiệu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 00839e4ef7..58efd43a34 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5482,7 +5482,7 @@ axis Y Axis Y 轴 Include Objects On Canvas 包括画布上的对象 Result(s): {count} 结果:{count} @msg select one object 请选择一个对象 -@msg Global Edit works on paths, compound paths and symbol instances 全局编辑适用于路径、复合路径和符号实例 +@msg Global Edit works on paths, compound paths, symbol instances and groups of them 全局编辑适用于路径、复合路径、符号实例及其编组 @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again 未找到相似对象(旋转或镜像的副本不会匹配);请更改全局编辑选项后重试 @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`:应为 all 或 1, 3-5 这样的范围,而不是 {v} Add to Symbols 添加到符号 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1385a52c7e..1067a2ec21 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5278,7 +5278,7 @@ axis Y Axis Y 軸 Include Objects On Canvas 包含畫布上的物件 Result(s): {count} 結果:{count} @msg select one object 請選取一個物件 -@msg Global Edit works on paths, compound paths and symbol instances 整體編輯適用於路徑、複合路徑和符號實體 +@msg Global Edit works on paths, compound paths, symbol instances and groups of them 整體編輯適用於路徑、複合路徑、符號實體及其群組 @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again 找不到相似的物件(旋轉或鏡像的副本不會相符);請變更整體編輯選項後再試一次 @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`:應為 all 或 1, 3-5 這類範圍,而不是 {v} Add to Symbols 新增至符號 diff --git a/docs/gaps.md b/docs/gaps.md index 072ee477a3..9b93120bed 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G4: PDF import finds installed fonts whose PDF names hold hyphens or a composite font's CMap; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (G5: Start Global Edit on groups, #4939; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -517,7 +517,9 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall Color eyedropper for scatter, art and pattern brushes (Hue Shift colorization; samples canvas art); Select › Start Global Edit (#3521) on paths, compound paths and symbol instances: the objects of the same shape at any place and size, narrowed by Appearance, Size and the artboards to search, take an edit of any one of - them in proportion, as one undo step ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)). + them in proportion, as one undo step ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)); + on a group (#4939), the groups like it (the same objects at the same places, moved or scaled) take an edit + made to an object inside it at the object in the same place ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)). Color eyedropper for scatter, art and pattern brushes (Hue Shift colorization; samples canvas art); symbol libraries ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own (one original library generated in code, @@ -537,9 +539,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall as a `.vectorcraft` library into the user library folder (listed under User Defined) or a file (`brush.libraries`, `brush.addFromLibrary`, `brush.saveLibrary`, `brush.loadLibrary`). - **Missing:** the Art brush's Overlap; more built-in brush, symbol and graphic-style libraries (original, - generated in code, never Adobe's); dynamic symbols; Global Edit of similar groups (edits to an object inside a - group reaching the matching objects of similar groups, [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)), - rotated copies as matches, Shift-click to leave a match out and highlighting matches before the start; + generated in code, never Adobe's); dynamic symbols; Global Edit of groups holding type or + images, rotated copies as matches, Shift-click to leave a match out and highlighting matches before the start; drawing the 9-slice guides on the canvas in symbol edit mode and scaling by them. - **Estimate:** 15–26 h. @@ -676,6 +677,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | G5: Select › Start Global Edit on a group takes the groups like it (the same objects at the same places, moved or scaled; Appearance, Size and the artboard options apply) and gives an edit made to an object inside one to the object at its place in each of the others, in proportion, as one undo step (#4939); rotated copies and Shift-click exclusion remain. Estimate unchanged. | | 2026-10-31 | minor | G4: PDF import finds an installed font whose PDF name holds hyphens (`Noto-Sans-Bold` is Noto Sans, Bold: the longest part before a hyphen that names an installed family) and a composite font by its CIDFont's name rather than its base name, which ends in the CMap's (`Name-Identity-H`, [ISO 32000-1 §9.7.6.1](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)); a missing font is split only before a style part (`Helvetica-BoldOblique`), so it is reported as `MS PGothic`, not `MS`. Estimate unchanged. | | 2026-10-31 | minor | G13: Direct Selection snaps the end of an existing straight line, dragged by its end anchor, square to straight paths and grazing curves (Smart Guides › Geometric Guides: Snap to Perpendicular and Snap to Tangent), the case the public Snap to Perpendicular and Snap to Tangent pages add to drawing with the Line Segment and Pen tools (#2530). Scores and estimates unchanged. | | 2026-10-31 | minor | G8: a gradient mesh read from a file is budgeted: at most about a million quads per tessellation, and a mesh with more patches than that is malformed (#3592); estimate unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 4c893cff82..c6bbae8f61 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1450,22 +1450,28 @@ nearest to the pointer. Select › Start Global Edit is `select.globalEdit {appearance?, size?, artboards?, includeCanvas?}`. With one path, compound path or symbol instance selected, it finds the objects of the same shape (moved or scaled copies; not rotated -ones), among those `select.all` would take and the objects in their groups, and returns -`{active: true, count, ids}`, the selected object first. `appearance` also asks for the same fill and stroke, `size` -for the same width and height; `artboards` is `"all"` or a range such as `"1, 3-5"`, and `includeCanvas: false` -leaves out the objects on no artboard. Missing params come from `select.globalEditOptions` (the Global Edit Options, -kept for the session; it returns them with `count`, the objects a start would take now). The selection stays the -one object. Until the next `select.globalEdit` (Stop Global Edit, `{active: false}`), what an edit of a selected match -changed is given to the other matches, in the same undo step, and nothing else. A changed outline or anchors go to -each match in proportion to its size. A changed opacity or blending, and each changed setting of a fill or stroke -(paint, weight, opacity, blending, effects…), are copied as they are to the match's fill or stroke of the same kind -and rank; its other fills and strokes, and their unchanged settings, stay its own (a stroke weight change leaves the -fills). A stroke weight set on the selected match is given as it is, and resizing the outline in proportion never -scales a match's stroke weight. Hidden or locked matches are left as they are. A fill or stroke added or removed is -added or removed on the matches whose fills and strokes lay in the same order; the others, and any other change to the -list, take the whole list. Whenever the document is put back (Undo, Redo, a cancelled drag or scrub), the matches it no -longer has leave the Global Edit, which ends when fewer than two are left. An edit that would take any match past the -canvas fails with the coordinates-out-of-range error and changes nothing. Nothing of it is saved. +ones), among those `select.all` would take and the objects in their groups, and returns `{active: true, count, ids}`, +the selected object first (at most 10,000). With a group of such objects selected (nested groups and clipping paths +included; not type or images), it finds the groups like it: as many objects, in the same order, each of the same +shape, lying the same way relative to each other (the group moved or scaled as a whole). `appearance` also asks for +the same fill and stroke (for groups, of each object in them), `size` for the same width and height; `artboards` is +`"all"` or a range such as `"1, 3-5"`, and `includeCanvas: false` leaves out the objects on no artboard. Missing +params come from `select.globalEditOptions` (the Global Edit Options, kept for the session; it returns them with +`count`, the objects a start would take now). The selection stays the one object. Until the next `select.globalEdit` +(Stop Global Edit, `{active: false}`), what an edit of a selected match changed is given to the other matches, in the +same undo step, and nothing else. A changed outline or anchors go to each match in proportion to its size. A changed +opacity or blending, and each changed setting of a fill or stroke (paint, weight, opacity, blending, effects…), are +copied as they are to the match's fill or stroke of the same kind and rank; its other fills and strokes, and their +unchanged settings, stay its own (a stroke weight change leaves the fills). A stroke weight set on the selected match +is given as it is, and resizing the outline in proportion never scales a match's stroke weight. Hidden or locked +matches are left as they are. A fill or stroke added or removed is added or removed on the matches whose fills and +strokes lay in the same order; the others, and any other change to the list, take the whole list. In groups, an edit +made to an object inside one of them (selected on its own) is given by the same rules to the object at its place in +each of the others, whose hidden or locked objects are left as they are; when the group gains or loses objects, each +other group takes its objects at that level, keeping its own ids in order. Whenever the document is put back (Undo, +Redo, a cancelled drag or scrub), the matches it no longer has leave the Global Edit, which ends when fewer than two +are left. An edit that would take any match past the canvas fails with the coordinates-out-of-range error and changes +nothing. Nothing of it is saved. ## Saved selections diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8e145f25aa..51d9dd20dd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Document Tools add-on: New Symbols from Layers, #4927; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Start Global Edit on groups, #4939; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -120,7 +120,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Area | Weight | Done | Main gaps | One agent (h) | Kind | |---|---:|---:|---|---:|---| -| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521); the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of similar groups and excluding a match with Shift-click, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | +| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939); the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies and excluding a match with Shift-click, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | 30.0's gradient additions are done (dither, perceptual blending, presets); freeform and mixed spot/process gradients in SVG/PDF | 4–7 | estimated; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged | @@ -129,7 +129,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, dynamic symbols, more built-in symbol libraries, Global Edit of similar groups, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guide settings (stored, not drawn) are done | 5–9 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, dynamic symbols, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guide settings (stored, not drawn) are done | 5–9 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, dynamic symbols, symbol libraries, Start Global Edit, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guide settings (stored, not drawn) are done | 5–9 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged) | @@ -140,7 +140,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Type core | 9 | 80% | Auto-leading style resets are implemented; remaining: hyphenation and justification options, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; colour emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; scores and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Raster effects (Effect Gallery) | 4 | 52% | the Effect Gallery's filter thumbnails and in-dialog preview area ([Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html)) | 1–2 | estimated (raised from 49%: the Effect Gallery shipped, #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `dialogs::effect_gallery::tests::stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; depth estimated | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, dynamic symbols, more built-in symbol libraries, Global Edit of similar groups, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration and Export Type (Graphic / Movie Clip) are done | 5–9 | estimated | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, dynamic symbols, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration and Export Type (Graphic / Movie Clip) are done | 5–9 | estimated | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers panel row context menus and Collect for Export (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated; document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | @@ -1419,6 +1419,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Selection: Select › Start Global Edit on a group takes the groups like it (the same objects at the same places, moved or scaled; Appearance, Size and the artboard options apply) and gives an edit made to an object inside one to the object at its place in each of the others, in proportion, as one undo step (#4939); Global Edit of rotated copies and Shift-click exclusion remain. Score unchanged at 85% (estimated), hours unchanged. | | 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): New Symbols from Layers (#4927); evidence added; scores unchanged. | | 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): Save a Timestamped Copy (#4926); evidence added; scores unchanged. | | 2026-11-01 | minor | Path Precision Tools add-on (a VectorCraft addition): Divide into Dashes (#4950); evidence added; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e05eeafa8c..9b4a0460a2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Document Tools add-on: New Symbols from Layers, #4927) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Start Global Edit on groups, #4939) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -296,7 +296,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Actions panel: a clicked action stays selected for Play Current Selection and Delete Selection | partial | #1853 (part of #1629); editing actions and action shortcuts remain | | Actions panel: Create New Set (bottom bar, ≡ › New Set…) names a new set and Set Options… renames the current one; a click on a set's name makes it current and a recording goes into the current set ([helpx: Automation with actions](https://helpx.adobe.com/illustrator/using/automation-actions.html)) | partial | #3712; the New Action dialog (name, set menu, shortcut, colour), dragging actions between sets and deleting a set remain | | Properties panel per context (every selection type's Quick Actions) | partial | one clip group: Edit Clipping Path and Edit Contents, at the top of the panel rather than in Quick Actions (G1); the overview's additional controls ([Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html)): Blend Options (one blend selected, with any tool, #4817) and Merge Live Paint (a Live Paint group with more) in Quick Actions, the Width Profile list (Width tool or a variable-width stroke) and an applied effect's Delete icon in Appearance, Corner and Corner Radius for corners selected with Direct Selection; Variable Font was already there | -| Select › Start Global Edit / Stop Global Edit; Properties › Quick Actions with the Global Edit Options popover (Match: Appearance, Size; On Artboards: All Artboards or a range, Include Objects On Canvas; Result(s)); Escape stops it; the matched objects are highlighted in their layer colour while it runs | partial | #3521, `select.globalEdit` / `select.globalEditOptions`, `crates/engine/src/tests/globaledit.rs`; paths, compound paths and symbol instances; the Control panel's copy of the options, Shift-click to leave a match out, highlighting matches before the start and similar groups remain ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)) | +| Select › Start Global Edit / Stop Global Edit; Properties › Quick Actions with the Global Edit Options popover (Match: Appearance, Size; On Artboards: All Artboards or a range, Include Objects On Canvas; Result(s)); Escape stops it; the matched objects are highlighted in their layer colour while it runs | partial | #3521, `select.globalEdit` / `select.globalEditOptions`, `crates/engine/src/tests/globaledit.rs`; paths, compound paths, symbol instances and groups of them (similar groups, #4939: edits inside one group reach the same object in the others; [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)); the Control panel's copy of the options, Shift-click to leave a match out, rotated copies and highlighting matches before the start remain ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)) | | Contextual task bar | done | | | Control bar with Transform and Stroke popovers | done | | | Pathfinder shape results keep their source names and SVG IDs | done | #1293; Minus Front keeps the back name, Minus Back the front name; Unite/Intersect/Exclude use the backmost named input; compound output carries it once; geometry and paint unchanged | @@ -385,6 +385,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Select › Start Global Edit on a group takes the groups like it (the same objects at the same places, moved or scaled; Appearance, Size and the artboard options apply) and gives an edit made to an object inside one to the object at its place in each of the others, in proportion, as one undo step (#4939). Scores and estimates unchanged | | 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): New Symbols from Layers and Convert Layers to Symbols (#4927); scores and estimates unchanged | | 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): Save a Timestamped Copy (#4926); scores and estimates unchanged | | 2026-11-01 | minor | Path Precision Tools add-on (a VectorCraft addition): Divide into Dashes (#4950); scores and estimates unchanged | From 8c35bacfb3a10f6899e613008806fa3640d83346 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 03:28:49 +0700 Subject: [PATCH 175/260] Global Edit: the menu checks a selected group's kind only; its contents are checked on start --- crates/engine/src/cmd/globaledit.rs | 3 +++ crates/engine/src/tests/globaledit.rs | 4 +++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index fe18309463..6ff31dabea 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -357,7 +357,10 @@ fn can_toggle(s: &Session) -> std::result::Result<(), String> { let [id] = st.selection.objects.as_slice() else { return Err(if st.selection.is_empty() { "nothing selected" } else { "select one object" }.into()); }; + // A group's contents are checked when Global Edit starts: building its shape here would walk + // every object in it each time the menu or the Properties panel asks. match st.doc.node(*id) { + Some(n) if n.extras().mask.is_none() && plain_group(n) => Ok(()), Some(n) if supported(n) => Ok(()), _ => Err(UNSUPPORTED.into()), } diff --git a/crates/engine/src/tests/globaledit.rs b/crates/engine/src/tests/globaledit.rs index fe87d57b31..aeb426ac45 100644 --- a/crates/engine/src/tests/globaledit.rs +++ b/crates/engine/src/tests/globaledit.rs @@ -295,8 +295,10 @@ fn global_edit_needs_one_supported_object() { }; let (g, _) = (group(&mut s, 600.0), group(&mut s, 700.0)); sel(&mut s, &[g]); + // The menu only checks that it is a group; starting refuses its contents. let e = s.execute("select.globalEdit", &json!({})).unwrap_err(); - assert!(matches!(e, EngineError::Disabled(..)) && e.to_string().contains("symbol instances and groups of them"), "{e}"); + assert!(e.to_string().contains("symbol instances and groups of them"), "{e}"); + assert!(s.doc().unwrap().global_edit.is_none()); } #[test] From 9c17301c464e7e1f43a97e11a16f6d17cbf5eba1 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 04:11:00 +0700 Subject: [PATCH 176/260] Fix #4937: artboards can have a background fill, included in exports and print --- crates/doc/src/artboard.rs | 35 ++++- crates/doc/src/tests.rs | 23 +++ crates/engine/src/cmd/fileio.rs | 3 + crates/engine/src/cmd/fileio/commands.rs | 6 +- crates/engine/src/cmd/fileio/encode.rs | 3 + crates/engine/src/cmd/fileio/eps.rs | 3 + crates/engine/src/cmd/fileio/export.rs | 15 ++ crates/engine/src/cmd/fileio/pdf.rs | 4 + crates/engine/src/cmd/fileio/screens.rs | 15 +- crates/engine/src/cmd/fileio/svg.rs | 4 +- .../src/cmd/fileio/tests_artboard_fill.rs | 134 ++++++++++++++++++ crates/engine/src/cmd/print.rs | 6 +- crates/mcp/src/headless.rs | 2 +- .../ui-egui/src/dialogs/export_for_screens.rs | 19 ++- crates/ui-egui/src/dialogs/print.rs | 3 +- crates/ui-egui/src/dialogs/tests_screens.rs | 26 ++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + 42 files changed, 309 insertions(+), 18 deletions(-) create mode 100644 crates/engine/src/cmd/fileio/tests_artboard_fill.rs diff --git a/crates/doc/src/artboard.rs b/crates/doc/src/artboard.rs index b78b8eb014..6d5d50d4d4 100644 --- a/crates/doc/src/artboard.rs +++ b/crates/doc/src/artboard.rs @@ -35,8 +35,8 @@ pub struct Artboard { pub video_ruler_pixel_aspect_ratio: f64, /// Background color (Properties › Artboards › Fill, Artboard Options). The canvas draws the /// artboard's paper in it, multiplied with the Simulate Colored Paper color while that is on; - /// without one the paper is white, or the Simulate Colored Paper color. Exports and print leave - /// it out. + /// without one the paper is white, or the Simulate Colored Paper color. Exports and print draw + /// it behind the art ([`super::Document::with_artboard_fills`]). #[serde(default, skip_serializing_if = "Option::is_none")] pub color: Option<vectorcraft_color::Color>, } @@ -77,6 +77,37 @@ impl Artboard { } } +impl super::Document { + /// A copy for output with the background colors ([`Artboard::color`]) of the artboards at + /// `indices` drawn behind all the art: each a rectangle of its artboard filled with its color + /// (in the color's own model), on a layer of their own (Artboard Fill) below the + /// others. `None` when none of them has a color. + pub fn with_artboard_fills(&self, indices: impl IntoIterator<Item = usize>) -> Option<Self> { + let fills: Vec<(Rect, vectorcraft_color::Color)> = indices + .into_iter() + .filter_map(|i| { + let a = self.artboards.get(i)?; + Some((a.rect, a.color?)) + }) + .collect(); + if fills.is_empty() { + return None; + } + let mut d = self.clone(); + let mut layer = Node::layer(d.alloc_id(), "Artboard Fill", super::LayerColor::Preset(0)); + let paths: Vec<Arc<Node>> = fills + .into_iter() + .map(|(r, c)| { + let look = super::Appearance::basic(vectorcraft_color::Paint::solid(c), vectorcraft_color::Paint::None, 0.0); + Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), look)) + }) + .collect(); + *layer.children_mut()? = paths; + d.layers.insert(0, Arc::new(layer)); + Some(d) + } +} + /// A document's locked artboards ([`Document::locked_artboards`]). pub struct LockedArtboards<'a> { pub(crate) rects: Vec<Rect>, diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 0b205a5b16..df94ba2c9f 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -55,6 +55,29 @@ fn doc_with_rects() -> (Document, NodeId, NodeId) { (d, a, b) } +/// Output draws the background colors of the artboards asked for, and only theirs, as rectangles +/// of those artboards on a layer below the art; without a color there is nothing to draw. +#[test] +fn artboard_fills_go_below_the_art() { + let (mut d, a, _) = doc_with_rects(); + assert!(d.with_artboard_fills([0]).is_none(), "no color, no fill"); + let second = Rect::new(700.0, 0.0, 800.0, 100.0); + d.artboards.push(Artboard { id: 2, rect: second, ..d.artboards[0].clone() }); + let blue = vectorcraft_color::Color::cmyk(1.0, 0.5, 0.0, 0.0); + d.artboards[1].color = Some(blue); + assert!(d.with_artboard_fills([0]).is_none(), "only the artboards asked for"); + let out = d.with_artboard_fills([0, 1]).unwrap(); + assert_eq!(out.layers.len(), d.layers.len() + 1); + assert_eq!(out.layers[1..], d.layers[..], "the art stays as it was, above the fills"); + let fills = out.layers[0].children().unwrap(); + assert_eq!(out.layers[0].display_name(), "Artboard Fill"); + assert_eq!(fills.len(), 1); + assert_eq!(fills[0].geometric_bounds(), Some(second)); + assert_eq!(fills[0].appearance.fill_paint(), vectorcraft_color::Paint::solid(blue), "in the color's own model"); + assert!(out.node(a).is_some() && out.node(fills[0].id).is_some() && fills[0].id != a); + assert_eq!(d.artboards, out.artboards); +} + #[test] fn new_document_has_layer_and_artboard() { let d = Document::new(612.0, 792.0); diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index e41bdd9b2a..b873f36387 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -57,6 +57,7 @@ pub use dxf::{UNSUPPORTED, Unsupported, unsupported}; pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, encode, encode_all, encode_with_warnings}; pub(crate) use encode::{anti_alias, background, with_single_artboard}; pub use export::export_source; +pub(crate) use export::with_artboard_fills; pub(crate) use export::{export_crop, isolated}; pub(crate) use load::check_not_lossy_overwrite; use load::err; @@ -132,6 +133,8 @@ mod tests; #[cfg(test)] mod tests_affinity; #[cfg(test)] +mod tests_artboard_fill; +#[cfg(test)] mod tests_pdf; #[cfg(test)] mod tests_pdfcolor; diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 9c6861f555..4588b58aaa 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path", has_doc, export::export ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export for Screens", ["File", "Export"], None, - "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)", + "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)", has_doc, screens::export_for_screens ), @@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> { "Save Export Preset", [], None, - "{name, settings: {formats, settings, preset, name, prefix, counterStart, counterPer, folders, subfolders, includeBleed, antiAlias, folder, fullDocument} (as document.exportForScreens; other keys are left out)} save (or replace) a batch export preset, kept with the preferences; built-in names are refused → {name, created, settings}", + "{name, settings: {formats, settings, preset, name, prefix, counterStart, counterPer, folders, subfolders, includeBleed, includeArtboardFill, antiAlias, folder, fullDocument} (as document.exportForScreens; other keys are left out)} save (or replace) a batch export preset, kept with the preferences; built-in names are refused → {name, created, settings}", always, screens::presets_save ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 1202bde7f8..a807010711 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -565,6 +565,9 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> { (RasterFormat::Jpeg, Some(m)) => MapKind::from_id(m).ok_or_else(|| bad(C, format!("imageMap `{m}`: none, client or server")))?, _ => MapKind::None, }; + // The artboards' background colors, behind the art (a transparent background too). + let filled = super::export::with_artboard_fills(doc, p, chosen.iter().copied()).map_err(|e| bad(C, e))?; + let doc = &*filled; let mut enc = Encoded::default(); let mut renderer = vectorcraft_render::Renderer::new(); let total = chosen.len() as u64; diff --git a/crates/engine/src/cmd/fileio/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index 49ecfaa345..f90dacfc71 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -300,6 +300,9 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> { if pages.is_empty() { return Err(bad(C, "the document has no artboard")); } + // The artboards' background colors, behind the art (the editing data keeps them as colors). + let filled = super::export::with_artboard_fills(doc, p, pages.iter().filter_map(|(b, ..)| *b)).map_err(|e| bad(C, e))?; + let doc = &*filled; let regions: Vec<Rect> = pages.iter().map(|(_, region, _)| *region).collect(); let expanded = expand_transparent_tile_images(doc, &set.flatten)?; let source = expanded.as_ref().unwrap_or(doc); diff --git a/crates/engine/src/cmd/fileio/export.rs b/crates/engine/src/cmd/fileio/export.rs index 2a3ff0e78b..852f2c735e 100644 --- a/crates/engine/src/cmd/fileio/export.rs +++ b/crates/engine/src/cmd/fileio/export.rs @@ -146,6 +146,21 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect) -> Document d } +/// `doc` with the background colors of `artboards` drawn behind its art +/// ([`Document::with_artboard_fills`]), what exports and print draw, unless `p` turns +/// `includeArtboardFill` off (Export for Screens › Include Artboard Fill; on by default). +pub(crate) fn with_artboard_fills<'a>( + doc: &'a Document, + p: &Value, + artboards: impl IntoIterator<Item = usize>, +) -> std::result::Result<Cow<'a, Document>, String> { + let include = match p.get("includeArtboardFill") { + None | Some(Value::Null) => true, + Some(v) => v.as_bool().ok_or("`includeArtboardFill` must be true or false")?, + }; + Ok(include.then(|| doc.with_artboard_fills(artboards)).flatten().map_or(Cow::Borrowed(doc), Cow::Owned)) +} + /// `p` without its artboard choice, also inside its SVG options (for documents made of one /// synthetic artboard, and for callers that pick the artboard themselves). pub(super) fn without_artboards(p: &Value) -> Value { diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 213a442cf6..2a3829acd6 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -284,6 +284,10 @@ fn overflow_warning(cmd: &str, doc: &Document, p: &Value) -> Result<Option<Strin /// native document with its save options, whose pages may be left blank). pub(super) fn encode_carrying(cmd: &str, doc: &Document, p: &Value, native: impl FnOnce() -> Result<Vec<u8>>) -> Result<(Vec<u8>, Vec<String>)> { let mut opts = options(cmd, doc, p)?; + // The pages' background colors, behind the art (the editing data keeps them as colors). + let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect()); + let filled = super::export::with_artboard_fills(doc, p, pages).map_err(|e| bad(cmd, e))?; + let doc = &*filled; if opts.settings.thumbnails { opts.thumbnails = thumbnails(doc, &opts).map_err(|e| pdf_error(cmd, e))?; } diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index c6ff1e8d6a..966038b35e 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -21,7 +21,7 @@ use super::encode::single_artboard; use super::export::{export_crop, isolated, selected_artwork, without_artboards}; use super::naming::{self, NameParts}; use super::{ - ARTBOARD_PARAMS, ArtboardPick, Format, artboard_file_names, create_dir, distinct_names, encode_with_warnings, unique_file_names, + ARTBOARD_PARAMS, ArtboardPick, Format, artboard_file_names, create_dir, distinct_names, encode_with_warnings, merge, unique_file_names, with_black_output, writable, write_file, }; @@ -289,6 +289,8 @@ struct ScreenParams { zip: bool, full_document: bool, include_bleed: bool, + /// Include Artboard Fill: the artboards' background colors behind the art (default on). + include_artboard_fill: Option<bool>, subfolders: bool, preset: Option<String>, prefix: Option<String>, @@ -579,7 +581,7 @@ pub struct ScreenExportPreset { /// What a preset keeps: the formats, their settings, the naming and the folders; not which art /// (it changes with the document) nor where to (unless given). -pub const PRESET_KEYS: [&str; 13] = [ +pub const PRESET_KEYS: [&str; 14] = [ "formats", "settings", "preset", @@ -590,6 +592,7 @@ pub const PRESET_KEYS: [&str; 13] = [ "folders", "subfolders", "includeBleed", + "includeArtboardFill", "antiAlias", "folder", "fullDocument", @@ -708,7 +711,9 @@ pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> { let crop = rows.iter().any(|r| r.format.id != "pdf"); let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?; // Appearance of Black › Printing / Exporting for RGB raster rows. - let rows = rows.into_iter().map(|r| Row { options: with_black_output(s, &r.options), ..r }).collect(); + // Include Artboard Fill off: the encoders leave the background colors out. + let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) }; + let rows = rows.into_iter().map(|r| Row { options: merge(with_black_output(s, &r.options), fill.clone()), ..r }).collect(); let export = ScreenExport { cmd: C, o, rows, naming, items }; match &mut s.screens_hand_off { Some(slot) => { @@ -830,6 +835,10 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> .entry(b) .or_insert_with(|| { let mut d = single_artboard(&item.doc, item.region, &item.name); + // It keeps its background color. + if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(b)) { + a.color = from.color; + } super::save::keep_art_on(&mut d, item.region); Arc::new(d) }) diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index e0909cb570..a11e4a4e8f 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -169,7 +169,9 @@ pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Enco // Draw linked files as vectors when available, or their previews with a warning. Keep // that preparation out of the native attachment so missing links remain relinkable. let (full, warnings) = crate::cmd::place::document::full_documents(doc); - let doc = &*full; + // The artboards' background colors, behind the art (the editing data keeps them as colors). + let filled = super::export::with_artboard_fills(&full, p, boards.iter().flatten().copied())?; + let doc = &*filled; // A chosen artboard's file holds the art over it; otherwise the file holds all of it. let regions: Option<Vec<vectorcraft_geom::Rect>> = chosen.then(|| boards.iter().flatten().filter_map(|b| doc.artboards.get(*b)).map(|a| a.rect).collect()); diff --git a/crates/engine/src/cmd/fileio/tests_artboard_fill.rs b/crates/engine/src/cmd/fileio/tests_artboard_fill.rs new file mode 100644 index 0000000000..6ca7d486fd --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_artboard_fill.rs @@ -0,0 +1,134 @@ +//! Artboard background colors in output (#4937): raster, PDF, SVG and EPS exports, Export for +//! Screens and print draw each artboard's color behind its art, inside the artboard; +//! `includeArtboardFill: false` (Include Artboard Fill) leaves it out; the editing data keeps it as +//! the artboard's color, not as art. + +use serde_json::{Value, json}; + +use super::*; + +const RED: [u8; 4] = [255, 0, 0, 255]; + +/// Two 60×40 pt artboards, a 20 pt square (white fill, black stroke) on the first, which is red. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 60, "height": 40, "artboards": 2})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 0, "color": "#ff0000"})).unwrap(); + s +} + +fn b64(v: &Value) -> Vec<u8> { + vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap() +} + +fn with(mut p: Value, more: &Value) -> Value { + if let (Some(o), Some(m)) = (p.as_object_mut(), more.as_object()) { + o.extend(m.iter().map(|(k, v)| (k.clone(), v.clone()))); + } + p +} + +/// The pixels of the PNG `document.export` writes of the active document with `p`, on transparency. +fn png(s: &mut Session, p: Value) -> image::RgbaImage { + let v = s.execute("document.export", &with(json!({"format": "png", "background": "transparent"}), &p)).unwrap(); + image::load_from_memory(&b64(&v)).unwrap().to_rgba8() +} + +/// The file `document.export` writes with `p`. +fn file(s: &mut Session, p: Value) -> Vec<u8> { + b64(&s.execute("document.export", &p).unwrap()) +} + +/// The file `bytes` named `name`, opened in a new session. +fn opened(name: &str, bytes: &[u8]) -> Session { + let mut s = Session::new(); + s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap(); + s +} + +/// What the file `bytes` named `name` shows near its top-left corner, opened and drawn. +fn corner(name: &str, bytes: &[u8]) -> [u8; 4] { + png(&mut opened(name, bytes), json!({"artboard": 0})).get_pixel(2, 2).0 +} + +#[test] +fn raster_exports_paint_the_color_behind_the_art() { + let mut s = session(); + let on = png(&mut s, json!({"artboard": 0})); + assert_eq!(on.get_pixel(2, 2).0, RED, "a transparent background still shows the color"); + assert_eq!(on.get_pixel(20, 20).0, [255, 255, 255, 255], "the art over it"); + assert_eq!(png(&mut s, json!({"artboard": 0, "includeArtboardFill": false})).get_pixel(2, 2)[3], 0, "left out"); + assert_eq!(png(&mut s, json!({"artboard": 1})).get_pixel(2, 2)[3], 0, "an artboard without a color"); + let jpg = file(&mut s, json!({"format": "jpg", "artboard": 0, "quality": 100})); + let px = image::load_from_memory(&jpg).unwrap().to_rgb8().get_pixel(2, 2).0; + assert!(px[0] > 240 && px[1] < 16 && px[2] < 16, "JPEG too: {px:?}"); + for bad in [json!("no"), json!(1)] { + assert!(s.execute("document.export", &json!({"format": "png", "includeArtboardFill": bad})).is_err(), "{bad}"); + } + assert_eq!(s.doc().unwrap().doc.layers.len(), 1, "the document gains no layer"); +} + +#[test] +fn the_color_fills_its_artboard_alone_behind_the_art() { + let s = session(); + let doc = &s.doc().unwrap().doc; + let board = doc.artboards[0].rect; + let filled = doc.with_artboard_fills([0, 1]).unwrap(); + let img = vectorcraft_render::Renderer::new().render_region(&filled, board.inflate(10.0, 10.0), 1.0, false); + let rgba = img.to_straight(); + let px = |x: usize, y: usize| rgba[(y * img.width as usize + x) * 4..][..4].to_vec(); + assert_eq!(px(5, 5)[3], 0, "outside the artboard"); + assert_eq!(px(15, 15), RED, "inside it"); + assert_eq!(px(30, 30), [255, 255, 255, 255], "the art over it"); +} + +#[test] +fn pdf_and_svg_show_the_color_and_their_editing_data_keeps_it_as_the_artboards() { + let mut s = session(); + for (format, name) in [("pdf", "a.pdf"), ("svg", "a.svg")] { + let p = json!({"format": format, "artboard": 0, "preserveEditing": false}); + assert_eq!(corner(name, &file(&mut s, p.clone())), RED, "{format}"); + assert_eq!(corner(name, &file(&mut s, with(p, &json!({"includeArtboardFill": false}))))[3], 0, "{format}"); + } + let reopened = opened("a.pdf", &file(&mut s, json!({"format": "pdf", "preserveEditing": true}))); + let (back, doc) = (&reopened.doc().unwrap().doc, &s.doc().unwrap().doc); + assert_eq!(back.artboards[0].color, doc.artboards[0].color); + assert_eq!(back.layers.len(), doc.layers.len(), "no art made of it"); +} + +#[test] +fn eps_and_postscript_print_draw_the_color() { + let mut s = session(); + // The only red the document has, the first artboard's color: RGB, or CMYK PostScript's. + let red = |t: &str| t.contains("1 0 0 rg\n") || t.contains("0 0.9725 1 0 k\n"); + let eps = |s: &mut Session, more: Value| { + String::from_utf8_lossy(&file(s, with(json!({"format": "eps", "useArtboards": true, "artboard": 0}), &more))).into_owned() + }; + assert!(red(&eps(&mut s, json!({}))), "EPS"); + assert!(!red(&eps(&mut s, json!({"includeArtboardFill": false}))), "EPS without it"); + let ps = |s: &mut Session, more: Value| { + String::from_utf8_lossy(&b64(&s.execute("file.print", &with(json!({"format": "postscript"}), &more)).unwrap())).into_owned() + }; + assert!(red(&ps(&mut s, json!({}))), "print"); + assert!(!red(&ps(&mut s, json!({"includeArtboardFill": false}))), "print without it"); +} + +#[test] +fn export_for_screens_includes_the_fill_unless_unchecked() { + let mut s = session(); + let screens = |s: &mut Session, more: Value| { + let p = with(json!({"artboards": [0], "formats": [{"format": "png"}], "settings": {"png": {"background": "transparent"}}}), &more); + s.execute("document.exportForScreens", &p).unwrap() + }; + let corner = |r: &Value| image::load_from_memory(&b64(&r["files"][0])).unwrap().to_rgba8().get_pixel(2, 2).0; + assert_eq!(corner(&screens(&mut s, json!({}))), RED, "on by default"); + assert_eq!(corner(&screens(&mut s, json!({"includeArtboardFill": false})))[3], 0, "unchecked"); + assert_eq!(s.execute("document.exportSettings", &json!({})).unwrap()["settings"]["includeArtboardFill"], false, "remembered"); + assert!(s.execute("document.exportForScreens", &json!({"includeArtboardFill": "no", "formats": [{"format": "png"}]})).is_err()); + // A document row's artboard keeps its color, as a color. + let r = screens(&mut s, json!({"formats": [{"format": "vectorcraft"}]})); + let back = vectorcraft_format::load(&b64(&r["files"][0])).unwrap(); + assert_eq!(back.artboards[0].color, s.doc().unwrap().doc.artboards[0].color); + assert_eq!(back.layers.len(), 1, "not as art"); +} diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 075bac2f5b..f85c7b2c23 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> { "Print", [], Some("Cmd+P"), - "{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device", + "{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), includeArtboardFill?: true (each artboard's background color prints behind its art; false leaves it out), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device", has_doc, print ), @@ -176,7 +176,9 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> { } // Placed documents print their files' art. let (full, _) = super::place::document::full_documents(doc); - let doc = &*full; + // The artboards' background colors print behind the art. + let filled = super::fileio::with_artboard_fills(&full, p, 0..full.artboards.len()).map_err(|e| bad(PRINT, e))?; + let doc = &*filled; // Raster effects print as images at the document's raster effects resolution. let flat = super::rasterfx::flatten_raster_effects(doc); let doc = flat.as_ref().unwrap_or(doc); diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 6b1e9f6b06..c8fbf05f29 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -42,7 +42,7 @@ const HOST_COMMANDS: &[(&str, &str, &str)] = &[ ( "file.exportForScreens", "Export for Screens…", - "{folder?, zip?, artboards? | range? | fullDocument? | assets?, includeBleed?, subfolders?, preset?, formats?, settings?, prefix?} = document.exportForScreens (no folder → the files, or one zip, as dataBase64)", + "{folder?, zip?, artboards? | range? | fullDocument? | assets?, includeBleed?, includeArtboardFill?, subfolders?, preset?, formats?, settings?, prefix?} = document.exportForScreens (no folder → the files, or one zip, as dataBase64)", ), ("tool.select", "Select Tool", "{tool} e.g. selection, directSelection, pen, rectangle, ellipse, polygon, star, lineSegment"), ( diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index fdb48a7536..3dc2417fb8 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -1,6 +1,6 @@ //! File → Export → Export for Screens, laid out as Illustrator's: on the left the Artboards and //! Assets tabs (thumbnails with checkboxes, in a grid or a list), Clear Selection and the prefix; -//! on the right Select (All, a range or Full Document, Include Bleed), the destination (folder +//! on the right Select (All, a range or Full Document, Include Bleed, Include Artboard Fill), the destination (folder //! picker, Open Location after Export, Create Sub-folders by scale or by format; the web downloads //! instead), Export PDFs As (one file of every artboard or a file each), and the format rows (scale //! as `2x`, `100w`, `100h` or `72ppi`, suffix, format) with the iOS and Android rows, the format @@ -16,6 +16,7 @@ //! //! Fields (`ui.dialog.set`): `tab` (artboards|assets), `select` (all|range|full), `range`, //! `boards` ([bool] per artboard), `assets` ([asset id] checked on the Assets tab), `includeBleed`, +//! `includeArtboardFill`, //! `folder`, `openLocation`, `subfolders`, `subfolderBy` (scale|format), `pdfs` (single|multiple), //! `prefix`, `preset` (""|mobile|density: where the rows came from), `formats` (rows of //! `document.exportForScreens`, `scale` as text), `settings` ({png|png8|jpg|webp|gif|tiff|svg|pdf: @@ -164,6 +165,7 @@ pub fn open(app: &mut VectorcraftApp) { "boards": boards, "assets": assets, "includeBleed": flag("includeBleed", false), + "includeArtboardFill": flag("includeArtboardFill", true), "folder": folder.unwrap_or_default(), "openLocation": flag("openLocation", true), "subfolders": subfolders, @@ -324,6 +326,7 @@ fn selection_params(app: &VectorcraftApp, d: &Dialog) -> Result<(Map<String, Val let pdf_rows = rows.iter().filter(|r| r["format"].as_str().and_then(fileio::format).is_some_and(|f| f.id == "pdf")).count(); let files = if single { (rows.len() - pdf_rows) * pieces + pdf_rows } else { rows.len() * pieces }; p.insert("includeBleed".into(), json!(d.bool("includeBleed"))); + p.insert("includeArtboardFill".into(), json!(d.bool("includeArtboardFill"))); let folders = match (d.bool("subfolders"), d.str("subfolderBy").as_str()) { (false, _) => "none", (true, "format") => "format", @@ -448,7 +451,8 @@ fn boards(app: &VectorcraftApp, d: &Dialog) -> Vec<bool> { boards } -/// Select: All or a Range (which checks the artboards it names), Include Bleed and Full Document. +/// Select: All or a Range (which checks the artboards it names), Include Bleed, Include Artboard +/// Fill and Full Document. fn select_options(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let n = app.session.active().map_or(0, |st| st.doc.artboards.len()); let select = d.str("select"); @@ -470,7 +474,10 @@ fn select_options(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { } }); }); - form::check(ui, d, "includeBleed", tl!("Include Bleed")); + ui.horizontal(|ui| { + form::check(ui, d, "includeBleed", tl!("Include Bleed")); + form::check(ui, d, "includeArtboardFill", tl!("Include Artboard Fill")); + }); if widgets::radio(ui, tl!("Full Document"), d.str("select") == "full", true) { set_select(d, "full"); } @@ -740,8 +747,10 @@ pub(super) fn apply_preset(d: &mut Dialog, preset: &Value) { if let Some(prefix) = st["prefix"].as_str() { d.fields.insert("prefix".into(), json!(prefix)); } - if let Some(b) = st["includeBleed"].as_bool() { - d.fields.insert("includeBleed".into(), json!(b)); + for key in ["includeBleed", "includeArtboardFill"] { + if let Some(b) = st[key].as_bool() { + d.fields.insert(key.into(), json!(b)); + } } d.fields.insert("exportPreset".into(), json!(preset["name"])); } diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 5355ef0f62..76650401c0 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -545,7 +545,8 @@ fn art_texture(app: &mut VectorcraftApp, ctx: &egui::Context, layers: PrintLayer { return Some(tex); } - let mut doc = (*st.doc).clone(); + // The artboards' background colors print behind the art. + let mut doc = st.doc.with_artboard_fills(0..st.doc.artboards.len()).unwrap_or_else(|| (*st.doc).clone()); vectorcraft_pdf::keep_layers(&mut doc.layers, layers); let tex = widgets::region_texture(ctx, &mut app.canvas.renderer, "print-preview-art", &doc, area, px); ctx.data_mut(|m| m.insert_temp(key, (stamp, tex.clone()))); diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index 2a54850ca4..5e2891f5c3 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -65,6 +65,7 @@ fn opens_on_defaults_and_draws_every_view() { assert_eq!(field(&app, "folder"), json!(fileio::export_folder().unwrap_or_default()), "the Desktop, else home"); assert_eq!((field(&app, "openLocation"), field(&app, "subfolders"), field(&app, "preset")), (json!(true), json!(true), json!(""))); assert_eq!((field(&app, "subfolderBy"), field(&app, "pdfs"), field(&app, "view")), (json!("scale"), json!("multiple"), json!("grid"))); + assert_eq!((field(&app, "includeBleed"), field(&app, "includeArtboardFill")), (json!(false), json!(true))); let settings = field(&app, "settings"); for f in ["png", "png8", "jpg", "webp", "gif", "tiff", "svg", "pdf"] { assert!(settings[f].is_object(), "{f} has settings"); @@ -450,6 +451,30 @@ fn the_web_downloads_one_zip_or_the_file() { assert_eq!(image::load_from_memory(&log[0].1).unwrap().to_rgba8().get_pixel(1, 1).0, [0, 0, 0, 255], "the PNG settings' background"); } +/// Include Artboard Fill: checked, the file shows the artboard's background color behind the art +/// (on transparency too); unchecked, it doesn't, and the dialog reopens unchecked. +#[test] +fn include_artboard_fill_reaches_the_files_and_is_remembered() { + let (mut app, log) = app(1, true); + app.run("artboard.setProps", json!({"index": 0, "color": "#ff0000"})).unwrap(); + for include in [true, false] { + log.borrow_mut().clear(); + open(&mut app); + assert_eq!(field(&app, "includeArtboardFill"), json!(true), "on until unchecked"); + set(&mut app, "includeArtboardFill", json!(include)); + set(&mut app, "settings", json!({"png": {"background": "transparent"}})); + frame(&mut app); + confirm(&mut app).unwrap(); + let px = image::load_from_memory(&log.borrow()[0].1).unwrap().to_rgba8().get_pixel(58, 38).0; + assert_eq!(px, if include { [255, 0, 0, 255] } else { [0, 0, 0, 0] }, "include {include}"); + if include { + continue; + } + open(&mut app); + assert_eq!(field(&app, "includeArtboardFill"), json!(false), "remembered"); + } +} + #[test] fn the_status_bar_says_when_an_image_could_not_be_decoded() { const NOTE: &str = "with 1 note(s): an image couldn't be decoded and is missing from the picture"; @@ -784,6 +809,7 @@ fn the_dialog_is_laid_out_as_illustrators() { "Select:", "Full Document", "Include Bleed", + "Include Artboard Fill", "Export to:", "Open Location after Export", "Create Sub-folders", diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index a89d71c136..bf02bfbf4c 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1524,6 +1524,7 @@ font-technology Variable Променливи In Tangent Handles Входящи управляващи точки In the selected objects В избраните обекти Inches Инчове + Include Artboard Fill Включване на запълването на работната област Include Blacks with CMY: Включване на черни към CMY: Include Bleed Включване на изтичане Include Cmy Blacks Включване на CMYK черни diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index e4ab0eac16..a22b6b9854 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2221,6 +2221,7 @@ digits Malayalam Malajalam Compatible Gradient and Gradient Mesh Printing Kompatibilno štampanje gradijenata i gradijentnih mreža Embed Fonts (for other applications) Ugradi fontove (za druge aplikacije) EPS Options EPS opcije + Include Artboard Fill Uključi ispunu radne ploče Include CMYK PostScript in RGB Files Uključi CMYK PostScript u RGB datoteke Include Document Thumbnails Uključi sličice dokumenta Include Linked Files Uključi povezane datoteke diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c4ecf209d7..1086b60b89 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1944,6 +1944,7 @@ digits Malayalam Malaiàlam In the selected objects Als objectes seleccionats In VectorCraft A VectorCraft Inches Polzades + Include Artboard Fill Inclou el farciment del tauler Include all profiles Inclou tots els perfils Include All Subdirectories Inclou tots els subdirectoris Include Blacks with CMY: Inclou negres amb CMY: diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index dbbae87849..52a61db5c8 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2249,6 +2249,7 @@ digits Malayalam Malajálamské Compatible Gradient and Gradient Mesh Printing Kompatibilní tisk přechodů a přechodových sítí Embed Fonts (for other applications) Vložit písma (pro jiné aplikace) EPS Options Možnosti EPS + Include Artboard Fill Zahrnout výplň pracovní plochy Include CMYK PostScript in RGB Files Zahrnout CMYK PostScript do souborů RGB Include Document Thumbnails Zahrnout miniatury dokumentu Include Linked Files Zahrnout propojené soubory diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 21f9192ba8..2b79b23dc6 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2052,6 +2052,7 @@ digits Malayalam Malayalam Compatible Gradient and Gradient Mesh Printing Kompatibel udskrivning af gradienter og gradientnet Embed Fonts (for other applications) Indlejr skrifttyper (til andre programmer) EPS Options EPS-indstillinger + Include Artboard Fill Medtag kunstpladens udfyldning Include CMYK PostScript in RGB Files Medtag CMYK-PostScript i RGB-filer Include Document Thumbnails Medtag dokumentminiaturer Include Linked Files Medtag linkede filer diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 503a545858..328205b3a0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1562,6 +1562,7 @@ file-filter Templates Vorlagen In Tangent Handles Eingehende Tangentengriffe In the selected objects In den ausgewählten Objekten Inches Zoll + Include Artboard Fill Zeichenflächenfüllung einschließen Include Blacks with CMY: Schwarz mit CMY einschließen: Include Bleed Anschnitt einschließen Include Cmy Blacks CMY-Schwarz einschließen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 887bfe7d43..bd0a4834de 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1487,6 +1487,7 @@ font-technology Variable Μεταβλητές In Tangent Handles Λαβές εφαπτομένης εισόδου In the selected objects Στα επιλεγμένα αντικείμενα Inches Ίντσες + Include Artboard Fill Συμπερίληψη γεμίσματος πίνακα σχεδίασης Include Blacks with CMY: Συμπερίληψη μαύρων με CMY: Include Bleed Συμπερίληψη ξακρίσματος Include Cmy Blacks Συμπερίληψη μαύρων CMY diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 78e3a7ce57..aa29fafd25 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1562,6 +1562,7 @@ font-technology Variable Variables In Tangent Handles Manejadores de tangente de entrada In the selected objects En los objetos seleccionados Inches Pulgadas + Include Artboard Fill Incluir relleno de la mesa de trabajo Include Blacks with CMY: Incluir negros con CMY: Include Bleed Incluir sangrado Include Cmy Blacks Incluir negros CMY diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index ca6db15365..b6a15979c0 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2204,6 +2204,7 @@ digits Malayalam Malajalam Compatible Gradient and Gradient Mesh Printing Yhteensopiva liukuvärin ja liukuväriverkon tulostus Embed Fonts (for other applications) Upota fontit (muita sovelluksia varten) EPS Options EPS-asetukset + Include Artboard Fill Sisällytä piirtoalustan täyttö Include CMYK PostScript in RGB Files Sisällytä CMYK PostScript RGB-tiedostoihin Include Document Thumbnails Sisällytä asiakirjan pikkukuvat Include Linked Files Sisällytä linkitetyt tiedostot diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 0102a7ad70..f16a049277 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1562,6 +1562,7 @@ font-technology Variable Variables In Tangent Handles Poignées de tangente entrantes In the selected objects Dans les objets sélectionnés Inches Pouces + Include Artboard Fill Inclure le fond du plan de travail Include Blacks with CMY: Inclure les noirs avec CMJ : Include Bleed Inclure le fond perdu Include Cmy Blacks Inclure les noirs CMJ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index ce55ee09d4..37e40c442b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1961,6 +1961,7 @@ file-filter Templates Sablonok In Tangent Handles Bejövő érintőfogantyúk In the selected objects A kijelölt objektumokban Inches Hüvelyk + Include Artboard Fill Rajztábla kitöltésével együtt Include all profiles Összes profil beágyazása Include Blacks with CMY: CMY-alapú feketék is: Include Bleed Kifutóval együtt diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index f111cc213c..1b46b5d862 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2052,6 +2052,7 @@ digits Malayalam Malayalam Compatible Gradient and Gradient Mesh Printing Pencetakan gradien dan mesh gradien yang kompatibel Embed Fonts (for other applications) Sematkan font (untuk aplikasi lain) EPS Options Opsi EPS + Include Artboard Fill Sertakan isian artboard Include CMYK PostScript in RGB Files Sertakan PostScript CMYK dalam file RGB Include Document Thumbnails Sertakan miniatur dokumen Include Linked Files Sertakan file tertaut diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index d01f8ebad8..701468a834 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1586,6 +1586,7 @@ file-filter Templates Modelli In Tangent Handles Maniglie tangente in entrata In the selected objects Negli oggetti selezionati Inches Pollici + Include Artboard Fill Includi riempimento tavola da disegno Include Blacks with CMY: Includi neri con CMY: Include Bleed Includi abbondanza Include Cmy Blacks Includi neri CMY diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index f1738d56b2..7057e12d7b 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1856,6 +1856,7 @@ digits Malayalam マラヤーラム数字 In Tangent Handles 入る側のハンドル In the selected objects 選択したオブジェクト内 Inches インチ + Include Artboard Fill アートボードの塗りを含める Include Bleed 裁ち落としを含める Include CMYK PostScript in RGB Files RGB ファイルに CMYK PostScript を含める Include Document Thumbnails ドキュメントのサムネールを含める diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 5ea64087e7..8af3007e15 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1952,6 +1952,7 @@ digits Malayalam მალაიალამური Compatible Gradient and Gradient Mesh Printing თავსებადი გრადიენტისა და გრადიენტული ბადის ბეჭდვა Embed Fonts (for other applications) შრიფტების ჩაშენება (სხვა აპლიკაციებისთვის) EPS Options EPS-ის პარამეტრები + Include Artboard Fill სამუშაო დაფის შევსების ჩართვა Include CMYK PostScript in RGB Files CMYK PostScript-ის ჩართვა RGB ფაილებში Include Document Thumbnails დოკუმენტის ესკიზების ჩართვა Include Linked Files დაკავშირებული ფაილების ჩართვა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 880456dee5..6156029dbb 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1884,6 +1884,7 @@ digits Malayalam 말라얄람어 In Tangent Handles 안쪽 접선 핸들 In the selected objects 선택한 개체 안에서 Inches 인치 + Include Artboard Fill 아트보드 칠 포함 Include Bleed 블리드 포함 Include CMYK PostScript in RGB Files RGB 파일에 CMYK PostScript 포함 Include Document Thumbnails 문서 미리 보기 이미지 포함 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 0d1fe8b2e9..ea641dab79 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2066,6 +2066,7 @@ digits Malayalam Malayalam Compatible Gradient and Gradient Mesh Printing Compatibel afdrukken van verlopen en verlooprasters Embed Fonts (for other applications) Lettertypen insluiten (voor andere programma's) EPS Options EPS-opties + Include Artboard Fill Tekenbordvulling opnemen Include CMYK PostScript in RGB Files CMYK PostScript opnemen in RGB-bestanden Include Document Thumbnails Documentminiaturen opnemen Include Linked Files Gekoppelde bestanden opnemen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 5fb2f16f10..a1f22e4d78 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2165,6 +2165,7 @@ digits Malayalam Malajalam Compatible Gradient and Gradient Mesh Printing Zgodne drukowanie gradientów i siatek gradientowych Embed Fonts (for other applications) Osadź czcionki (dla innych aplikacji) EPS Options Opcje EPS + Include Artboard Fill Uwzględnij wypełnienie obszaru kompozycji Include CMYK PostScript in RGB Files Dołącz CMYK PostScript w plikach RGB Include Document Thumbnails Dołącz miniatury dokumentu Include Linked Files Dołącz połączone pliki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8cefbc8d39..4b1d5f83fe 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1347,6 +1347,7 @@ In Tangent Handles Alças de Tangente de Entrada In the selected objects Nos objetos selecionados Inches Polegadas + Include Artboard Fill Incluir Preenchimento da Prancheta Include Bleed Incluir Sangria Include CMYK PostScript in RGB Files Incluir PostScript CMYK em Arquivos RGB Include Document Thumbnails Incluir Miniaturas do Documento diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 900f2361fd..3f05c0190f 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1584,6 +1584,7 @@ file-filter Templates Шаблоны In Tangent Handles Маркеры входящей касательной In the selected objects В выделенных объектах Inches Дюймы + Include Artboard Fill Включать заливку монтажной области Include Blacks with CMY: Включать чёрные с CMY: Include Bleed Включать вылет Include Cmy Blacks Включать чёрные CMY diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index ef1a8500ae..adabea465d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1526,6 +1526,7 @@ font-technology Variable Variabla In Tangent Handles Inkommande tangenthandtag In the selected objects I de markerade objekten Inches Tum + Include Artboard Fill Inkludera ritytans fyllning Include Blacks with CMY: Inkludera svart med CMY: Include Bleed Inkludera utfall Include Cmy Blacks Inkludera CMY-svarta diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c4980e5e5c..88017e1917 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1412,6 +1412,7 @@ font-technology Variable Değişken In Tangent Handles Teğet Tutamaçlarda In the selected objects Seçilen nesnelerde Inches İnç + Include Artboard Fill Çalışma Yüzeyi Dolgusunu Dahil Et Include Blacks with CMY: CMY ile Siyahları Dahil Et: Include Bleed Taşmayı Dahil Et Include Cmy Blacks Cmy Black'leri dahil et diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index daee9a6d5f..c0533166d8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1580,6 +1580,7 @@ file-filter Templates Шаблони In Tangent Handles Маркери вхідної дотичної In the selected objects У виділених об’єктах Inches Дюйми + Include Artboard Fill Включати заливку монтажної області Include Blacks with CMY: Включати чорні з CMY: Include Bleed Включати виліт Include Cmy Blacks Включати чорні CMY diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index ab2dd4721c..3ade68399e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1842,6 +1842,7 @@ digits Hindi Hindi In Tangent Handles Tay nắm tiếp tuyến vào In the selected objects Trong các đối tượng đã chọn Inches Inch + Include Artboard Fill Bao gồm màu tô bảng vẽ Include Blacks with CMY: Bao gồm đen với CMY: Include Bleed Bao gồm vùng chảy tràn Include Cmy Blacks Bao gồm đen CMY diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 58efd43a34..b3f76cc2b6 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1513,6 +1513,7 @@ file-filter Templates 模板 In Tangent Handles 内侧切线控制手柄 In the selected objects 在所选对象中 Inches 英寸 + Include Artboard Fill 包含画板填色 Include Blacks with CMY: 包含 CMY 的黑色: Include Bleed 包含出血 Include Cmy Blacks 包含 CMY 黑色 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1067a2ec21..fd750354a3 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1551,6 +1551,7 @@ file-filter Templates 範本 In Tangent Handles 內側切線控制把手 In the selected objects 在選取的物件中 Inches 英吋 + Include Artboard Fill 包含工作區域填色 Include Blacks with CMY: 包含 CMY 的黑色: Include Bleed 包含出血 Include Cmy Blacks 包含 CMY 黑色 From ea0539976ebb669d49320d701d73cc5fd6331fd2 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 04:11:00 +0700 Subject: [PATCH 177/260] Fix #4937: document artboard fills in exports, print and Export for Screens --- docs/file-format-parity.md | 3 ++- docs/gaps.md | 7 +++++-- docs/mcp.md | 10 ++++++++-- docs/target-app-parity.md | 7 ++++--- docs/ui-parity.md | 3 ++- 5 files changed, 21 insertions(+), 9 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 2d687384cb..fe9f554155 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (PDF import: fonts named with hyphens or with a composite font's CMap find the installed family) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (exports draw artboard background colors, #4937) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -131,6 +131,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Exports draw each artboard's background color behind its art (#4937): PNG, JPEG, GIF, TIFF, WebP, BMP, Targa and PSD (a layer of its own; on a transparent background too), PDF, SVG and EPS pages, a `.ai` file's PDF pages and PostScript and PDF print; `includeArtboardFill: false` leaves it out. Files with editing data (Preserve Editing, `.ai`, EPS, native) keep it as the artboard's color and reopen without extra art. Not read from the reference app's own `.ai` data, nor written to it. DXF, EMF and WMF leave it out | | 2026-10-31 | minor | PDF import finds an installed font whose PDF name holds hyphens (`Noto-Sans-Bold` is Noto Sans, Bold: the longest part before a hyphen that names an installed family) and a composite font by its CIDFont's name rather than its base name, which ends in the CMap's (`Name-Identity-H`, [ISO 32000-1 §9.7.6.1](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)); a missing font is split only before a style part (`Helvetica-BoldOblique`), so it is reported as `MS PGothic`, not `MS`; scores unchanged (estimated) | | 2026-10-31 | minor | DXF export (2000–2018): the LAYOUT objects wrote the paper image origin as a point at group codes 148 and 158, but PLOTSETTINGS defines 148 and 149 and no 158, so strict readers could reject the file (Autodesk Fusion reported "DXF File failed to insert", #3085). They now write 148/149, the shade plot mode, resolution and DPI (76–78, 2004 and later) and flag 1024 on the Model layout; the plot style ACDBPLACEHOLDER no longer carries a subclass marker. Test `r2000_and_later_files_have_the_structure_cad_apps_require` (required sections and table entries, handles and references, LAYOUT group codes); exports pass ezdxf's recover and audit; not tested in Fusion itself; scores unchanged | | 2026-10-31 | minor | `.ai`/EPS editing data: an envelope whose contents are being edited is written the other way round from one that isn't: its contents, a group on `%_` lines, then its dictionary, which holds the mesh that shapes them. Those contents were read as art, so the undistorted art drew over the distorted art the page draws. The group on `%_` lines before an envelope's dictionary is now left out whatever it holds (text in it stays as hidden text, as the dictionary's own does), as the envelope's mesh already was (#2405). Test `import::ai::tests::an_envelope_s_contents_being_edited_are_not_read_as_art`; checked locally against a user's file: it opens from its layers, 0.0% from its page (it was 9.7%, over the 5% limit); scores unchanged | diff --git a/docs/gaps.md b/docs/gaps.md index 9b93120bed..d8fa3849ba 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (G5: Start Global Edit on groups, #4939; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (G13: artboard background colors in exports and print, #4937; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -435,7 +435,9 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done:** TIFF choices and format settings in Export for Screens and Asset Export (30.2), using the existing encoder; UI-to-file regressions cover selection, scaling, options and persistence. - **Done:** artboard background colors on the canvas (30.0): Properties › Artboards › Fill and Artboard Options set - each artboard's color, and the canvas draws its paper in it. Exports and print do not draw the color yet. + each artboard's color, and the canvas draws its paper in it. Exports (raster, PDF, SVG, EPS, `.ai` PDF pages, + Export for Screens with Include Artboard Fill) and print draw it behind the art (#4937). Left: the color isn't read + from or written to the reference app's own `.ai` data. - **Done:** Object › Intertwine (#1763): Make, Edit and Release; the Intertwine tool highlights the overlap area under the pointer, a click swaps which object is on top there, and a path (Shift: a rectangle) drawn around overlaps @@ -677,6 +679,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | G13: Artboard background colors in output (#4937): raster exports (a transparent background too), PDF, SVG and EPS pages, `.ai` files' PDF pages, Export for Screens and print (and its preview) draw each artboard's color behind its art, inside the artboard and in the color's own model; Export for Screens has Include Artboard Fill beside Include Bleed (on by default, remembered; `includeArtboardFill`, also on `document.export` and `file.print`); editing data keeps the color as the artboard's, and Export for Screens' document rows keep it too; estimate unchanged. | | 2026-11-01 | minor | G5: Select › Start Global Edit on a group takes the groups like it (the same objects at the same places, moved or scaled; Appearance, Size and the artboard options apply) and gives an edit made to an object inside one to the object at its place in each of the others, in proportion, as one undo step (#4939); rotated copies and Shift-click exclusion remain. Estimate unchanged. | | 2026-10-31 | minor | G4: PDF import finds an installed font whose PDF name holds hyphens (`Noto-Sans-Bold` is Noto Sans, Bold: the longest part before a hyphen that names an installed family) and a composite font by its CIDFont's name rather than its base name, which ends in the CMap's (`Name-Identity-H`, [ISO 32000-1 §9.7.6.1](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)); a missing font is split only before a style part (`Helvetica-BoldOblique`), so it is reported as `MS PGothic`, not `MS`. Estimate unchanged. | | 2026-10-31 | minor | G13: Direct Selection snaps the end of an existing straight line, dragged by its end anchor, square to straight paths and grazing curves (Smart Guides › Geometric Guides: Snap to Perpendicular and Snap to Tangent), the case the public Snap to Perpendicular and Snap to Tangent pages add to drawing with the Line Segment and Pen tools (#2530). Scores and estimates unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index c6bbae8f61..c0eafc23c3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3586,7 +3586,12 @@ An artboard's background color (Properties › Artboards › Fill, Artboard Opti with one. The canvas draws that artboard's paper in the color. With Simulate Colored Paper on, it multiplies the color with the paper color, each sRGB channel as artboard × paper / 255; artboards without a color show the paper color. The transparency grid still covers it while -it shows. Copies, duplicates and the native format keep the color; exports and print do not draw it. `inspect_document` +it shows. Copies, duplicates and the native format keep the color. Exports draw it behind the art of each artboard +they write (raster formats, a transparent background too; PDF, SVG and EPS pages; `.ai` files' PDF pages; Export for +Screens; `file.print` and its preview), as a rectangle of the artboard filled with the color in its own model, on a +layer of its own below the others; files that carry the editing data (Preserve Editing, `.ai`, EPS, native rows of +Export for Screens) keep it as the artboard's color, not as art. `includeArtboardFill: false` on `document.export`, +`document.serialize`, `document.exportForScreens` (Include Artboard Fill) or `file.print` leaves it out. `inspect_document` lists it as the artboard's `color` (`#rrggbb`), and `ui.colorPicker {artboard: index}` opens the Color Picker for it. Artboard Options' Show Center Mark and Show Cross Hairs: `artboard.setProps {index, showCenterMark?: bool, @@ -4028,7 +4033,8 @@ each file deflated, or stored when deflating does not make it smaller. A row is `{format, scale?}` where `scale` is a factor (`2`, `"2x"`), a pixel width (`"100w"` or `width: 100`), a height (`"100h"`) or a resolution (`"72ppi"`); raster rows name their files `@2x`, `@100w`… unless `suffix` says otherwise. `fullDocument` writes one file per row instead (a PDF of every artboard, other formats the bounds of all -art), `includeBleed` grows each artboard by the document's bleed, `pdfs: "single"` (Export PDFs As › Single file) +art), `includeBleed` grows each artboard by the document's bleed, `includeArtboardFill: false` (Include Artboard +Fill unchecked) leaves the artboards' background colors out of the files, `pdfs: "single"` (Export PDFs As › Single file) writes the artboards a PDF row exports as the pages of one PDF named after the document, `subfolders` puts each row's files in a sub-folder (its size or format, or its own `folder`; `folders: "format"` sorts by format instead), `preset: "mobile"` or `"density"` (Android-style ldpi…xxxhdpi sub-folders) replaces the rows, and `settings: {png: {…}, jpg: {…}, svg: {…}, pdf: {preset}}` gives every row of a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 51d9dd20dd..442dba38ac 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Start Global Edit on groups, #4939; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (artboard background colors in exports and print, #4937; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -528,7 +528,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **A clip group in Properties:** with one clip group selected, the panel has Edit Clipping Path and Edit Contents at its top, under the Clip Group heading, which select the clipping path or the clipped art for the selection tools to transform alone, as Object › Clipping Mask does (<https://www.adobe.com/learn/illustrator/web/crop-using-masks>: with a clip group selected, the tutorial uses Edit Clipping Path at the top of the Properties panel to select the mask for editing, and uses Edit Contents to select the masked art). Edit Contents shows only when the group clips something. Not checked against the reference app: whether Properties keeps the buttons while the clipping path or the contents is selected; the Control bar has no clip-group buttons here. Evidence: `panels::properties::tests::one_clip_group_has_edit_clipping_path_and_edit_contents_at_the_top`. - **Contextual controls in Properties:** the [Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html) lists controls that appear for particular selections and tools; Properties has them, each running the existing command. Quick Actions has Blend Options for one selected blend, with the Blend tool or any other, as the [blending page](https://helpx.adobe.com/illustrator/using/blending-objects.html) describes (#4817) (the Blend Options dialog, OK one undo step) and Merge Live Paint when a Live Paint group is selected with more paths and nothing Live Paint refuses (`livePaint.merge`). Appearance has the stroke's Variable Width Profile list, the Control bar's, with the Width tool or when the stroke has a variable width (`stroke.set {profile}`), and beside fx the Delete icon: with one effect on the one selected object (its own or a fill's or stroke's) its name and an icon that removes it (`effect.remove`), with several an icon that opens the Appearance panel, as the overview describes. With Direct Selection and corners of one path selected, Corner and Corner Radius set the kind and radius of those corners (`object.setLiveShape`); a live rectangle's and polygon's own rows already do. Each edit is one undo step. The overview's Variable Font icon was already in Character. Not checked against the reference app: whether Merge needs two Live Paint groups (the overview speaks of several selected groups; `livePaint.merge` takes a group and paths), and where exactly each control sits in its section. Evidence: `panels::properties::tests::{blend_options_is_a_quick_action_for_one_blend_with_the_blend_tool, merge_live_paint_is_a_quick_action_for_a_live_paint_group_and_more, the_width_profile_shows_for_a_variable_width_or_the_width_tool, direct_selected_corners_show_their_kind_and_radius, one_effect_has_a_delete_icon_in_appearance}`. - **Edit Artboards in Properties:** the active artboard's name is a field. Typing a new name and pressing Enter or clicking elsewhere renames that artboard in one undo step, as the Artboards panel's rename does (`artboard.setProps {index, name}`); pressing Escape or leaving the field empty keeps the old name. A click on the Artboard Options icon beside the field opens Artboard Options for the active artboard, as double-clicking the Artboard tool's button does (`tool.options {tool: "artboard"}`). Pointer and key tests in `panels/properties.rs` cover both. Public references: [Resize artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/resize-artboards.html) and [Create and add new artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/add-new-artboards.html). -- **Artboard background colors:** each artboard can have a background color (`artboard.setProps {index, color}`, `color: null` removes it). With the Artboard tool, Properties has a Fill row: its list sets None, White or Black, and its chip and its Color Picker… item open the Color Picker for the artboard. Artboard Options has a Background Color row with a list that sets None, White or Black, and a color button. The canvas draws the artboard's paper in the color, multiplied with the paper color while Simulate Colored Paper is on, and the transparency grid still covers it. The native format saves the color, and a document without colors saves as before. Exports and print do not draw the color. Engine, canvas, Properties, Color Picker and Artboard Options tests cover it. Public reference: [Apply colors to artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/add-background-color-to-artboards.html). +- **Artboard background colors:** each artboard can have a background color (`artboard.setProps {index, color}`, `color: null` removes it). With the Artboard tool, Properties has a Fill row: its list sets None, White or Black, and its chip and its Color Picker… item open the Color Picker for the artboard. Artboard Options has a Background Color row with a list that sets None, White or Black, and a color button. The canvas draws the artboard's paper in the color, multiplied with the paper color while Simulate Colored Paper is on, and the transparency grid still covers it. The native format saves the color, and a document without colors saves as before. Exports draw it behind each exported artboard's art, inside the artboard and in the color's own model: raster formats (on a transparent background too), PDF, SVG and EPS pages, `.ai` files' PDF pages, Export for Screens and print, whose preview shows it; files with editing data keep it as the artboard's color, not as art. Export for Screens has Include Artboard Fill beside Include Bleed (on by default and remembered; `includeArtboardFill: false`, which `document.export` and `file.print` take too, leaves it out) (#4937). Not done: `.ai` files the reference app reads keep it only in VectorCraft's editing data, and `.ai`/PDF import doesn't read a background color from the reference app's own data. Engine, canvas, Properties, Color Picker, Artboard Options, export (`fileio::tests_artboard_fill`) and Export for Screens dialog tests cover it. Public reference: [Apply colors to artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/add-background-color-to-artboards.html). - **Resizing several artboards:** with several artboards selected with the Artboard tool, a new W or H in Properties, the Transform panel or the Control bar, a preset or an orientation in Properties or the Control bar, and a new Width or Height in Artboard Options resize every selected artboard in one undo step (`artboard.setProps {artboards}`); with Scale Artwork with Artboard on, Properties, the Transform panel and the Control bar scale each object once, with the artboard it was inside before the change. The Transform panel, the Control bar and Artboard Options resize each one about its own reference point, a preset sizes each one in its own orientation, and X and Y still move the active artboard alone. Pointer and key tests in `panels/properties.rs`, dialog tests in `dialogs/tests.rs` and an engine test in `tests/xform.rs` cover them. Public references: [Artboard Enhancements In Illustrator CC](https://blog.adobe.com/en/publish/2017/11/10/artboard-enhancements-in-illustrator-cc) (a height and a width entered once resize every selected artboard) and [Using multiple artboards](https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (2019). - **Artboard Escape routing:** Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture. Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. - **Escape in the distort tools:** Escape during a Puppet Warp pin drag or turn, a Perspective Grid tool handle or plane widget drag, a Perspective Selection move, resize or plane widget drag, or a Liquify stroke cancels it: the art goes back to how the press found it, no undo step is added, and the tool stays chosen. Puppet Warp also selects again the pins selected before the press, and Escape during a Liquify Alt-drag puts the brush size back. Regression tests: `escape_cancels_*` in `crates/tools/src/distort/puppet.rs`, `perspective.rs` and `liquify.rs`, and `escape_cancels_a_puppet_warp_perspective_or_liquify_drag` in `tests/distortkeys.rs`. @@ -550,7 +550,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output already in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). - Export for Screens: the dialog's Example line shows the path of the file the export writes first, sub-folder included, named as the export names it, for the first chosen artboard, asset, layer or object (`document.exportForScreens`). - - Export for Screens is laid out as the reference app's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`. + - Export for Screens is laid out as the reference app's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Include Artboard Fill, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`. - Save for Web: Preview in Browser writes each preview's page and images to a folder of its own inside `VectorCraft Save for Web` in the system's temporary folder. A later preview, from the same app or another one running, does not overwrite an earlier one. Each preview first removes the preview folders there that are an hour old or older and, on Linux, macOS and FreeBSD, belong to the current user; it leaves other files and folders alone. The folders a preview makes there are open to their owner only on those systems. When `VectorCraft Save for Web` is a link or is not a folder, or on those systems belongs to another user or can be written by other users, the preview goes to a new folder of its own in the temporary folder, which a later preview removes once it is an hour old (`file.saveForWeb.browser`). - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). - Variables (data merge): text, visibility and image variables bound to objects (an object may carry several), dataset rows applied in one undo step (`variable.*`, `dataset.*`) from a Variables panel and Window › Variables, with dialogs to define, bind and edit, Make Text/Visibility/Image Dynamic, Capture/Update Data Set, CSV import/export (`dataset.import` / `dataset.export`), and a row in italics when an edit leaves the art not matching it; an image dataset value is a file path and apply keeps the object's bounds; bindings let go of deleted art and locked art is left alone; every command, like the rest, is drivable over MCP and the CLI. @@ -1419,6 +1419,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Artboard background colors in output (#4937): raster exports (a transparent background too), PDF, SVG and EPS pages, `.ai` files' PDF pages, Export for Screens and print (and its preview) draw each artboard's color behind its art, inside the artboard and in the color's own model; Export for Screens has Include Artboard Fill beside Include Bleed (on by default, remembered; `includeArtboardFill`, also on `document.export` and `file.print`); editing data keeps the color as the artboard's, and Export for Screens' document rows keep it too; evidence updated; scores unchanged. | | 2026-11-01 | minor | Selection: Select › Start Global Edit on a group takes the groups like it (the same objects at the same places, moved or scaled; Appearance, Size and the artboard options apply) and gives an edit made to an object inside one to the object at its place in each of the others, in proportion, as one undo step (#4939); Global Edit of rotated copies and Shift-click exclusion remain. Score unchanged at 85% (estimated), hours unchanged. | | 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): New Symbols from Layers (#4927); evidence added; scores unchanged. | | 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): Save a Timestamped Copy (#4926); evidence added; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 9b4a0460a2..e9b977ff79 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Start Global Edit on groups, #4939) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Export for Screens: Include Artboard Fill, #4937) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -385,6 +385,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Export for Screens has Include Artboard Fill beside Include Bleed (on by default, remembered; `includeArtboardFill`): the files draw each artboard's background color behind its art, as exports and print now do, and the Print dialog's preview shows it (#4937); scores and estimates unchanged | | 2026-11-01 | minor | Select › Start Global Edit on a group takes the groups like it (the same objects at the same places, moved or scaled; Appearance, Size and the artboard options apply) and gives an edit made to an object inside one to the object at its place in each of the others, in proportion, as one undo step (#4939). Scores and estimates unchanged | | 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): New Symbols from Layers and Convert Layers to Symbols (#4927); scores and estimates unchanged | | 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): Save a Timestamped Copy (#4926); scores and estimates unchanged | From f22caa6108a8895265f58b2fc334c968e42dcbbd Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 04:39:50 +0700 Subject: [PATCH 178/260] Fix #4938: Dynamic symbols keep per-instance appearance linked to the symbol --- crates/brush/src/colorize.rs | 5 +- crates/brush/src/tests.rs | 2 +- crates/cad/src/import/build.rs | 2 +- crates/cad/src/scene.rs | 2 +- crates/cad/src/tests.rs | 2 +- crates/doc/src/depth.rs | 6 +- crates/doc/src/hit/tests.rs | 2 +- crates/doc/src/lib.rs | 2 + crates/doc/src/mem.rs | 1 + crates/doc/src/node/extras.rs | 4 + crates/doc/src/node/wire.rs | 31 +-- crates/doc/src/objects_on_path.rs | 2 +- crates/doc/src/orient.rs | 2 +- crates/doc/src/placed_document.rs | 8 +- crates/doc/src/records.rs | 4 + crates/doc/src/symbol_overrides.rs | 190 ++++++++++++++++++ crates/doc/src/symbols.rs | 2 +- crates/doc/src/tests.rs | 2 +- crates/effects/src/adjust.rs | 4 +- crates/effects/src/bake.rs | 6 +- crates/effects/src/live.rs | 2 +- crates/effects/src/tests.rs | 8 +- crates/engine/src/cmd/brushlib.rs | 2 +- crates/engine/src/cmd/brushsym.rs | 43 +++- crates/engine/src/cmd/brushsym/dynamic.rs | 151 ++++++++++++++ crates/engine/src/cmd/brushsym/symbols.rs | 64 ++++-- crates/engine/src/cmd/effectcmd.rs | 6 +- crates/engine/src/cmd/symbollib.rs | 2 +- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/docsetup.rs | 2 +- crates/engine/src/tests/dynamic_symbols.rs | 165 +++++++++++++++ crates/engine/src/tests/envelope_distort.rs | 2 +- crates/engine/src/tests/pdfraster.rs | 4 +- crates/engine/src/tests/placed_document.rs | 10 +- crates/engine/src/tests/previewbounds.rs | 4 +- crates/engine/src/tests/symbolbounds.rs | 18 +- crates/engine/src/tests/typescale.rs | 2 +- crates/engine/tests/import_fuzz.rs | 4 +- crates/eps/src/legacy_ai/writer.rs | 2 +- crates/eps/src/scene.rs | 2 +- crates/eps/src/tests.rs | 4 +- crates/format/tests/it/native_v3.rs | 2 +- crates/format/tests/it/save_options.rs | 2 +- crates/metafile/src/scene.rs | 2 +- crates/metafile/src/tests.rs | 2 +- crates/pdf/src/export/nodes.rs | 2 +- crates/pdf/src/tests.rs | 4 +- crates/pdf/src/tests/print.rs | 4 +- crates/render/src/brush_fx.rs | 6 +- crates/render/src/encode/tests.rs | 2 +- crates/render/src/fx/tests.rs | 4 +- crates/render/src/live.rs | 4 +- crates/render/src/renderer/text.rs | 4 +- crates/render/src/tests.rs | 20 +- crates/render/src/tests/adjust.rs | 2 +- crates/render/src/tests/changed.rs | 2 +- crates/render/src/tests/cmykblend.rs | 2 +- crates/render/src/tests/fontchange.rs | 6 +- crates/render/src/tests/memory.rs | 66 +++--- crates/render/src/tests/objectfx.rs | 4 +- crates/render/src/tests/placed_document.rs | 6 +- crates/render/src/tests/rasterize.rs | 2 +- crates/svg/src/export/nodes.rs | 2 +- crates/svg/src/import/importer.rs | 2 +- crates/svg/tests/it/data_attributes.rs | 2 +- crates/svg/tests/it/encoding_profile_fonts.rs | 2 +- crates/svg/tests/it/import_live.rs | 2 +- crates/svg/tests/it/symbols_layers.rs | 8 +- crates/tools/src/xform/eyedropper.rs | 20 +- crates/ui-egui/src/dialogs/symbol_options.rs | 28 ++- crates/ui-egui/src/i18n/bg.tsv | 12 ++ crates/ui-egui/src/i18n/bs.tsv | 12 ++ crates/ui-egui/src/i18n/ca.tsv | 12 ++ crates/ui-egui/src/i18n/cs.tsv | 12 ++ crates/ui-egui/src/i18n/da.tsv | 12 ++ crates/ui-egui/src/i18n/de.tsv | 12 ++ crates/ui-egui/src/i18n/el.tsv | 12 ++ crates/ui-egui/src/i18n/es.tsv | 12 ++ crates/ui-egui/src/i18n/fi.tsv | 12 ++ crates/ui-egui/src/i18n/fr.tsv | 12 ++ crates/ui-egui/src/i18n/hu.tsv | 12 ++ crates/ui-egui/src/i18n/id.tsv | 12 ++ crates/ui-egui/src/i18n/it.tsv | 12 ++ crates/ui-egui/src/i18n/ja.tsv | 12 ++ crates/ui-egui/src/i18n/ka.tsv | 12 ++ crates/ui-egui/src/i18n/ko.tsv | 12 ++ crates/ui-egui/src/i18n/nl.tsv | 12 ++ crates/ui-egui/src/i18n/pl.tsv | 12 ++ crates/ui-egui/src/i18n/pt-br.tsv | 12 ++ crates/ui-egui/src/i18n/ru.tsv | 12 ++ crates/ui-egui/src/i18n/sv.tsv | 12 ++ crates/ui-egui/src/i18n/tr.tsv | 12 ++ crates/ui-egui/src/i18n/uk.tsv | 12 ++ crates/ui-egui/src/i18n/vi.tsv | 12 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 12 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 12 ++ crates/ui-egui/src/panels/brushes/tests.rs | 2 +- crates/ui-egui/src/panels/properties.rs | 4 + crates/ui-egui/src/panels/properties/tests.rs | 18 ++ crates/ui-egui/src/panels/symbols.rs | 36 +++- docs/file-format-parity.md | 5 +- docs/gaps.md | 19 +- docs/mcp.md | 24 ++- docs/target-app-parity.md | 13 +- docs/ui-parity.md | 6 +- 105 files changed, 1218 insertions(+), 212 deletions(-) create mode 100644 crates/doc/src/symbol_overrides.rs create mode 100644 crates/engine/src/cmd/brushsym/dynamic.rs create mode 100644 crates/engine/src/tests/dynamic_symbols.rs diff --git a/crates/brush/src/colorize.rs b/crates/brush/src/colorize.rs index 9ef049f860..179c0de516 100644 --- a/crates/brush/src/colorize.rs +++ b/crates/brush/src/colorize.rs @@ -138,9 +138,10 @@ pub fn stain(inst: &Node) -> Option<(Color, f32)> { Some((f.paint.color()?, f.opacity)) } -/// A symbol's art for instance `inst`, stained by the instance's fill ([`stain`]). +/// A symbol's art for instance `inst`: with the instance's own appearance changes to it (a dynamic +/// symbol's, [`vectorcraft_doc::symbol_overrides`]), stained by the instance's fill ([`stain`]). pub fn instance_art(art: &Node, inst: &Node) -> Node { - let mut a = art.clone(); + let mut a = vectorcraft_doc::symbol_overrides::dynamic_art(art, inst); if let Some((c, amount)) = stain(inst) { tint_node(&mut a, &c, amount); } diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 6362c8da8d..a7320895ce 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1134,7 +1134,7 @@ fn pieces_leave_out_what_draws_a_brushed_stroke_by_name() { let mut brushed = rect_art(10.0, 4.0); brushed.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(StrokeLayer { brush: Some("s".into()), ..stroke(1.0) })); for (name, art) in [("plain", rect_art(10.0, 4.0)), ("brushed", brushed)] { - doc.symbols.push(Symbol { name: name.into(), art: std::sync::Arc::new(art.clone()) }); + doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: std::sync::Arc::new(art.clone()) }); doc.patterns.push(PatternDef::new(name, vec![std::sync::Arc::new(art)])); } let instance = |symbol: &str| Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY }); diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index 1e43c45dc2..6857c2a175 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -622,7 +622,7 @@ impl<'d, 'a> Build<'d, 'a> { let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str()); let symbol = unique(label, &mut self.next_suffix, &self.symbol_names); self.symbol_names.insert(symbol.clone()); - self.doc.symbols.push(Symbol { name: symbol.clone(), art: Arc::new(art) }); + self.doc.symbols.push(Symbol { dynamic: false, name: symbol.clone(), art: Arc::new(art) }); symbol }); self.symbols.insert(key, made.clone()); diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index 34e69d6edb..6ae29487a8 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -545,7 +545,7 @@ impl<'a> Scene<'a> { if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol) && self.nest < MAX_NEST { - let mut art = (*sym.art).clone(); + let mut art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n); art.transform(*xf, false); self.nest += 1; self.node(&art, true); diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index c08417b8de..ba0a13b768 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -986,7 +986,7 @@ fn crop_keeps_an_instance_whose_art_reaches_the_region() { // while the 20 × 20 square around the origin, moved to (-60, -60) to (-40, -40), is off it. let mut d = doc_with(|d| vec![Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Far".into(), xf: Affine::translate((-50.0, -50.0)) })]); let art = path(&mut d, shapes::rectangle(Rect::new(100.0, 50.0, 140.0, 90.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); - d.symbols.push(vectorcraft_doc::Symbol { name: "Far".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) }); let o = DxfOptions { crop: true, ..opts(&d) }; assert!(!kinds(&export(&d, &o).unwrap()).is_empty()); } diff --git a/crates/doc/src/depth.rs b/crates/doc/src/depth.rs index 8e4f807282..6f10da9b7a 100644 --- a/crates/doc/src/depth.rs +++ b/crates/doc/src/depth.rs @@ -485,7 +485,7 @@ mod tests { #[test] fn symbols_and_patterns_are_limited_too() { let mut d = Document::new(10.0, 10.0); - d.symbols.push(crate::Symbol { name: "s".into(), art: nested(MAX_DEPTH + 3) }); + d.symbols.push(crate::Symbol { dynamic: false, name: "s".into(), art: nested(MAX_DEPTH + 3) }); assert!(d.too_deep(None)); assert!(d.limit_depth()); assert!(!d.too_deep(None)); @@ -504,7 +504,7 @@ mod tests { for _ in 0..levels { art = Arc::new(Node::group(NodeId(3), vec![art])); } - d.symbols.push(crate::Symbol { name: format!("s{i}"), art }); + d.symbols.push(crate::Symbol { dynamic: false, name: format!("s{i}"), art }); } d } @@ -573,7 +573,7 @@ mod tests { }; let through_a_symbol = |d: &mut Document| { d.patterns.push(crate::PatternDef::new("p", vec![instance(2, "s")])); - d.symbols.push(crate::Symbol { name: "s".into(), art: painted(3, "p") }); + d.symbols.push(crate::Symbol { dynamic: false, name: "s".into(), art: painted(3, "p") }); }; for make in [&itself as &dyn Fn(&mut Document), &each_other, &through_a_symbol] { let mut d = doc(painted(1, "p")); diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 08503e8a77..e5ee6c4c8e 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -841,7 +841,7 @@ fn objects_at_matches_repeated_hits_on_random_documents() { fn objects_at_finds_symbol_instances_by_their_art() { let mut d = Document::new(200.0, 200.0); let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 60.0, 140.0, 80.0)), Appearance::default_art()); - d.symbols.push(crate::Symbol { name: "Far".into(), art: Arc::new(art) }); + d.symbols.push(crate::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) }); let (layer, top, inner, group) = (d.layers[0].id, d.alloc_id(), d.alloc_id(), d.alloc_id()); let instance = |id, dy: f64| Node::new(id, NodeKind::SymbolInstance { symbol: "Far".into(), xf: vectorcraft_geom::Affine::translate((0.0, dy)) }); d.insert(Some(layer), 0, instance(top, 0.0)).unwrap(); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index b6a9a60efc..333890c53b 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -24,11 +24,13 @@ pub mod intertwine; pub mod shared; mod symbol_export_type; mod symbol_nine_slice; +pub mod symbol_overrides; mod symbol_registration; pub use inline::{SYMBOL_HALF, SYMBOL_SIZES}; pub use shared::Shared; pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType}; pub use symbol_nine_slice::{SYMBOL_NINE_SLICE, SymbolNineSlice}; +pub use symbol_overrides::SymbolOverride; pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration}; pub mod links; pub mod live; diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index bf9259943b..a1268505fb 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -256,6 +256,7 @@ fn node_bytes(n: &Node, other: Option<&Node>) -> usize { if e.intertwine_tiers.capacity() > 0 { b += ALLOC + e.intertwine_tiers.capacity() * size_of::<PathData>() + e.intertwine_tiers.iter().map(path_bytes).sum::<usize>(); } + b += e.symbol_overrides.capacity() * size_of::<crate::SymbolOverride>(); b += e.objects_on_path.as_deref().map_or(0, |o| { ALLOC + size_of::<crate::objects_on_path::ObjectsOnPath>() + o.members.capacity() * size_of::<crate::objects_on_path::Member>() }); diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index 93145985be..239dce93c6 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -63,6 +63,9 @@ pub struct NodeExtras { pub compound_shape: bool, /// As a member of a compound shape, how this object combines with the members below it. pub shape_mode: crate::ShapeMode, + /// As an instance of a dynamic symbol, its own appearance changes to objects of the symbol's + /// art (see [`crate::symbol_overrides`]); empty for none. + pub symbol_overrides: Vec<crate::SymbolOverride>, } /// No extras: what [`Node::extras`] gives for a node without any. @@ -87,6 +90,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras { colorize: None, compound_shape: false, shape_mode: crate::ShapeMode::Add, + symbol_overrides: Vec::new(), }; /// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index 3456b359e2..ed81b13915 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -52,6 +52,7 @@ impl Serialize for Node { e.colorize.is_none(), is_default(&e.compound_shape), is_default(&e.shape_mode), + e.symbol_overrides.is_empty(), ]; let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?; let mut skip = skips.into_iter(); @@ -92,6 +93,7 @@ impl Serialize for Node { field!("colorize", &e.colorize); field!("compound_shape", &e.compound_shape); field!("shape_mode", &e.shape_mode); + field!("symbol_overrides", &e.symbol_overrides); st.end() } } @@ -138,26 +140,26 @@ fn count_one<E: serde::de::Error>() -> Result<(), E> { Ok(()) } -/// A member's Intertwine areas of tier 2 and up, each counting against [`with_node_budget`] as -/// an object does: a compressed file of repeated empty areas stays small while they take memory -/// once read. -fn counted_tiers<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<PathData>, D::Error> { - struct Tiers; - impl<'de> serde::de::Visitor<'de> for Tiers { - type Value = Vec<PathData>; +/// A list read from a file (a member's Intertwine areas of tier 2 and up, an instance's symbol +/// overrides), each item counting against [`with_node_budget`] as an object does: a compressed +/// file of repeated empty items stays small while they take memory once read. +fn counted_list<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Vec<T>, D::Error> { + struct Items<T>(std::marker::PhantomData<T>); + impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for Items<T> { + type Value = Vec<T>; fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - f.write_str("a list of areas") + f.write_str("a list") } - fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<PathData>, A::Error> { + fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<T>, A::Error> { let mut out = Vec::new(); - while let Some(area) = seq.next_element::<PathData>()? { + while let Some(item) = seq.next_element::<T>()? { count_one()?; - out.push(area); + out.push(item); } Ok(out) } } - d.deserialize_seq(Tiers) + d.deserialize_seq(Items(std::marker::PhantomData)) } /// How a [`Node`] is read: the flat field list of the file format. Fields move into the node @@ -216,7 +218,7 @@ pub(super) struct NodeWire { dimension: Option<Box<crate::dimension::Dimension>>, #[serde(default)] intertwine: Option<Box<PathData>>, - #[serde(default, deserialize_with = "counted_tiers")] + #[serde(default, deserialize_with = "counted_list")] intertwine_tiers: Vec<PathData>, #[serde(default)] live_paint_gaps: Option<Box<crate::live_paint::GapOptions>>, @@ -228,6 +230,8 @@ pub(super) struct NodeWire { compound_shape: bool, #[serde(default)] shape_mode: crate::ShapeMode, + #[serde(default, deserialize_with = "counted_list")] + symbol_overrides: Vec<crate::SymbolOverride>, } impl From<NodeWire> for Node { @@ -253,6 +257,7 @@ impl From<NodeWire> for Node { colorize: w.colorize, compound_shape: w.compound_shape, shape_mode: w.shape_mode, + symbol_overrides: w.symbol_overrides, }; Node { id: w.id, diff --git a/crates/doc/src/objects_on_path.rs b/crates/doc/src/objects_on_path.rs index ca2ec7dd99..779e2eced3 100644 --- a/crates/doc/src/objects_on_path.rs +++ b/crates/doc/src/objects_on_path.rs @@ -337,7 +337,7 @@ mod tests { // The art is a 40 × 10 box to the right of and below the origin, not the 20 × 20 square // around it that instances are measured by without the symbols. let mut d = crate::Document::new(400.0, 400.0); - d.symbols.push(crate::Symbol { name: "Bar".into(), art: Arc::new(rect(9, Rect::new(0.0, 0.0, 40.0, 10.0))) }); + d.symbols.push(crate::Symbol { dynamic: false, name: "Bar".into(), art: Arc::new(rect(9, Rect::new(0.0, 0.0, 40.0, 10.0))) }); let line = Node::path(NodeId(1), shapes::line(Point::new(100.0, 300.0), Point::new(300.0, 300.0)), Default::default()); let instance = Node::new(NodeId(2), NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::IDENTITY }); let other = rect(3, Rect::new(0.0, 0.0, 10.0, 10.0)); diff --git a/crates/doc/src/orient.rs b/crates/doc/src/orient.rs index 43c67d86f3..114a152909 100644 --- a/crates/doc/src/orient.rs +++ b/crates/doc/src/orient.rs @@ -200,7 +200,7 @@ mod tests { fn oriented_bounds_hug_a_rotated_symbol_instances_art() { let mut d = Document::new(500.0, 500.0); let bar = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 10.0)), Appearance::default_art()); - d.symbols.push(crate::Symbol { name: "Bar".into(), art: std::sync::Arc::new(bar) }); + d.symbols.push(crate::Symbol { dynamic: false, name: "Bar".into(), art: std::sync::Arc::new(bar) }); let (l, id) = (d.layers[0].id, d.alloc_id()); d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::translate((100.0, 100.0)) })).unwrap(); let c = Point::new(120.0, 105.0); diff --git a/crates/doc/src/placed_document.rs b/crates/doc/src/placed_document.rs index 9b00da57eb..310d7b784f 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -667,7 +667,7 @@ mod tests { pixels: None, })), ); - d.symbols.push(Symbol { name: "Star".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Star".into(), art: Arc::new(art) }); d.images.insert("pic".into(), ImageBlob::new("image/png", vec![1, 2, 3])); let mut children = vec![Arc::new(Node::new(NodeId(51), NodeKind::SymbolInstance { symbol: "Star".into(), xf: Affine::IDENTITY }))]; if bytes.starts_with(b"nest") { @@ -702,7 +702,11 @@ mod tests { fn the_art_and_its_resources_join_only_a_prepared_copy_under_their_own_names() { set_loader(stub_loader); let mut d = Document::new(200.0, 200.0); - d.symbols.push(Symbol { name: "Star".into(), art: Arc::new(Node::new(NodeId(60), NodeKind::Group { children: vec![], clip: false })) }); + d.symbols.push(Symbol { + dynamic: false, + name: "Star".into(), + art: Arc::new(Node::new(NodeId(60), NodeKind::Group { children: vec![], clip: false })), + }); d.images.insert("doc1-1".into(), ImageBlob::new("application/json", b"nest".to_vec())); let p = placed("doc1-1"); let layer = d.layers[0].id; diff --git a/crates/doc/src/records.rs b/crates/doc/src/records.rs index b13a1e955a..434a85a8fa 100644 --- a/crates/doc/src/records.rs +++ b/crates/doc/src/records.rs @@ -108,6 +108,10 @@ impl SavedSelection { pub struct Symbol { pub name: String, pub art: Arc<Node>, + /// Symbol Options › Symbol Type › Dynamic Symbol: each instance may change the appearance of + /// objects in the art and stay linked (see [`crate::symbol_overrides`]). Static by default. + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub dynamic: bool, } /// Encoded image bytes (PNG/JPEG/WebP…) shared by image objects. diff --git a/crates/doc/src/symbol_overrides.rs b/crates/doc/src/symbol_overrides.rs new file mode 100644 index 0000000000..b4e3a726f5 --- /dev/null +++ b/crates/doc/src/symbol_overrides.rs @@ -0,0 +1,190 @@ +//! Dynamic symbols (Symbol Options › Symbol Type › Dynamic Symbol): an instance of a dynamic +//! symbol keeps appearance changes of its own to objects in the symbol's art, while the art stays +//! the symbol's. Editing the symbol reshapes every instance and each keeps its changes; Reset drops +//! them. The changes are stored on the instance ([`crate::node::NodeExtras::symbol_overrides`]) and +//! applied wherever an instance is drawn or exported ([`dynamic_art`]). + +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; +use vectorcraft_color::{BlendMode, Paint}; + +use crate::{Node, NodeKind}; + +/// Deepest object an override may name: groups nested this deep in the symbol's art. +pub const MAX_PATH_DEPTH: usize = 64; + +/// One instance's appearance changes to one object of its dynamic symbol's art. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct SymbolOverride { + /// The object: child indices (paint order) from the art's root down through its groups; empty + /// for the root itself. + #[serde(deserialize_with = "short_path")] + pub path: Vec<u32>, + /// The object's (top) fill paint; type takes it as its characters' fill. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fill: Option<Paint>, + /// The object's (top) stroke paint; type takes it as its characters' stroke. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stroke: Option<Paint>, + /// The object's opacity, 0..1. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub opacity: Option<f32>, + /// The object's blending mode. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub blend: Option<BlendMode>, +} + +impl SymbolOverride { + /// Does this override change nothing? + pub fn is_empty(&self) -> bool { + self.fill.is_none() && self.stroke.is_none() && self.opacity.is_none() && self.blend.is_none() + } + + /// Put this override's changes on object `n`. + fn apply(&self, n: &mut Node) { + if let NodeKind::Text(t) = &mut n.kind { + for r in &mut t.runs { + if let Some(p) = &self.fill { + r.style.fill = p.clone(); + } + if let Some(p) = &self.stroke { + r.style.stroke = p.clone(); + } + } + } else { + if let Some(p) = &self.fill { + n.appearance.set_fill(p.clone()); + } + if let Some(p) = &self.stroke { + n.appearance.set_stroke(p.clone()); + } + } + if let Some(o) = self.opacity.filter(|o| o.is_finite()) { + n.opacity = o.clamp(0.0, 1.0); + } + if let Some(b) = self.blend { + n.blend = b; + } + } +} + +/// An override's path read from a file: at most [`MAX_PATH_DEPTH`] indices, so a compressed file +/// of one endless path stays small once read. +fn short_path<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<u32>, D::Error> { + struct Path; + impl<'de> serde::de::Visitor<'de> for Path { + type Value = Vec<u32>; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a list of child indices") + } + fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<u32>, A::Error> { + let mut out = Vec::new(); + while let Some(i) = seq.next_element::<u32>()? { + if out.len() == MAX_PATH_DEPTH { + return Err(serde::de::Error::custom(format!("a symbol override path is deeper than {MAX_PATH_DEPTH}"))); + } + out.push(i); + } + Ok(out) + } + } + d.deserialize_seq(Path) +} + +/// The children a path steps through: a group's (clip groups included) or a layer's. +fn groups_children(n: &Node) -> Option<&Vec<Arc<Node>>> { + matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }).then(|| n.children()).flatten() +} + +/// The object `path` names in symbol art `art`, if there is one. +pub fn part<'a>(art: &'a Node, path: &[u32]) -> Option<&'a Node> { + if path.len() > MAX_PATH_DEPTH { + return None; + } + path.iter().try_fold(art, |n, &i| groups_children(n)?.get(i as usize).map(|c| &**c)) +} + +/// [`part`], to change (the nodes on the way are copied when shared). +fn part_mut<'a>(art: &'a mut Node, path: &[u32]) -> Option<&'a mut Node> { + let Some((&i, rest)) = path.split_first() else { return Some(art) }; + if !matches!(art.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) { + return None; + } + let c = art.children_mut()?.get_mut(i as usize)?; + part_mut(Arc::make_mut(c), rest) +} + +/// Put `overrides` on symbol art `art`; an override naming no object of it is left out. +pub fn apply(art: &mut Node, overrides: &[SymbolOverride]) { + for o in overrides.iter().filter(|o| o.path.len() <= MAX_PATH_DEPTH) { + if let Some(n) = part_mut(art, &o.path) { + o.apply(n); + } + } +} + +/// Symbol art `art` as instance `inst` shows it: a copy with the instance's overrides applied. +pub fn dynamic_art(art: &Node, inst: &Node) -> Node { + let mut a = art.clone(); + apply(&mut a, &inst.extras().symbol_overrides); + a +} + +/// Keep the overrides that name an object of `art` (a symbol's new art), dropping the rest. +pub fn retain_parts(overrides: &mut Vec<SymbolOverride>, art: &Node) { + overrides.retain(|o| part(art, &o.path).is_some()); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Appearance, NodeId}; + use vectorcraft_color::Color; + use vectorcraft_geom::{Rect, shapes}; + + fn square(id: u64) -> Arc<Node> { + Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art())) + } + + fn art() -> Node { + let inner = Node::group(NodeId(3), vec![square(4), square(5)]); + Node::group(NodeId(1), vec![square(2), Arc::new(inner)]) + } + + #[test] + fn paths_name_objects_through_groups_only() { + let a = art(); + assert_eq!(part(&a, &[]).map(|n| n.id), Some(NodeId(1))); + assert_eq!(part(&a, &[1, 0]).map(|n| n.id), Some(NodeId(4))); + assert!(part(&a, &[2]).is_none()); + assert!(part(&a, &[0, 0]).is_none(), "a path has no children"); + assert!(part(&a, &[0; MAX_PATH_DEPTH + 1]).is_none()); + } + + #[test] + fn overrides_paint_their_object_and_skip_missing_ones() { + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let o = vec![ + SymbolOverride { path: vec![1, 1], fill: Some(red.clone()), opacity: Some(0.5), ..Default::default() }, + SymbolOverride { path: vec![9], fill: Some(red.clone()), ..Default::default() }, + ]; + let mut a = art(); + apply(&mut a, &o); + let n = part(&a, &[1, 1]).unwrap(); + assert_eq!(n.appearance.fill_paint(), red); + assert_eq!(n.opacity, 0.5); + assert_eq!(part(&a, &[1, 0]).unwrap().appearance.fill_paint(), Paint::solid(Color::WHITE), "its sibling keeps the symbol's look"); + let mut kept = o; + retain_parts(&mut kept, &a); + assert_eq!(kept.len(), 1); + } + + #[test] + fn a_path_deeper_than_the_cap_does_not_read() { + let deep = format!("{{\"path\":{:?}}}", vec![0; MAX_PATH_DEPTH + 1]); + assert!(serde_json::from_str::<SymbolOverride>(&deep).is_err()); + let ok: SymbolOverride = serde_json::from_str("{\"path\":[1,0],\"opacity\":0.25}").unwrap(); + assert_eq!(ok, SymbolOverride { path: vec![1, 0], opacity: Some(0.25), ..Default::default() }); + } +} diff --git a/crates/doc/src/symbols.rs b/crates/doc/src/symbols.rs index 8f095566b4..bb3cbf11f4 100644 --- a/crates/doc/src/symbols.rs +++ b/crates/doc/src/symbols.rs @@ -410,7 +410,7 @@ mod tests { /// Symbol `name` holding `art` in a group. fn symbol(d: &mut Document, name: &str, art: Vec<Node>) { let group = Node::group(d.alloc_id(), art.into_iter().map(Arc::new).collect()); - d.symbols.push(Symbol { name: name.into(), art: Arc::new(group) }); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(group) }); } #[test] diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index df94ba2c9f..37e2d39bca 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -225,7 +225,7 @@ fn art_on_a_locked_artboard_cannot_be_selected_or_edited() { fn art_on_artboard_measures_a_symbol_instance_by_its_art() { let mut d = Document::new(612.0, 792.0); let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); - d.symbols.push(Symbol { name: "Box".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Box".into(), art: Arc::new(art) }); let (layer, id) = (d.layers[0].id, d.alloc_id()); d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Box".into(), xf: Affine::translate((2.0, 2.0)) })).unwrap(); // The art, (2, 2) to (12, 12), lies inside; the 20 × 20 square, (-8, -8) to (12, 12), doesn't. diff --git a/crates/effects/src/adjust.rs b/crates/effects/src/adjust.rs index 93601680f0..a656f11e85 100644 --- a/crates/effects/src/adjust.rs +++ b/crates/effects/src/adjust.rs @@ -473,8 +473,8 @@ pub fn adjust_in_document(d: &mut Document, n: &Node) -> Option<Node> { let art; let src = match &n.kind { NodeKind::SymbolInstance { symbol, .. } if has_adjustment(n) => { - let symbol = d.symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone()); - art = crate::reshape::as_art(Some(d), n, symbol.as_deref())?; + let symbol = d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n)); + art = crate::reshape::as_art(Some(d), n, symbol.as_ref())?; &art } _ => n, diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index e713e0ffa3..ee8aba6c26 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -122,10 +122,12 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> { return Some(bake_pieces(d, m)); } let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, .. } => d.symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone()), + NodeKind::SymbolInstance { symbol, .. } => { + d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n)) + } _ => None, }; - let m = reshape(Some(d), n, symbol.as_deref())?; + let m = reshape(Some(d), n, symbol.as_ref())?; return Some(bake_node(d, &m).unwrap_or(m)); } // A path whose Transform effect copies it with a gradient, or scales its strokes or moves its diff --git a/crates/effects/src/live.rs b/crates/effects/src/live.rs index aad8d8edd9..769eae6b53 100644 --- a/crates/effects/src/live.rs +++ b/crates/effects/src/live.rs @@ -24,7 +24,7 @@ fn outline(doc: Option<&Document>, n: &Node) -> Option<Node> { match &n.kind { NodeKind::SymbolInstance { symbol, xf } => { let sym = doc?.symbols.iter().find(|s| s.name == *symbol)?; - let mut art = (*sym.art).clone(); + let mut art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n); art.transform(*xf, false); Some(Node::group(n.id, vec![Arc::new(art)])) } diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 198da329e8..cff94b0f46 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -1191,10 +1191,10 @@ fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() { let instance = |name: &str| Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })); let mut d = Document::new(100.0, 100.0); // A 500 × 500 grid as a symbol's art, directly and inside a group; a symbol holding itself. - d.symbols.push(Symbol { name: "Grid".into(), art: repeat(grid(unit(), 500)) }); - d.symbols.push(Symbol { name: "Grouped".into(), art: Arc::new(Node::group(NodeId(0), vec![repeat(grid(unit(), 500))])) }); - d.symbols.push(Symbol { name: "Loop".into(), art: Arc::new(Node::group(NodeId(0), vec![unit(), instance("Loop")])) }); - d.symbols.push(Symbol { name: "Small".into(), art: repeat(grid(unit(), 3)) }); + d.symbols.push(Symbol { dynamic: false, name: "Grid".into(), art: repeat(grid(unit(), 500)) }); + d.symbols.push(Symbol { dynamic: false, name: "Grouped".into(), art: Arc::new(Node::group(NodeId(0), vec![repeat(grid(unit(), 500))])) }); + d.symbols.push(Symbol { dynamic: false, name: "Loop".into(), art: Arc::new(Node::group(NodeId(0), vec![unit(), instance("Loop")])) }); + d.symbols.push(Symbol { dynamic: false, name: "Small".into(), art: repeat(grid(unit(), 3)) }); // A 3 × 3 grid of an instance of each: each copy draws 250,000 instances, so one copy fits. for name in ["Grid", "Grouped"] { let outer = Node::new(NodeId(0), NodeKind::Repeat(grid(instance(name), 3))); diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 9bb04dac92..04498111c9 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -335,7 +335,7 @@ fn scatter_shapes() -> BrushLibrary { a.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(gold)))); a }); - doc.symbols.push(Symbol { name: "Sparkle".into(), art: Arc::new(sparkle) }); + doc.symbols.push(Symbol { dynamic: false, name: "Sparkle".into(), art: Arc::new(sparkle) }); let instance = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Sparkle".into(), xf: Affine::scale(0.3) }); let random = |a: f64, b: f64| (a, b); let base = Scatter { colorization: Colorization::Tints, ..Default::default() }; diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 2124667ced..4f335dc0cb 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -25,6 +25,7 @@ use super::{ use crate::EngineError; mod brushes; +mod dynamic; mod symbols; pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; @@ -32,6 +33,8 @@ use brushes::{ brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_remove, brush_selection_art, brush_set_current, brush_unused, expand_brush, }; +use dynamic::{symbol_instance_reset, symbol_instance_set_appearance}; +use symbols::selected_instances; pub(crate) use symbols::{instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol}; use symbols::{ symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_edit, symbol_list, symbol_new, symbol_options, symbol_place, @@ -157,13 +160,21 @@ pub fn specs() -> Vec<CommandSpec> { brush_freehand ), // ----- symbols ----- - cmd!(query "symbol.list", "Symbols", [], None, "{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic}], current}", has_doc, symbol_list), + cmd!( + query "symbol.list", + "Symbols", + [], + None, + "{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic}], current}", + has_doc, + symbol_list + ), cmd!( "symbol.new", "New Symbol…", [], None, - "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions 0..1 of the natural size (default a third each) → {name, id, registration, exportType, nineSlice}", + "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions 0..1 of the natural size (default a third each) → {name, id, registration, exportType, nineSlice, type}", has_selection, symbol_new ), @@ -172,7 +183,7 @@ pub fn specs() -> Vec<CommandSpec> { "Symbol Options…", [], None, - "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array} rename a symbol and/or set Symbol Options › Registration and Export Type and 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1; default name: current) → {name, registration, exportType, nineSlice}", + "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}", has_doc, symbol_options ), @@ -190,7 +201,7 @@ pub fn specs() -> Vec<CommandSpec> { "Break Link to Symbol", [], None, - "{ids?|id?} expand selected instances into plain art → {ids}", + "{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol) → {ids}", has_selection, symbol_break_link ), @@ -199,7 +210,7 @@ pub fn specs() -> Vec<CommandSpec> { "Edit Symbol", [], None, - "{id?, ids?: [id…] (instead of id)} break the link of the selected instance so its art can be edited; finish with symbol.update → {name, ids}", + "{id?, ids?: [id…] (instead of id)} break the link of the selected instance so the symbol's art can be edited (without the instance's own appearance changes to a dynamic symbol); finish with symbol.update → {name, ids}", has_selection, symbol_edit ), @@ -208,7 +219,7 @@ pub fn specs() -> Vec<CommandSpec> { "Redefine Symbol", [], None, - "{name, ids?|id?} replace the symbol's art with the selection (instances update; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}", + "{name, ids?|id?} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}", has_selection, symbol_update ), @@ -227,10 +238,28 @@ pub fn specs() -> Vec<CommandSpec> { "Replace Symbol", [], None, - "{name, ids?|id?} swap the symbol of the selected instances → {ids}", + "{name, ids?|id?} swap the symbol of the selected instances (they keep their appearance changes to the objects at paths a dynamic new symbol's art has) → {ids}", has_selection, symbol_replace ), + cmd!( + "symbol.instance.setAppearance", + "Symbol Instance Appearance", + [], + None, + "{id?|ids?: [one id] (default: the one selected object), path: [i…] (the object in the symbol's art: child indices in paint order from the art's root down through its groups; [] the root), fill?: \"#rrggbb\"|{…paint params of paint.setFill: color, none, swatch, tint, gradient, keepModel}|null (null: the symbol's own again), stroke?: as fill, opacity?: 0..100|null, blend?: name|null} change the appearance of one object of a dynamic symbol instance's art, for that instance only: it stays linked, so editing the symbol reshapes it and keeps the change; refused for a static symbol or a path naming no object → {id, overrides: how many objects the instance changes}", + has_selection, + symbol_instance_set_appearance + ), + cmd!( + "symbol.instance.reset", + "Reset Symbol Instance", + [], + None, + "{ids?|id?} drop the selected dynamic symbol instances' own appearance changes, so they show the symbol's appearance again → {ids: the instances that had changes}", + has_selection, + symbol_instance_reset + ), cmd!( "symbol.setCurrent", "Current Symbol", diff --git a/crates/engine/src/cmd/brushsym/dynamic.rs b/crates/engine/src/cmd/brushsym/dynamic.rs new file mode 100644 index 0000000000..baa721c45b --- /dev/null +++ b/crates/engine/src/cmd/brushsym/dynamic.rs @@ -0,0 +1,151 @@ +//! Dynamic symbols (Symbol Options › Symbol Type): an instance of a dynamic symbol changes the +//! appearance of objects in the symbol's art and stays linked to the symbol +//! (`symbol.instance.setAppearance`, `symbol.instance.reset`). The changes live on the instance +//! ([`vectorcraft_doc::symbol_overrides`]); editing the symbol keeps those whose object is still +//! there ([`fit_overrides`]). + +use std::sync::Arc; + +use vectorcraft_color::BlendMode; +use vectorcraft_doc::symbol_overrides::{self, SymbolOverride}; + +use super::{Document, EngineError, Node, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, ids_json, json, roots, selected_instances}; + +/// The `type` param, Symbol Options › Symbol Type: `Some(true)` for dynamic. +pub(super) fn type_param(p: &Value, cmd: &str) -> Result<Option<bool>> { + let Some(v) = p.get("type").filter(|v| !v.is_null()) else { return Ok(None) }; + match v.as_str() { + Some("static") => Ok(Some(false)), + Some("dynamic") => Ok(Some(true)), + _ => Err(bad(cmd, format!("type must be static or dynamic, not {v}"))), + } +} + +/// The `type` a symbol reports. +pub(super) fn type_id(dynamic: bool) -> &'static str { + if dynamic { "dynamic" } else { "static" } +} + +/// Fit the appearance changes of instances `ids` to their symbols: an instance of a static (or +/// missing) symbol keeps none, an instance of a dynamic one those naming an object of its art. +pub(super) fn fit_overrides(d: &mut Document, ids: &[NodeId]) { + for id in ids { + let art = match d.node(*id) { + Some(n) if !n.extras().symbol_overrides.is_empty() => match &n.kind { + NodeKind::SymbolInstance { symbol, .. } => d.symbols.iter().find(|s| s.name == *symbol).filter(|s| s.dynamic).map(|s| s.art.clone()), + _ => continue, + }, + _ => continue, + }; + let Some(n) = d.node_mut(*id) else { continue }; + let mut e = n.extras_mut(); + match art { + Some(art) => symbol_overrides::retain_parts(&mut e.symbol_overrides, &art), + None => e.symbol_overrides.clear(), + } + } +} + +/// The instance `id` names (else the one selected object) and its symbol's art; the symbol must +/// be dynamic. +fn dynamic_instance(s: &Session, p: &Value, cmd: &str) -> Result<(NodeId, Arc<Node>)> { + let d = &s.doc()?.doc; + let not_one = || EngineError::Other("select a symbol instance".into()); + let [id] = roots(s, p)?[..] else { return Err(not_one()) }; + let Some(NodeKind::SymbolInstance { symbol, .. }) = d.node(id).map(|n| &n.kind) else { return Err(not_one()) }; + let sym = d.symbols.iter().find(|x| x.name == *symbol).ok_or_else(|| bad(cmd, format!("no symbol named `{n}`", n = symbol)))?; + if !sym.dynamic { + let name = &sym.name; + return Err(bad(cmd, format!("`{name}` is a static symbol: set its Symbol Type to Dynamic first"))); + } + Ok((id, sym.art.clone())) +} + +/// The `path` param: child indices from the art's root, naming an object of `art`. +fn path_param(p: &Value, art: &Node, cmd: &str) -> Result<Vec<u32>> { + let path: Option<Vec<u32>> = + p.get("path").and_then(Value::as_array).and_then(|a| a.iter().map(|i| i.as_u64().and_then(|i| u32::try_from(i).ok())).collect()); + let path = path.ok_or_else(|| bad(cmd, "path must be a list of child indices"))?; + if symbol_overrides::part(art, &path).is_none() { + let shown = json!(path); + return Err(bad(cmd, format!("no object at path {shown} in the symbol's art"))); + } + Ok(path) +} + +/// `fill` or `stroke` of `p` for override `o`: absent leaves it, null clears it, a colour string or +/// an object of `paint.setFill`'s paint params sets it. +fn paint_change(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<Option<Option<vectorcraft_color::Paint>>> { + let Some(v) = p.get(key) else { return Ok(None) }; + if v.is_null() { + return Ok(Some(None)); + } + let v = if v.is_string() { json!({ "color": v }) } else { v.clone() }; + let paint = crate::cmd::paint::paint_from(s, &v)?.ok_or_else(|| bad(cmd, "give color, none, swatch or gradient"))?; + Ok(Some(Some(paint))) +} + +/// The change `p` asks of the override `old` (for the object at `path`). +fn changed(s: &Session, p: &Value, old: SymbolOverride, cmd: &str) -> Result<SymbolOverride> { + let mut o = old; + if let Some(fill) = paint_change(s, p, "fill", cmd)? { + o.fill = fill; + } + if let Some(stroke) = paint_change(s, p, "stroke", cmd)? { + o.stroke = stroke; + } + check_numbers(p, &["opacity"], cmd)?; + if let Some(v) = p.get("opacity") { + o.opacity = v.as_f64().map(crate::cmd::opacitymask::percent); + } + if let Some(v) = p.get("blend") { + o.blend = match v { + Value::Null => None, + b => Some(b.as_str().and_then(BlendMode::parse).ok_or_else(|| bad(cmd, format!("unknown blend mode {b}")))?), + }; + } + Ok(o) +} + +pub(super) fn symbol_instance_set_appearance(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "symbol.instance.setAppearance"; + if !["fill", "stroke", "opacity", "blend"].iter().any(|k| p.get(k).is_some()) { + return Err(bad(C, "give fill, stroke, opacity and/or blend")); + } + let (id, art) = dynamic_instance(s, p, C)?; + let path = path_param(p, &art, C)?; + let d = &s.doc()?.doc; + let old = d.node(id).and_then(|n| n.extras().symbol_overrides.iter().find(|o| o.path == path).cloned()); + let new = changed(s, p, old.unwrap_or_else(|| SymbolOverride { path: path.clone(), ..Default::default() }), C)?; + let count = s.edit("Symbol Instance Appearance", |d, _| { + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + let mut e = n.extras_mut(); + let list = &mut e.symbol_overrides; + list.retain(|o| o.path != path); + if !new.is_empty() { + list.push(new); + } + Ok(list.len()) + })?; + Ok(json!({ "id": id.0, "overrides": count })) +} + +pub(super) fn symbol_instance_reset(s: &mut Session, p: &Value) -> Result<Value> { + let ids = selected_instances(s, p)?; + if ids.is_empty() { + return Err(EngineError::Other("no symbol instances selected".into())); + } + let d = &s.doc()?.doc; + let changed: Vec<NodeId> = ids.into_iter().filter(|id| d.node(*id).is_some_and(|n| !n.extras().symbol_overrides.is_empty())).collect(); + if !changed.is_empty() { + s.edit("Reset Symbol Instance", |d, _| { + for id in &changed { + if let Some(n) = d.node_mut(*id) { + n.extras_mut().symbol_overrides.clear(); + } + } + Ok(()) + })?; + } + Ok(json!({ "ids": ids_json(&changed) })) +} diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index d1ce429a04..c7fe433541 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1,3 +1,4 @@ +use super::dynamic::{fit_overrides, type_id, type_param}; use super::{ Affine, AppearanceItem, Arc, CURRENT_SYMBOL, Color, Document, EngineError, FillLayer, HALF, Node, NodeId, NodeKind, Paint, Point, Result, SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_value, ids_json, json, @@ -128,6 +129,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> { "registration": d.symbol_registration(&sym.name).0, "exportType": d.symbol_export_type(&sym.name).id(), "nineSlice": nine_slice_json(d, &sym.name), + "type": type_id(sym.dynamic), }) }) .collect(); @@ -138,7 +140,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> { /// current symbol. pub(crate) fn store_symbol(d: &mut Document, art: &Node, name: &str, size: (f64, f64)) { let art = d.reid(art); - d.symbols.push(Symbol { name: name.into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); set_natural_size(d, name, Some(size)); d.unknown.insert(CURRENT_SYMBOL.into(), json!(name)); } @@ -179,10 +181,14 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> { let reg = registration_param(p, C)?.unwrap_or(SymbolRegistration::CENTER); let export = export_type_param(p, C)?.unwrap_or_default(); let nine = nine_slice_param(p, C, None)?.flatten(); + let dynamic = type_param(p, C)?.unwrap_or(false); // Keep the art where it was: the geometric centre stays at `c`, whatever the registration is. let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg); let id = s.edit("New Symbol", |d, sel| { store_symbol(d, &art, &name, size); + if let Some(sym) = d.symbols.iter_mut().find(|x| x.name == name) { + sym.dynamic = dynamic; + } d.set_symbol_registration(&name, reg); d.set_symbol_export_type(&name, export); d.set_symbol_nine_slice(&name, nine); @@ -190,9 +196,14 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> { sel.set([id]); Ok(id) })?; - Ok( - json!({ "name": name, "id": id.0, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) }), - ) + Ok(json!({ + "name": name, + "id": id.0, + "registration": reg.0, + "exportType": export.id(), + "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value), + "type": type_id(dynamic), + })) } pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> { @@ -201,9 +212,10 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> { let export = export_type_param(p, C)?; let reg = registration_param(p, C)?; let nine = nine_slice_param(p, C, s.doc()?.doc.symbol_nine_slice(&name))?; + let dynamic = type_param(p, C)?; let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); - if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() { - return Err(bad(C, "pass newName, registration, exportType and/or nineSlice")); + if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() { + return Err(bad(C, "pass newName, registration, exportType, nineSlice and/or type")); } if let Some(ref n) = new_name && n != &name @@ -241,6 +253,13 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> { if let Some(g) = nine { d.set_symbol_nine_slice(&final_name, g); } + if let Some(dynamic) = dynamic + && let Some(sym) = d.symbols.iter_mut().find(|x| x.name == final_name) + { + // A static symbol's instances drop their own appearance changes. + sym.dynamic = dynamic; + fit_overrides(d, &instances_of(d, Some(&final_name))); + } Ok(()) })?; let d = &s.doc()?.doc; @@ -249,6 +268,7 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> { "registration": d.symbol_registration(&final_name).0, "exportType": d.symbol_export_type(&final_name).id(), "nineSlice": nine_slice_json(d, &final_name), + "type": type_id(d.symbols.iter().any(|x| x.name == final_name && x.dynamic)), })) } @@ -279,11 +299,12 @@ pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "id": id.0 })) } -/// The plain art of instance `inst` in document space (fresh ids). -fn expanded_instance(d: &mut Document, inst: &Node) -> Option<Node> { +/// The plain art of instance `inst` in document space (fresh ids), with the instance's own +/// appearance changes to a dynamic symbol's art when `own`. +fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option<Node> { let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None }; let sym = d.symbols.iter().find(|s| &s.name == symbol)?; - let mut art = (*sym.art).clone(); + let mut art = if own { vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst) } else { (*sym.art).clone() }; if let Some(f) = inst.appearance.fill() && let Some(c) = f.paint.color() { @@ -302,11 +323,13 @@ fn expanded_instance(d: &mut Document, inst: &Node) -> Option<Node> { Some(art) } -fn break_links(d: &mut Document, ids: &[NodeId]) -> Result<Vec<NodeId>> { +/// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). Returns the +/// art's ids. +fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result<Vec<NodeId>> { let mut out = vec![]; for id in ids { let Some(inst) = d.node(*id).cloned() else { continue }; - let Some(art) = expanded_instance(d, &inst) else { continue }; + let Some(art) = expanded_instance(d, &inst, own) else { continue }; let (par, idx, _) = d.position(*id).ok_or(EngineError::NoNode(*id))?; let aid = art.id; d.remove(*id)?; @@ -316,7 +339,7 @@ fn break_links(d: &mut Document, ids: &[NodeId]) -> Result<Vec<NodeId>> { Ok(out) } -fn selected_instances(s: &Session, p: &Value) -> Result<Vec<NodeId>> { +pub(super) fn selected_instances(s: &Session, p: &Value) -> Result<Vec<NodeId>> { let d = &s.doc()?.doc; let mut out = vec![]; for id in roots(s, p)? { @@ -337,7 +360,7 @@ pub(super) fn symbol_break_link(s: &mut Session, p: &Value) -> Result<Value> { return Err(EngineError::Other("no symbol instances selected".into())); } let out = s.edit("Break Link to Symbol", |d, sel| { - let out = break_links(d, &ids)?; + let out = break_links(d, &ids, true)?; sel.set(out.iter().copied()); Ok(out) })?; @@ -351,8 +374,9 @@ pub(super) fn symbol_edit(s: &mut Session, p: &Value) -> Result<Value> { Some(NodeKind::SymbolInstance { symbol, .. }) => symbol.clone(), _ => return Err(EngineError::Other("select a symbol instance".into())), }; + // The symbol's own art: one instance's appearance changes would become every instance's. let out = s.edit("Edit Symbol", |d, sel| { - let out = break_links(d, &[first])?; + let out = break_links(d, &[first], false)?; sel.set(out.iter().copied()); Ok(out) })?; @@ -377,11 +401,14 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> { } set_natural_size(d, &name, Some(size)); let fix = Affine::scale_non_uniform(size.0 / old.0, size.1 / old.1); - for i in instances_of(d, Some(&name)) { - if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(i).map(|n| &mut n.kind) { + let instances = instances_of(d, Some(&name)); + for i in &instances { + if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(*i).map(|n| &mut n.kind) { *xf *= fix; } } + // Each instance keeps its appearance changes to the objects the new art still has. + fit_overrides(d, &instances); let reg = d.symbol_registration(&name); let id = instance_in_place(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?; sel.set([id]); @@ -400,7 +427,7 @@ pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result<Value> { s.edit("Delete Symbol", |d, _| { let inst = instances_of(d, Some(&name)); if expand { - break_links(d, &inst)?; + break_links(d, &inst, true)?; } else { remove_each(d, &inst)?; } @@ -430,7 +457,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result<Value> { let nine = d.symbol_nine_slice(&name); s.edit("Duplicate Symbol", |d, _| { let art = d.reid(&sym.art); - d.symbols.push(Symbol { name: new.clone(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: sym.dynamic, name: new.clone(), art: Arc::new(art) }); set_natural_size(d, &new, Some(size)); d.set_symbol_registration(&new, reg); d.set_symbol_export_type(&new, export); @@ -462,6 +489,7 @@ pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result<Value> { *xf *= Affine::scale_non_uniform(new.0 / old.0, new.1 / old.1); } } + fit_overrides(d, &ids); Ok(()) })?; Ok(json!({ "ids": ids_json(&ids) })) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 25a5ff004d..8010931a70 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -682,10 +682,12 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br // Type, images, symbol instances, live objects (and paths whose Transform effect copies // them with a gradient or changes their fills and strokes): through their outlines. let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, .. } => d.symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone()), + NodeKind::SymbolInstance { symbol, .. } => { + d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, &n)) + } _ => None, }; - effects::expand_outlined(Some(&*d), &v, symbol.as_deref()).map(|mut m| { + effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| { expand_pieces(d, &mut m, true, brushes, &mut stroke_art); m }) diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index 3f0c80944c..49e9f5a614 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -181,7 +181,7 @@ fn basic_shapes() -> SymbolLibrary { let id = doc.alloc_id(); let art = Node::path(id, path, Appearance::basic(Paint::solid(fill), Paint::solid(edge), 1.0)); let Ok((art, size, _)) = normalize(art) else { continue }; - doc.symbols.push(Symbol { name: name.into(), art: Arc::new(art) }); + doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); set_natural_size(&mut doc, name, Some(size)); } doc.title = "Basic Shapes".into(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c6a2a06bea..c5baf054d1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -41,6 +41,7 @@ mod dashalign; mod distort; mod docsetup; mod draw2; +mod dynamic_symbols; mod editcolors; mod effectedit; mod emptytype; diff --git a/crates/engine/src/tests/docsetup.rs b/crates/engine/src/tests/docsetup.rs index acd6cd58be..c1c70ac07e 100644 --- a/crates/engine/src/tests/docsetup.rs +++ b/crates/engine/src/tests/docsetup.rs @@ -256,7 +256,7 @@ fn a_file_with_script_proportions_out_of_range_opens_with_them_in_range() { } let mut art = d.node(id).unwrap().clone(); art.id = NodeId(9000); - d.symbols.push(vectorcraft_doc::Symbol { name: "Formula".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Formula".into(), art: Arc::new(art) }); if let Some(g) = d.node_mut(graph).and_then(|n| n.extras_if_any()).and_then(|e| e.graph.as_deref_mut()) { let position = CharPosition::Subscript(ScriptMetrics { size: 0.0, position: 1000.0 }); g.label_styles.legend = Some(vectorcraft_doc::CharStyle { position, small_caps: Some(0.0), ..vectorcraft_doc::CharStyle::default() }); diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs new file mode 100644 index 0000000000..a580106d3c --- /dev/null +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -0,0 +1,165 @@ +//! Dynamic symbols (#4938): an instance changes the appearance of objects in its symbol's art and +//! stays linked; editing the symbol keeps those changes, Reset and Break Link handle them. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_geom::Rect; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + s +} + +fn id(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +/// A blue square at `x` (40 pt, no stroke). +fn square(s: &mut Session, x: f64) -> NodeId { + let r = id(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [r.0], "color": "#0000ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [r.0], "none": true})).unwrap(); + r +} + +/// Symbol "Pair" of two blue squares (x 10..50 and 60..100) of `kind`, made in place: its instance. +fn pair(s: &mut Session, kind: &str) -> NodeId { + let (a, b) = (square(s, 10.0), square(s, 60.0)); + id(&s.execute("symbol.new", &json!({"name": "Pair", "ids": [a.0, b.0], "type": kind})).unwrap()) +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +fn overrides(s: &Session, id: NodeId) -> usize { + node(s, id).extras().symbol_overrides.len() +} + +fn pixel(s: &Session, x: u32, y: u32) -> [u8; 4] { + vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 200.0, 100.0), 1.0, true).pixel(x, y) +} + +const RED: [u8; 4] = [255, 0, 0, 255]; +const BLUE: [u8; 4] = [0, 0, 255, 255]; + +#[test] +fn a_dynamic_instance_paints_one_object_its_own_way_and_stays_linked() { + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + assert_eq!(s.execute("symbol.list", &json!({})).unwrap()["symbols"][0]["type"], "dynamic"); + let other = id(&s.execute("symbol.place", &json!({"name": "Pair", "x": 55, "y": 80})).unwrap()); + let r = s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [1], "fill": "#ff0000"})).unwrap(); + assert_eq!(r["overrides"], 1); + assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }), "still an instance"); + assert_eq!(pixel(&s, 80, 30), RED, "the changed object"); + assert_eq!(pixel(&s, 30, 30), BLUE, "its sibling keeps the symbol's look"); + assert_eq!(overrides(&s, other), 0, "other instances keep the symbol's look"); + // A later change to the same object merges with the first; null takes one back. + s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [1], "opacity": 50})).unwrap(); + assert_eq!(node(&s, inst).extras().symbol_overrides[0].opacity, Some(0.5)); + s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [1], "opacity": null})).unwrap(); + let o = node(&s, inst).extras().symbol_overrides[0].clone(); + assert!(o.opacity.is_none() && o.fill.is_some()); + // SVG export draws it too. + let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let svg = String::from_utf8(vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).unwrap(); + assert!(svg.to_ascii_lowercase().contains("#ff0000") || svg.contains("rgb(255,0,0)"), "{svg}"); +} + +#[test] +fn static_symbols_and_bad_targets_are_refused() { + let mut s = session(); + let inst = pair(&mut s, "static"); + let set = |s: &mut Session, p: Value| s.execute("symbol.instance.setAppearance", &p); + assert!(set(&mut s, json!({"id": inst.0, "path": [0], "fill": "#ff0000"})).is_err(), "a static symbol"); + s.execute("symbol.options", &json!({"name": "Pair", "type": "dynamic"})).unwrap(); + for bad in [ + json!({"id": inst.0, "path": [2], "fill": "#ff0000"}), + json!({"id": inst.0, "path": [0, 0], "fill": "#ff0000"}), + json!({"id": inst.0, "path": [-1], "fill": "#ff0000"}), + json!({"id": inst.0, "path": "0", "fill": "#ff0000"}), + json!({"id": inst.0, "fill": "#ff0000"}), + json!({"id": inst.0, "path": [0]}), + json!({"id": inst.0, "path": [0], "blend": "sparkle"}), + json!({"id": inst.0, "path": [0], "opacity": "half"}), + json!({"id": inst.0, "path": [0], "fill": {}}), + ] { + assert!(set(&mut s, bad.clone()).is_err(), "{bad}"); + } + let plain = square(&mut s, 120.0); + assert!(set(&mut s, json!({"id": plain.0, "path": [], "fill": "#ff0000"})).is_err(), "not an instance"); + assert!(s.execute("symbol.options", &json!({"name": "Pair", "type": "sometimes"})).is_err()); + assert_eq!(overrides(&s, inst), 0); +} + +#[test] +fn redefining_the_symbol_keeps_the_changes_whose_objects_remain() { + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [1], "fill": "#ff0000"})).unwrap(); + // New geometry with the same structure: two squares, now 10..40 and 50..80 tall. + let (a, b) = (square(&mut s, 10.0), square(&mut s, 120.0)); + s.execute("symbol.update", &json!({"name": "Pair", "ids": [a.0, b.0]})).unwrap(); + assert_eq!(overrides(&s, inst), 1, "the change follows the edited symbol"); + // Art of one object (no children) leaves path [1] behind. + let c = square(&mut s, 10.0); + s.execute("symbol.update", &json!({"name": "Pair", "ids": [c.0]})).unwrap(); + assert_eq!(overrides(&s, inst), 0); +} + +#[test] +fn reset_and_static_drop_the_changes_and_undo_brings_them_back() { + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [0], "fill": "#ff0000", "blend": "multiply"})).unwrap(); + let r = s.execute("symbol.instance.reset", &json!({"ids": [inst.0]})).unwrap(); + assert_eq!(r["ids"], json!([inst.0])); + assert_eq!(overrides(&s, inst), 0); + assert_eq!(pixel(&s, 30, 30), BLUE); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(overrides(&s, inst), 1); + // Nothing to reset: no undo step. + let other = id(&s.execute("symbol.place", &json!({"name": "Pair"})).unwrap()); + let undo = s.doc().unwrap().history.undo.len(); + assert_eq!(s.execute("symbol.instance.reset", &json!({"ids": [other.0]})).unwrap()["ids"], json!([])); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + // Static again: the instances show the symbol's appearance. + s.execute("symbol.options", &json!({"name": "Pair", "type": "static"})).unwrap(); + assert_eq!(overrides(&s, inst), 0); +} + +#[test] +fn break_link_bakes_the_changes_and_edit_symbol_shows_the_symbols_own_art() { + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [1], "fill": "#ff0000"})).unwrap(); + let other = id(&s.execute("symbol.place", &json!({"name": "Pair", "x": 55, "y": 80})).unwrap()); + s.execute("symbol.instance.setAppearance", &json!({"id": other.0, "path": [1], "fill": "#ff0000"})).unwrap(); + let fills = |s: &Session, art: NodeId| -> Vec<String> { + node(s, art).children().unwrap().iter().map(|c| c.appearance.fill_paint().color().unwrap().to_hex()).collect() + }; + let art = NodeId(s.execute("symbol.breakLink", &json!({"ids": [inst.0]})).unwrap()["ids"][0].as_u64().unwrap()); + assert_eq!(fills(&s, art), ["#0000ff", "#ff0000"]); + let art = NodeId(s.execute("symbol.edit", &json!({"ids": [other.0]})).unwrap()["ids"][0].as_u64().unwrap()); + assert_eq!(fills(&s, art), ["#0000ff", "#0000ff"], "the symbol's art, without this instance's changes"); +} + +#[test] +fn dynamic_symbols_and_their_changes_round_trip_and_old_documents_save_as_before() { + let mut s = session(); + pair(&mut s, "static"); + let json = serde_json::to_string(&s.doc().unwrap().doc).unwrap(); + assert!(!json.contains("\"dynamic\"") && !json.contains("symbol_overrides"), "nothing new is written for static symbols"); + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [1], "fill": "#ff0000", "opacity": 25})).unwrap(); + let doc = &s.doc().unwrap().doc; + let back = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap(); + assert!(back.symbols[0].dynamic); + assert_eq!(back.node(inst).unwrap().extras().symbol_overrides, doc.node(inst).unwrap().extras().symbol_overrides); + assert_eq!(back.symbols, doc.symbols); +} diff --git a/crates/engine/src/tests/envelope_distort.rs b/crates/engine/src/tests/envelope_distort.rs index 1ad528544b..b42b1da027 100644 --- a/crates/engine/src/tests/envelope_distort.rs +++ b/crates/engine/src/tests/envelope_distort.rs @@ -274,7 +274,7 @@ fn symbols_bend_with_the_envelope() { shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), ); - d.symbols.push(Symbol { name: "Box".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Box".into(), art: Arc::new(art) }); let id = d.alloc_id(); let xf = Affine::translate((200.0, 150.0)) * Affine::scale_non_uniform(10.0, 5.0); d.insert(d.default_layer(), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Box".into(), xf }))?; diff --git a/crates/engine/src/tests/pdfraster.rs b/crates/engine/src/tests/pdfraster.rs index f6e54bd0c1..1e0a2ecfde 100644 --- a/crates/engine/src/tests/pdfraster.rs +++ b/crates/engine/src/tests/pdfraster.rs @@ -119,9 +119,9 @@ fn groups_layers_type_images_and_symbols_keep_their_raster_effects() { // A symbol instance with a shadow, and a symbol whose art blurs. let mut d = Document::new(200.0, 200.0); let art = rect(&mut d, Rect::new(0.0, 0.0, 50.0, 50.0), Color::rgb(0.9, 0.6, 0.0)); - d.symbols.push(Symbol { name: "Tile".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Tile".into(), art: Arc::new(art) }); let blurred = with(rect(&mut d, Rect::new(0.0, 0.0, 40.0, 40.0), Color::rgb(0.2, 0.2, 0.8)), blur()); - d.symbols.push(Symbol { name: "Soft".into(), art: Arc::new(blurred) }); + d.symbols.push(Symbol { dynamic: false, name: "Soft".into(), art: Arc::new(blurred) }); let inst = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Tile".into(), xf: Affine::translate((30.0, 30.0)) }); add(&mut d, with(inst, shadow())); let soft = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Soft".into(), xf: Affine::translate((120.0, 120.0)) }); diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index eb3164db8f..2182769aa4 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -32,7 +32,7 @@ fn star_source(path: &str, title: &str) { d.title = title.into(); let layer = d.layers[0].id; let art = Node::path(vectorcraft_doc::NodeId(900), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), look(BLUE)); - d.symbols.push(vectorcraft_doc::Symbol { name: "Star".into(), art: std::sync::Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Star".into(), art: std::sync::Arc::new(art) }); let id = d.alloc_id(); d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Star".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap(); write(path, &vectorcraft_format::save_file(&d)); @@ -45,9 +45,11 @@ fn look(c: [u8; 3]) -> Appearance { /// The active document gets a red symbol named `Star` of its own. fn parent_star(s: &mut Session) { let star = Node::path(vectorcraft_doc::NodeId(901), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), look(RED)); - std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc) - .symbols - .push(vectorcraft_doc::Symbol { name: "Star".into(), art: std::sync::Arc::new(star) }); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).symbols.push(vectorcraft_doc::Symbol { + dynamic: false, + name: "Star".into(), + art: std::sync::Arc::new(star), + }); } /// Place `path` (linked: the default), centred on the artboard → its id. diff --git a/crates/engine/src/tests/previewbounds.rs b/crates/engine/src/tests/previewbounds.rs index 998f7fd14a..f1b31671e4 100644 --- a/crates/engine/src/tests/previewbounds.rs +++ b/crates/engine/src/tests/previewbounds.rs @@ -380,13 +380,13 @@ fn an_object_has_the_art_of_at_most_4096_symbol_instances_drawn() { let mut filled = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0); filled.effects.push(Effect { id: "path.offsetPath".into(), params: json!({"offset": 1}), visible: true }); let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), filled); - d.symbols.push(Symbol { name: "S0".into(), art: Arc::new(square) }); + d.symbols.push(Symbol { dynamic: false, name: "S0".into(), art: Arc::new(square) }); for k in 1..=12 { let mut instance = |dx: f64| Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: format!("S{}", k - 1), xf: Affine::translate((dx, 0.0)) })); let pair = vec![instance(0.0), instance(20.0 * f64::from(1 << (k - 1)))]; let art = Node::group(d.alloc_id(), pair); - d.symbols.push(Symbol { name: format!("S{k}"), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: format!("S{k}"), art: Arc::new(art) }); } let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "S12".into(), xf: Affine::IDENTITY }); let (layer, id) = (d.layers[0].id, instance.id); diff --git a/crates/engine/src/tests/symbolbounds.rs b/crates/engine/src/tests/symbolbounds.rs index 5b1c3f2c5d..5140d5630f 100644 --- a/crates/engine/src/tests/symbolbounds.rs +++ b/crates/engine/src/tests/symbolbounds.rs @@ -115,7 +115,7 @@ fn set_bounds_with_use_preview_bounds_keeps_the_strokes_in_the_symbol_at_their_w let mut d = Document::new(200.0, 120.0); let stroked = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0); let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 8.0, 8.0)), stroked); - d.symbols.push(Symbol { name: "Box".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Box".into(), art: Arc::new(art) }); let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Box".into(), xf: Affine::translate((50.0, 50.0)) }); *instance.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0); let (layer, id) = (d.layers[0].id, instance.id); @@ -136,7 +136,7 @@ fn set_bounds_with_use_preview_bounds_keeps_the_strokes_in_the_symbol_at_their_w let mut round = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0); round.stroke_mut().unwrap().join = vectorcraft_doc::LineJoin::Round; let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 8.0, 8.0)), round); - d.symbols.push(Symbol { name: "Ring".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Ring".into(), art: Arc::new(art) }); let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Ring".into(), xf: Affine::translate((50.0, 50.0)) }); let (layer, id) = (d.layers[0].id, instance.id); d.insert(Some(layer), 0, instance).unwrap(); @@ -164,7 +164,7 @@ fn set_bounds_sizes_an_instance_and_a_path_whose_strokes_differ() { Node::path(d.alloc_id(), shapes::rectangle(Rect::new(at, at, at + 10.0, at + 10.0)), stroked) }; let art = square(&mut d, 0.0, 10.0); - d.symbols.push(Symbol { name: "Thick".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Thick".into(), art: Arc::new(art) }); let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Thick".into(), xf: Affine::translate((50.0, 50.0)) }); let path = square(&mut d, 50.0, 2.0); let (layer, ids) = (d.layers[0].id, [instance.id, path.id]); @@ -202,7 +202,7 @@ fn set_bounds_measures_the_objects_in_an_instances_art_one_by_one() { *art.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); *instance.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); } - d.symbols.push(Symbol { name: "Mixed".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Mixed".into(), art: Arc::new(art) }); let mut roots = vec![if grouped { Node::group(d.alloc_id(), vec![Arc::new(instance)]) } else { instance }]; if plain { let filled = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0); @@ -271,7 +271,7 @@ fn set_bounds_measures_an_instance_as_one_object_past_4096_objects_in_its_art() art.push(Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 1.0, y + 1.0)), square))); } let art = Node::group(d.alloc_id(), art); - d.symbols.push(Symbol { name: "Many".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Many".into(), art: Arc::new(art) }); let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Many".into(), xf: Affine::translate((0.0, 100.0)) }); let (layer, id) = (d.layers[0].id, instance.id); d.insert(Some(layer), 0, instance).unwrap(); @@ -293,7 +293,7 @@ fn set_bounds_measures_a_turned_instance_by_the_box_around_its_turned_art_box() let mut d = Document::new(400.0, 400.0); let filled = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0); let circle = Node::path(d.alloc_id(), shapes::ellipse(Rect::new(-10.0, -10.0, 10.0, 10.0)), filled); - d.symbols.push(Symbol { name: "Disc".into(), art: Arc::new(circle) }); + d.symbols.push(Symbol { dynamic: false, name: "Disc".into(), art: Arc::new(circle) }); let xf = Affine::translate((100.0, 100.0)) * Affine::rotate(30f64.to_radians()); let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Disc".into(), xf }); let (layer, id) = (d.layers[0].id, instance.id); @@ -327,7 +327,7 @@ fn far_on_artboard_2() -> (Session, NodeId) { let mut d = Document::new(800.0, 600.0); let rect = shapes::rectangle(Rect::new(1100.0, 50.0, 1140.0, 70.0)); let art = Node::path(d.alloc_id(), rect, Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); - d.symbols.push(Symbol { name: "Far".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) }); let (layer, id) = (d.layers[0].id, d.alloc_id()); d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Far".into(), xf: Affine::translate((100.0, 100.0)) })).unwrap(); let mut s = Session::new(); @@ -437,7 +437,7 @@ fn an_artboards_svg_keeps_an_instance_whose_brush_art_is_on_it() { let mut stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); stroke.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); let line = Node::path(d.alloc_id(), shapes::line((0.0, 40.0).into(), (0.0, 60.0).into()), stroke); - d.symbols.push(Symbol { name: "Nib".into(), art: Arc::new(line) }); + d.symbols.push(Symbol { dynamic: false, name: "Nib".into(), art: Arc::new(line) }); let (layer, id) = (d.layers[0].id, d.alloc_id()); d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Nib".into(), xf: Affine::translate((-5.0, 0.0)) })).unwrap(); let mut s = Session::new(); @@ -462,7 +462,7 @@ fn an_artboards_svg_keeps_an_instance_whose_shadow_is_on_it() { } else { instance.appearance.effects.push(shadow); } - d.symbols.push(Symbol { name: "Dot".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(art) }); let layer = d.layers[0].id; d.insert(Some(layer), 0, instance).unwrap(); let mut s = Session::new(); diff --git a/crates/engine/src/tests/typescale.rs b/crates/engine/src/tests/typescale.rs index ad2bd1eaa9..bdfb27f2f9 100644 --- a/crates/engine/src/tests/typescale.rs +++ b/crates/engine/src/tests/typescale.rs @@ -247,7 +247,7 @@ fn a_file_with_type_sizes_out_of_range_opens_with_them_in_range() { (h.size, h.h_scale, h.v_scale, h.baseline_shift, h.leading) = (f64::MAX, f64::MAX, f64::MAX, f64::MAX, Some(f64::MAX)); (k.size, k.h_scale, k.v_scale, k.baseline_shift, k.leading) = (0.001, 0.5, 0.5, 5000.0, Some(0.0)); let art = d.node(id).unwrap().clone(); - d.symbols.push(vectorcraft_doc::Symbol { name: "Lines".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Lines".into(), art: Arc::new(art) }); let attrs = json!({"size": 0, "h_scale": 1e9, "v_scale": -1, "baseline_shift": -1e9, "leading": -1}); d.char_styles.push(vectorcraft_doc::TextStyleDef { name: "Broken".into(), attrs: attrs.as_object().unwrap().clone() }); let attrs = json!({"size": 40, "leading": null}); diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 10109e1ec3..e7a89d97c5 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -4312,7 +4312,7 @@ fn brushed_document(kind: usize, art: usize) -> Document { Node::path(doc.alloc_id(), square(), Appearance::basic(fill, Paint::None, 0.0)) }; let (in_symbol, in_pattern) = (brushed(&mut doc), brushed(&mut doc)); - doc.symbols.push(Symbol { name: "s0".into(), art: std::sync::Arc::new(in_symbol) }); + doc.symbols.push(Symbol { dynamic: false, name: "s0".into(), art: std::sync::Arc::new(in_symbol) }); doc.patterns.push(PatternDef::new("p0", vec![std::sync::Arc::new(in_pattern)])); let art = match art { 0 => instance(&mut doc), @@ -4502,7 +4502,7 @@ fn symbols_document(count: usize, levels: usize, last: &str) -> Document { for _ in 0..levels { art = Node::group(doc.alloc_id(), vec![std::sync::Arc::new(art)]); } - doc.symbols.push(Symbol { name: format!("s{i}"), art: std::sync::Arc::new(art) }); + doc.symbols.push(Symbol { dynamic: false, name: format!("s{i}"), art: std::sync::Arc::new(art) }); } let first = instance(&mut doc, "s0".into()); let layer = doc.layers[0].id; diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 89df7701bd..b0ba5508fa 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -278,7 +278,7 @@ impl<'a> Writer<'a> { if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol) && self.nest < MAX_NEST { - let mut art = (*sym.art).clone(); + let mut art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n); art.transform(*xf, false); art.visible = true; self.nest += 1; diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 6e6ba05847..f99aea9239 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -313,7 +313,7 @@ impl<'a> Scene<'a> { if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol) && self.nest < MAX_NEST { - let mut art = (*sym.art).clone(); + let mut art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n); art.transform(*xf, false); self.nest += 1; self.node(&art, true); diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index c8271dda81..6d1331c2f9 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -633,7 +633,7 @@ fn an_instance_whose_art_reaches_the_region_is_written() { // while the 20 × 20 square around the origin, moved to (-60, -60) to (-40, -40), is off it. let mut d = doc_with(|d| vec![Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Far".into(), xf: Affine::translate((-50.0, -50.0)) })]); let art = path(&mut d, shapes::rectangle(Rect::new(100.0, 100.0, 140.0, 140.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); - d.symbols.push(vectorcraft_doc::Symbol { name: "Far".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) }); let page = page_of(&d, &opts(&d)); assert!(page.contains("1 0 0 rg"), "{page}"); } @@ -652,7 +652,7 @@ fn an_instance_whose_brush_art_reaches_the_region_is_written() { vectorcraft_brush::store(&mut d, &lib); let mut art = path(&mut d, shapes::line((0.0, 40.0).into(), (0.0, 60.0).into()), Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 1.0); art.appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); - d.symbols.push(vectorcraft_doc::Symbol { name: "Nib".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Nib".into(), art: Arc::new(art) }); let page = page_of(&d, &opts(&d)); assert!(page.contains("1 0 0 rg"), "{page}"); } diff --git a/crates/format/tests/it/native_v3.rs b/crates/format/tests/it/native_v3.rs index 33633de5c5..5475f39fb0 100644 --- a/crates/format/tests/it/native_v3.rs +++ b/crates/format/tests/it/native_v3.rs @@ -129,7 +129,7 @@ fn unused_images_are_pruned() { n.extras_mut().mask = Some(Box::new(OpacityMask::new(image_node(&mut d, "in mask"), false))); d.insert(Some(layer), 0, n).unwrap(); let art = image_node(&mut d, "in symbol"); - d.symbols.push(Symbol { name: "S".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); // Image objects inside foreign data (a brush library kept as JSON) keep theirs too. d.unknown.insert("brushes".into(), json!([{"art": {"type": "image", "key": "in brush"}}])); let back = load(&save(&d, true)).unwrap(); diff --git a/crates/format/tests/it/save_options.rs b/crates/format/tests/it/save_options.rs index 5cafcb114b..c9a82839c2 100644 --- a/crates/format/tests/it/save_options.rs +++ b/crates/format/tests/it/save_options.rs @@ -200,7 +200,7 @@ fn art_outside_the_layers_counts_too() { let mut art = paths_doc(1, anchors_for(1, 2 * PRETTY_MAX_BYTES)); let path = Arc::clone(&art.layers[0]); art.layers.clear(); - d.symbols.push(Symbol { name: "Leaves".into(), art: path }); + d.symbols.push(Symbol { dynamic: false, name: "Leaves".into(), art: path }); assert!(!SaveOptions::for_doc(&d).pretty); let bytes = save_file(&d); assert!(!is_pretty(&bytes)); diff --git a/crates/metafile/src/scene.rs b/crates/metafile/src/scene.rs index 587577f41c..fff90f6977 100644 --- a/crates/metafile/src/scene.rs +++ b/crates/metafile/src/scene.rs @@ -217,7 +217,7 @@ impl<'a> Scene<'a> { if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol) && self.nest < MAX_NEST { - let mut art = (*sym.art).clone(); + let mut art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n); art.transform(*xf, false); self.nest += 1; self.node(&art, true); diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index 25bb51277f..23bcfdc672 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -393,7 +393,7 @@ fn an_instance_whose_art_reaches_the_artboard_is_written() { let inst = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Far".into(), xf: Affine::translate((-50.0, -50.0)) }); let mut d = doc_with(100.0, 100.0, vec![inst]); let art = path(shapes::rectangle(Rect::new(100.0, 100.0, 140.0, 140.0)), red(), Paint::None, 0.0); - d.symbols.push(vectorcraft_doc::Symbol { name: "Far".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) }); let k = kinds(&emf_records(&emf(&d).bytes)); assert!(k.contains(&39), "a brush fills the art: {k:?}"); } diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 9740362ec5..c7090e8e20 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -217,7 +217,7 @@ impl Exporter<'_> { let total = sym.map_or(0, |sym| self.symbol_nodes.saturating_add(sym.art.count() as u64)); if let Some(sym) = sym.filter(|_| total <= vectorcraft_doc::MAX_SYMBOL_NODES) { self.symbol_nodes = total; - let mut art = (*sym.art).clone(); + let mut art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n); art.transform(*xf, false); self.node(s, &art, page, true); } diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 0b7e3aceab..8ac576a23b 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -194,7 +194,7 @@ fn an_instance_whose_art_reaches_the_page_is_written() { // the 20 × 20 square around the origin, moved to (-60, -60) to (-40, -40), is off it. let mut d = doc(200.0, 100.0); let red = rect_node(Rect::new(100.0, 50.0, 140.0, 90.0), Color::rgb(1.0, 0.0, 0.0)); - let far = vectorcraft_doc::Symbol { name: "Far".into(), art: Arc::new(red) }; + let far = vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(red) }; d.symbols.push(far.clone()); let instance = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Far".into(), xf: Affine::translate((-50.0, -50.0)) }); add(&mut d, instance.clone()); @@ -228,7 +228,7 @@ fn an_instance_whose_brush_art_reaches_the_page_is_written() { let mut stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); stroke.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); let line = Node::path(NodeId(0), shapes::line((0.0, 40.0).into(), (0.0, 60.0).into()), stroke); - d.symbols.push(vectorcraft_doc::Symbol { name: "Nib".into(), art: Arc::new(line) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Nib".into(), art: Arc::new(line) }); add(&mut d, Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Nib".into(), xf: Affine::translate((-5.0, 0.0)) })); let out = roundtrip(&d); let l = leaves(&out); diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index cd1232a4a4..019beddd73 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -265,7 +265,7 @@ fn a_symbol_instance_prints_by_its_art() { let mut d = doc(100.0, 100.0, &[]); let red = Appearance::basic(rgb(1.0, 0.0, 0.0), Paint::None, 0.0); let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 100.0, 140.0, 140.0)), red); - d.symbols.push(vectorcraft_doc::Symbol { name: "Far".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) }); let (layer, id) = (d.default_layer().unwrap(), d.alloc_id()); let xf = vectorcraft_geom::Affine::translate((-50.0, -50.0)); d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Far".into(), xf })).unwrap(); @@ -293,7 +293,7 @@ fn a_symbol_instances_brush_art_keeps_its_artboard_printed() { let mut stroke = Appearance::basic(Paint::None, rgb(1.0, 0.0, 0.0), 1.0); stroke.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); let art = Node::path(d.alloc_id(), shapes::line((0.0, 40.0).into(), (0.0, 60.0).into()), stroke); - d.symbols.push(vectorcraft_doc::Symbol { name: "Nib".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Nib".into(), art: Arc::new(art) }); let (layer, id) = (d.default_layer().unwrap(), d.alloc_id()); let xf = vectorcraft_geom::Affine::translate((-5.0, 0.0)); d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Nib".into(), xf })).unwrap(); diff --git a/crates/render/src/brush_fx.rs b/crates/render/src/brush_fx.rs index c19bfb6e6b..52f045cbb9 100644 --- a/crates/render/src/brush_fx.rs +++ b/crates/render/src/brush_fx.rs @@ -370,7 +370,7 @@ mod tests { shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), ); - d.symbols.push(vectorcraft_doc::Symbol { name: "S".into(), art: std::sync::Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "S".into(), art: std::sync::Arc::new(art) }); let id = d.alloc_id(); let mut inst = Node::new(id, vectorcraft_doc::NodeKind::SymbolInstance { symbol: "S".into(), xf: Affine::translate((50.0, 50.0)) }); inst.appearance.set_fill(Paint::solid(Color::rgb(1.0, 0.0, 0.0))); @@ -394,7 +394,7 @@ mod tests { let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); ap.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); let art = Node::path(vectorcraft_doc::NodeId(0), shapes::line((0.0, 40.0).into(), (0.0, 60.0).into()), ap); - d.symbols.push(vectorcraft_doc::Symbol { name: "Nib".into(), art: std::sync::Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Nib".into(), art: std::sync::Arc::new(art) }); let id = d.alloc_id(); let inst = Node::new(id, vectorcraft_doc::NodeKind::SymbolInstance { symbol: "Nib".into(), xf: Affine::translate((-6.0, 0.0)) }); let l = d.layers[0].id; @@ -424,7 +424,7 @@ mod tests { let moved = Affine::translate((-8.0, 0.0)); let source = if instance { let art = line(&mut d); - d.symbols.push(vectorcraft_doc::Symbol { name: "Nib".into(), art: std::sync::Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Nib".into(), art: std::sync::Arc::new(art) }); Node::new(d.alloc_id(), vectorcraft_doc::NodeKind::SymbolInstance { symbol: "Nib".into(), xf: moved }) } else { let mut n = line(&mut d); diff --git a/crates/render/src/encode/tests.rs b/crates/render/src/encode/tests.rs index 03f2fcc1cd..0935ba3567 100644 --- a/crates/render/src/encode/tests.rs +++ b/crates/render/src/encode/tests.rs @@ -236,7 +236,7 @@ fn art_bounds_take_in_the_effects_in_a_symbols_art() { let mut art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), black); let shadow = vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: serde_json::json!({"x": 8, "y": 0, "blur": 0}), visible: true }; art.appearance.effects.push(shadow); - d.symbols.push(vectorcraft_doc::Symbol { name: "Box".into(), art: std::sync::Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Box".into(), art: std::sync::Arc::new(art) }); let (id, l) = (d.alloc_id(), d.layers[0].id); let xf = vectorcraft_geom::Affine::translate((20.0, 20.0)); d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Box".into(), xf })).unwrap(); diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index e7a46af247..274c763b02 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -479,7 +479,7 @@ fn thirty_stacked_glows_draw_quickly_cached_or_not() { shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), ); - instanced.symbols.push(vectorcraft_doc::Symbol { name: "Square".into(), art: std::sync::Arc::new(art) }); + instanced.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Square".into(), art: std::sync::Arc::new(art) }); let mut instance = Node::new(instanced.alloc_id(), vectorcraft_doc::NodeKind::SymbolInstance { symbol: "Square".into(), xf: Affine::translate((30.0, 30.0)) }); instance.appearance.effects = glows.into_iter().map(|(id, p)| Effect { id: id.into(), params: p, visible: true }).collect(); @@ -754,7 +754,7 @@ fn a_moved_group_draws_the_shadow_of_the_instance_art_in_it_while_interacting() let mut base = Document::new(100.0, 100.0); let orange = Appearance::basic(Paint::solid(Color::rgb(0.9, 0.4, 0.1)), Paint::None, 0.0); let art = Node::path(base.alloc_id(), shapes::rectangle(Rect::new(100.0, 100.0, 130.0, 126.0)), orange); - base.symbols.push(vectorcraft_doc::Symbol { name: "Far".into(), art: std::sync::Arc::new(art) }); + base.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: std::sync::Arc::new(art) }); // The instance draws the art from (20, 20) to (50, 46), and the 20 × 20 square around the // origin from (-90, -90) to (-70, -70). let xf = Affine::translate((-80.0, -80.0)); diff --git a/crates/render/src/live.rs b/crates/render/src/live.rs index 8d3d7d14c7..e6315d6450 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -771,7 +771,7 @@ mod tests { true => Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: format!("S{}", k + 1), xf: Affine::IDENTITY }), false => square(&mut d), }; - d.symbols.push(Symbol { name: format!("S{k}"), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: format!("S{k}"), art: Arc::new(art) }); } let first = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "S0".into(), xf: Affine::IDENTITY }); let kind = EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true }; @@ -805,7 +805,7 @@ mod tests { }; let (x, y) = (square(&mut d, 0.0), square(&mut d, 20.0)); for (name, art) in [("A", &x), ("B", &y), ("C", &x)] { - d.symbols.push(Symbol { name: name.into(), art: art.clone() }); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: art.clone() }); } let content = ["A", "B", "C"].map(|s| Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: s.into(), xf: Affine::IDENTITY }))); let kind = EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true }; diff --git a/crates/render/src/renderer/text.rs b/crates/render/src/renderer/text.rs index 675247efda..c53cbb7143 100644 --- a/crates/render/src/renderer/text.rs +++ b/crates/render/src/renderer/text.rs @@ -56,7 +56,9 @@ impl Renderer { /// placed again when the fonts change. pub(super) fn placed_art(&mut self, art: &Arc<Node>, xf: Affine, scale_strokes: bool, inst: Option<&Node>) -> (Arc<Node>, bool) { let kept_kind = matches!(art.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) || vectorcraft_doc::live::is_live(art); - if !kept_kind || fx::has_object_fx(art) { + // An instance with appearance changes of its own isn't kept: the key doesn't tell them apart. + let overridden = inst.is_some_and(|i| !i.extras().symbol_overrides.is_empty()); + if !kept_kind || overridden || fx::has_object_fx(art) { return (place(art, xf, scale_strokes, inst), false); } let stain = stain_bits(inst.and_then(vectorcraft_brush::stain)); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index e7782b8132..81a91d8ea8 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -220,7 +220,7 @@ fn hidden_and_culled() { fn far_instance(art: Rect) -> Document { let mut d = Document::new(100.0, 100.0); let art = rect_node(&mut d, art, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); - d.symbols.push(vectorcraft_doc::Symbol { name: "Far".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) }); let (id, l) = (d.alloc_id(), d.layers[0].id); d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Far".into(), xf: Affine::translate((-50.0, -50.0)) })).unwrap(); d @@ -250,7 +250,7 @@ fn an_instance_is_culled_by_the_effects_in_its_art() { let mut art = rect_node(&mut d, Rect::new(-1.0, -1.0, 1.0, 1.0), Paint::solid(Color::BLACK), Paint::None, 0.0); let shadow = vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: serde_json::json!({"x": 8, "y": 0, "blur": 0}), visible: true }; art.appearance.effects.push(shadow); - d.symbols.push(vectorcraft_doc::Symbol { name: "Dot".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(art) }); let (id, l) = (d.alloc_id(), d.layers[0].id); d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((-5.0, 20.0)) })).unwrap(); let img = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()); @@ -264,7 +264,7 @@ fn a_repeat_of_an_instance_is_culled_by_the_effects_in_its_art() { let mut art = rect_node(&mut d, Rect::new(-1.0, -1.0, 1.0, 1.0), Paint::solid(Color::BLACK), Paint::None, 0.0); let shadow = vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: serde_json::json!({"x": 8, "y": 0, "blur": 0}), visible: true }; art.appearance.effects.push(shadow); - d.symbols.push(vectorcraft_doc::Symbol { name: "Dot".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(art) }); let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((-5.0, 20.0)) }); let grid = vectorcraft_doc::TileType::Grid; let kind = @@ -287,11 +287,11 @@ fn past_the_measured_placements_an_instance_is_culled_by_an_estimate_of_its_art_ let mut art = rect_node(&mut d, Rect::new(-1.0, -1.0, 1.0, 1.0), Paint::solid(Color::BLACK), Paint::None, 0.0); let shadow = vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: serde_json::json!({"x": 8, "y": 0, "blur": 0}), visible: true }; art.appearance.effects.push(shadow); - d.symbols.push(vectorcraft_doc::Symbol { name: "Spot".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Spot".into(), art: Arc::new(art) }); for name in ["Dot", "Late"] { let spot = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Spot".into(), xf: Affine::IDENTITY }); let group = Node::group(d.alloc_id(), vec![Arc::new(spot)]); - d.symbols.push(vectorcraft_doc::Symbol { name: name.into(), art: Arc::new(group) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(group) }); } let l = d.layers[0].id; for i in 0..4100 { @@ -317,7 +317,7 @@ fn nested_instances_are_culled_in_bounded_time(effect: Option<vectorcraft_doc::E let mut art = rect_node(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), Paint::solid(Color::BLACK), Paint::None, 0.0); let shadow = vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: serde_json::json!({"x": 2, "y": 0, "blur": 0}), visible: true }; art.appearance.effects.push(shadow); - d.symbols.push(vectorcraft_doc::Symbol { name: "S30".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "S30".into(), art: Arc::new(art) }); let instance = |d: &mut Document, symbol: String, xf: Affine| { let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol, xf }); n.appearance.effects.extend(effect.clone()); @@ -330,7 +330,7 @@ fn nested_instances_are_culled_in_bounded_time(effect: Option<vectorcraft_doc::E pair.push(Arc::new(instance(&mut d, next.clone(), xf))); } let group = Node::group(d.alloc_id(), pair); - d.symbols.push(vectorcraft_doc::Symbol { name: format!("S{i}"), art: Arc::new(group) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("S{i}"), art: Arc::new(group) }); } let first = instance(&mut d, "S0".into(), Affine::translate((-100_000.0, 0.0))); let l = d.layers[0].id; @@ -369,7 +369,7 @@ fn a_scaled_instance_is_culled_by_the_effects_in_its_art_as_placed() { let mut art = rect_node(&mut d, Rect::new(-1.0, -1.0, 1.0, 1.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); let double = vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"scaleH": 200, "scaleV": 200}), visible: true }; art.appearance.effects.push(double); - d.symbols.push(vectorcraft_doc::Symbol { name: "Dot".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(art) }); let (id, l) = (d.alloc_id(), d.layers[0].id); let xf = Affine::translate((-50.0, 50.0)) * Affine::scale(30.0); d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Dot".into(), xf })).unwrap(); @@ -401,7 +401,7 @@ fn an_instance_with_a_geometry_effect_is_culled_by_the_effects_in_its_reshaped_a let effect = || vectorcraft_doc::Effect { id: "distort.transform".into(), params: scale.clone(), visible: true }; let mut art = rect_node(&mut d, Rect::new(-1.0, -1.0, 1.0, 1.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); art.appearance.effects.push(effect()); - d.symbols.push(vectorcraft_doc::Symbol { name: "Dot".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(art) }); let (id, l) = (d.alloc_id(), d.layers[0].id); let mut instance = Node::new(id, NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((-11.0, 20.0)) }); instance.appearance.effects.push(effect()); @@ -845,7 +845,7 @@ fn placed_symbol_art_root_applies_its_own_mask() { let mut art = if grouped { Node::group(d.alloc_id(), vec![Arc::new(red)]) } else { red }; let inner = rect_node(&mut d, Rect::new(10.0, 10.0, 50.0, 90.0), Paint::solid(Color::WHITE), Paint::None, 0.0); art.extras_mut().mask = Some(Box::new(OpacityMask::new(inner, true))); - d.symbols.push(vectorcraft_doc::Symbol { name: "Masked".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Masked".into(), art: Arc::new(art) }); let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Masked".into(), xf: Affine::IDENTITY }); d.insert(Some(d.layers[0].id), 0, instance).unwrap(); diff --git a/crates/render/src/tests/adjust.rs b/crates/render/src/tests/adjust.rs index f3e930dcaa..c50bdc39f4 100644 --- a/crates/render/src/tests/adjust.rs +++ b/crates/render/src/tests/adjust.rs @@ -112,7 +112,7 @@ fn an_embedded_image_is_recoloured_and_the_original_pixels_stay() { fn a_symbol_instance_recolours_its_art() { let mut d = Document::new(100.0, 100.0); let art = red_square(-15.0, -15.0); - d.symbols.push(Symbol { name: "Red".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Red".into(), art: Arc::new(art) }); let mut n = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Red".into(), xf: Affine::translate((50.0, 50.0)) }); n.appearance.effects.push(hue()); let l = d.layers[0].id; diff --git a/crates/render/src/tests/changed.rs b/crates/render/src/tests/changed.rs index 675ea52ee4..e5f1f913d8 100644 --- a/crates/render/src/tests/changed.rs +++ b/crates/render/src/tests/changed.rs @@ -220,7 +220,7 @@ fn an_unchanged_document_changes_nothing_and_a_new_symbol_everything() { assert_eq!(redraw(&old, &old.clone()), Changed::Nothing); let mut new = old.clone(); let art = Arc::new(rect(&mut new, Rect::new(0.0, 0.0, 5.0, 5.0), Color::BLACK)); - new.symbols.push(vectorcraft_doc::Symbol { name: "Dot".into(), art }); + new.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Dot".into(), art }); assert_eq!(redraw(&old, &new), Changed::Everything); } diff --git a/crates/render/src/tests/cmykblend.rs b/crates/render/src/tests/cmykblend.rs index a6ed64ff9a..2235320021 100644 --- a/crates/render/src/tests/cmykblend.rs +++ b/crates/render/src/tests/cmykblend.rs @@ -118,7 +118,7 @@ fn the_transparency_test_is_kept_while_the_art_stays_the_same() { // A symbol whose art shows transparency, placed nowhere, makes the page draw by ink planes again. let mut art = rect(&mut e, Rect::new(0.0, 0.0, 5.0, 5.0), CYAN); art.opacity = 0.5; - e.symbols.push(vectorcraft_doc::Symbol { name: "S".into(), art: Arc::new(art) }); + e.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); assert!(frame(&mut r, &e) == frame(&mut Renderer::new(), &e)); assert_eq!(kept(&r).map(|(_, shows)| shows), Some(true)); } diff --git a/crates/render/src/tests/fontchange.rs b/crates/render/src/tests/fontchange.rs index a4c9820556..c98af03d34 100644 --- a/crates/render/src/tests/fontchange.rs +++ b/crates/render/src/tests/fontchange.rs @@ -162,7 +162,7 @@ fn symbol_type_redraws_when_its_font_becomes_available() { let mut t = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(-140.0, 25.0), "Hamburg", style)))); t.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 0.0}), visible: true }); let art = Node::group(d.alloc_id(), vec![Arc::new(t)]); - d.symbols.push(vectorcraft_doc::Symbol { name: "Word".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Word".into(), art: Arc::new(art) }); let (l, id) = (d.layers[0].id, d.alloc_id()); d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Word".into(), xf: Affine::translate((150.0, 75.0)) })).unwrap(); let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; @@ -207,7 +207,7 @@ fn type_with_geometry_effects_redraws_when_its_font_becomes_available() { } 3 => { let art = Node::group(d.alloc_id(), vec![Arc::new(object)]); - d.symbols.push(vectorcraft_doc::Symbol { name: "Word".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Word".into(), art: Arc::new(art) }); object = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Word".into(), xf: Affine::translate((150.0, 75.0)) }); object.appearance.effects.push(moved()); } @@ -243,7 +243,7 @@ fn enveloped_type_redraws_when_its_font_becomes_available() { let typed = word(&mut d, Point::new(10.0, 60.0)); let art = word(&mut d, Point::new(-140.0, 20.0)); let art = Node::group(d.alloc_id(), vec![Arc::new(art)]); - d.symbols.push(vectorcraft_doc::Symbol { name: "Word".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Word".into(), art: Arc::new(art) }); let shown = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Word".into(), xf: Affine::translate((150.0, 120.0)) }); let l = d.layers[0].id; for (i, content) in [typed, shown].into_iter().enumerate() { diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index f1cf1da5ad..f95c617998 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -389,7 +389,7 @@ fn type_with_an_inline_graphic_draws_its_symbols_new_size() { for i in 0..4 { let mut d = Document::new(200.0, 100.0); let art = symbol_art(&mut d); - d.symbols.push(vectorcraft_doc::Symbol { name: "S".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); let style = CharStyle { size: 24.0, ..Default::default() }; let mut t = TextObject::point(vectorcraft_geom::Point::new(10.0, 50.0), "A", style.clone()); t.runs.push(TextRun::inline(InlineArt::new("S"), style.clone())); @@ -428,7 +428,7 @@ fn symbol_art(d: &mut Document) -> Node { fn symbol_doc() -> Document { let mut d = Document::new(200.0, 100.0); let art = symbol_art(&mut d); - d.symbols.push(vectorcraft_doc::Symbol { name: "S".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); let l = d.layers[0].id; let xfs = [ Affine::translate((30.0, 30.0)), @@ -579,9 +579,9 @@ fn art_placed_again_in_every_frame_keeps_one_outline_per_stroke() { if let Some(c) = art.children_mut() { c.push(Arc::new(image)); } - d.symbols.push(vectorcraft_doc::Symbol { name: "I".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "I".into(), art: Arc::new(art) }); let art = symbol_art(&mut d); - d.symbols.push(vectorcraft_doc::Symbol { name: "S".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); let l = d.layers[0].id; let instance = |d: &mut Document, symbol: &str, x: f64, y: f64| { let id = d.alloc_id(); @@ -707,7 +707,7 @@ fn strokes_of_brush_art_draw_as_a_new_renderer_does() { // Three instances show symbol `B`, a group of a wave. A fourth wave is a path of the document, // and a Mirror repeat draws a fifth wave and its reflection. let art = Node::group(d.alloc_id(), vec![Arc::new(wave(&mut d, (0.0, 0.0)))]); - d.symbols.push(vectorcraft_doc::Symbol { name: "B".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "B".into(), art: Arc::new(art) }); let l = d.layers[0].id; for at in [(50.0, 30.0), (150.0, 30.0), (50.0, 70.0)] { let id = d.alloc_id(); @@ -755,10 +755,10 @@ fn brushed_copies_doc() -> Document { use vectorcraft_doc::text::{CharStyle, InlineArt, TextObject, TextRun}; let mut d = Document::new(200.0, 100.0); let line = brushed_line(&mut d); - d.symbols.push(vectorcraft_doc::Symbol { name: "Line".into(), art: Arc::new(line) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Line".into(), art: Arc::new(line) }); let line = brushed_line(&mut d); let held = Node::group(d.alloc_id(), vec![Arc::new(line)]); - d.symbols.push(vectorcraft_doc::Symbol { name: "Held".into(), art: Arc::new(held) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Held".into(), art: Arc::new(held) }); let l = d.layers[0].id; for (symbol, at) in [("Line", (20.0, 15.0)), ("Line", (60.0, 15.0)), ("Line", (100.0, 15.0)), ("Held", (20.0, 45.0)), ("Held", (60.0, 45.0))] { let id = d.alloc_id(); @@ -856,7 +856,7 @@ fn brush_art_draws_edits_of_the_symbols_and_patterns_it_shows() { let doc = |dot_brushed: bool, fill_brushed: bool| { let mut d = Document::new(200.0, 100.0); let dot = art(&mut d, Paint::solid(Color::rgb(0.0, 0.0, 1.0)), dot_brushed); - d.symbols.push(vectorcraft_doc::Symbol { name: "Dot".into(), art: Arc::new(dot) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(dot) }); let fill = art(&mut d, Paint::solid(Color::rgb(0.0, 0.6, 0.0)), fill_brushed); let mut def = PatternDef::new("Fill", vec![Arc::new(fill)]); def.tile = Rect::new(-6.0, -6.0, 6.0, 6.0); @@ -917,7 +917,7 @@ fn brush_art_draws_renamed_symbols_and_patterns_it_shows() { [("Dot", Paint::solid(Color::rgb(0.0, 0.0, 1.0)), false), ("Other", Paint::solid(Color::rgb(1.0, 0.0, 0.0)), true)] { let a = art(&mut d, paint, brushed); - d.symbols.push(vectorcraft_doc::Symbol { name: name.into(), art: Arc::new(a) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(a) }); } for (name, paint, brushed) in [("Fill", Paint::solid(Color::rgb(0.0, 0.6, 0.0)), false), ("Spare", Paint::solid(Color::rgb(1.0, 0.0, 0.0)), true)] @@ -978,7 +978,7 @@ fn live_objects_in_brush_art_keep_their_evaluations_between_frames() { }; let held = bent(&mut d, (-60.0, 0.0), (60.0, 0.0)); let held = Node::group(d.alloc_id(), vec![Arc::new(held)]); - d.symbols.push(vectorcraft_doc::Symbol { name: "Wave".into(), art: Arc::new(held) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Wave".into(), art: Arc::new(held) }); let path = bent(&mut d, (20.0, 25.0), (180.0, 25.0)); let l = d.layers[0].id; d.insert(Some(l), usize::MAX, path).unwrap(); @@ -1006,7 +1006,7 @@ fn editing_an_instance_or_a_symbol_places_only_its_art_again() { let green = vectorcraft_doc::Appearance::basic(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0); let square = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(-5.0, -5.0, 5.0, 5.0)), green); let t = Node::group(d.alloc_id(), vec![Arc::new(square)]); - d.symbols.push(vectorcraft_doc::Symbol { name: "T".into(), art: Arc::new(t) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "T".into(), art: Arc::new(t) }); let (l, id) = (d.layers[0].id, d.alloc_id()); d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "T".into(), xf: Affine::translate((30.0, 80.0)) })).unwrap(); let opts = RenderOptions::default(); @@ -1056,7 +1056,7 @@ fn instances_of_art_outside_the_square_follow_their_symbols_art() { // the one from x 200 lies from (40, 40) to (60, 60), in it. The 20 × 20 square around the // origin lies from (-170, 30) to (-150, 50), left of the view. let (off, on) = (square_at(&mut d, 100.0), square_at(&mut d, 200.0)); - d.symbols.push(vectorcraft_doc::Symbol { name: "Far".into(), art: off.clone() }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: off.clone() }); let (l, id) = (d.layers[0].id, d.alloc_id()); d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Far".into(), xf: Affine::translate((-160.0, 40.0)) })).unwrap(); let opts = RenderOptions::default(); @@ -1098,7 +1098,7 @@ fn draws_as_new(d: &mut Document, before: &RenderOptions, after: &RenderOptions, /// `d` with symbol `Holder` (a group of `members`) shown by one instance at (100, 50). fn holder_doc(mut d: Document, members: Vec<Node>) -> Document { let holder = Node::group(d.alloc_id(), members.into_iter().map(Arc::new).collect()); - d.symbols.push(vectorcraft_doc::Symbol { name: "Holder".into(), art: Arc::new(holder) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Holder".into(), art: Arc::new(holder) }); let (l, id) = (d.layers[0].id, d.alloc_id()); d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Holder".into(), xf: Affine::translate((100.0, 50.0)) })).unwrap(); d @@ -1113,7 +1113,7 @@ fn art_showing_another_symbol_draws_its_edits() { use vectorcraft_doc::text::{CharStyle, InlineArt, TextObject, TextRun}; let mut d = Document::new(200.0, 100.0); let art = symbol_art(&mut d); - d.symbols.push(vectorcraft_doc::Symbol { name: "S".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); let style = CharStyle { size: 24.0, ..Default::default() }; let mut t = TextObject::point(vectorcraft_geom::Point::new(-60.0, 10.0), "A", style.clone()); t.runs.push(TextRun::inline(InlineArt::new("S"), style.clone())); @@ -1234,7 +1234,7 @@ fn live_objects_in_symbol_art_keep_their_evaluations_between_frames() { for (name, art, at) in [("Bent", bent, (40.0, 25.0)), ("Envelope", envelope, (100.0, 25.0)), ("Blend", blend, (160.0, 25.0)), ("Grid", grid, (20.0, 60.0))] { - d.symbols.push(vectorcraft_doc::Symbol { name: name.into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); let id = d.alloc_id(); d.insert(Some(l), usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::translate(at) })).unwrap(); } @@ -1298,7 +1298,7 @@ fn live_objects_in_symbol_art_draw_symbol_and_pattern_edits() { for bricks in [false, true] { let mut d = Document::new(200.0, 100.0); let art = symbol_art(&mut d); - d.symbols.push(vectorcraft_doc::Symbol { name: "S".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); let xf = Affine::translate((10.0, 10.0)) * Affine::scale(0.5); let dot = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "S".into(), xf }); let mut dots = PatternDef::new("Dots", vec![Arc::new(dot)]); @@ -1307,7 +1307,7 @@ fn live_objects_in_symbol_art_draw_symbol_and_pattern_edits() { let band = filled(&mut d, rectangle(Rect::new(-80.0, -30.0, 80.0, 30.0)), pattern_paint("Dots"), vec![]); let envelope = arc_envelope(&mut d, vec![band], true); let art = if grouped { Node::group(d.alloc_id(), vec![Arc::new(envelope)]) } else { envelope }; - d.symbols.push(vectorcraft_doc::Symbol { name: "Bent".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Bent".into(), art: Arc::new(art) }); let (l, id) = (d.layers[0].id, d.alloc_id()); d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Bent".into(), xf: Affine::translate((100.0, 50.0)) })).unwrap(); let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; @@ -1401,7 +1401,7 @@ fn live_objects_draw_symbol_and_pattern_art_edits() { let with_s = || { let mut d = Document::new(200.0, 100.0); let art = symbol_art(&mut d); - d.symbols.push(vectorcraft_doc::Symbol { name: "S".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); d }; let red_bar = |d: &mut Document| { @@ -1415,7 +1415,7 @@ fn live_objects_draw_symbol_and_pattern_art_edits() { let mut d = with_s(); let shown = instance(&mut d, "S", Affine::IDENTITY); let a = Node::group(d.alloc_id(), vec![Arc::new(shown)]); - d.symbols.push(vectorcraft_doc::Symbol { name: "A".into(), art: Arc::new(a) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "A".into(), art: Arc::new(a) }); let a = instance(&mut d, "A", Affine::translate((100.0, 50.0)) * Affine::scale(2.0)); let envelope = arc_envelope(&mut d, vec![a], false); edit_draws_as_new(with_art(d, vec![envelope]), red_bar); @@ -1430,7 +1430,7 @@ fn live_objects_draw_symbol_and_pattern_art_edits() { let mut d = Document::new(200.0, 100.0); d.patterns.push(checks(Color::rgb(1.0, 0.0, 0.0))); let band = filled(&mut d, rectangle(Rect::new(-80.0, -30.0, 80.0, 30.0)), pattern_paint("Checks"), vec![]); - d.symbols.push(vectorcraft_doc::Symbol { name: "Banded".into(), art: Arc::new(band) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Banded".into(), art: Arc::new(band) }); let banded = instance(&mut d, "Banded", Affine::translate((100.0, 50.0))); let envelope = arc_envelope(&mut d, vec![banded], true); edit_draws_as_new(with_art(d, vec![envelope]), |d| { @@ -1457,7 +1457,7 @@ fn symbol_in_live_and_effect_art() -> Document { use vectorcraft_geom::shapes::rectangle; let mut d = Document::new(500.0, 100.0); let art = symbol_art(&mut d); - d.symbols.push(vectorcraft_doc::Symbol { name: "S".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); let bent = |d: &mut Document, x: f64| { let xf = Affine::translate((x, 50.0)) * Affine::scale(2.0); let s = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "S".into(), xf }); @@ -1470,7 +1470,7 @@ fn symbol_in_live_and_effect_art() -> Document { group.appearance.effects.push(drop_shadow()); let copy = symbol_art(&mut d); let art = arc_envelope(&mut d, vec![copy], false); - d.symbols.push(vectorcraft_doc::Symbol { name: "Bent".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Bent".into(), art: Arc::new(art) }); let xf = Affine::translate((250.0, 50.0)) * Affine::scale(2.0); let symbol = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Bent".into(), xf }); let mask = bent(&mut d, 350.0); @@ -1603,7 +1603,7 @@ fn objects_with_plugin_effects_follow_the_plugins_installed() { let mut d = Document::new(200.0, 100.0); let art = square(&mut d, -20.0, -20.0, vec![]); let art = Node::group(d.alloc_id(), vec![Arc::new(art)]); - d.symbols.push(vectorcraft_doc::Symbol { name: "Shaped".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Shaped".into(), art: Arc::new(art) }); let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Shaped".into(), xf: Affine::translate((100.0, 50.0)) }); plugin_change_draws_as_new(with_art(d, vec![instance]), ID, small.clone(), big); // Left of the view, the square is culled until the plug-in draws it in the view. @@ -1616,7 +1616,7 @@ fn objects_with_plugin_effects_follow_the_plugins_installed() { // effects in the art paint past the art, which the plug-in's first shape does not. let mut d = Document::new(200.0, 100.0); let art = square(&mut d, -20.0, -20.0, vec![]); - d.symbols.push(vectorcraft_doc::Symbol { name: "Shaped".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Shaped".into(), art: Arc::new(art) }); let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Shaped".into(), xf: Affine::translate((-30.0, 50.0)) }); plugin_change_draws_as_new(with_art(d, vec![instance]), ID, Some(triangle(-15.0, -15.0, 10.0)), Some(triangle(0.0, 0.0, 150.0))); } @@ -1676,7 +1676,7 @@ fn effect_art_follows_the_plugins_installed() { plugin_change_draws_as_new(group(vec![feather]), ID, small.clone(), big.clone()); let mut d = Document::new(200.0, 100.0); let art = symbol_art(&mut d); - d.symbols.push(vectorcraft_doc::Symbol { name: "S".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "S".into(), xf: Affine::translate((100.0, 50.0)) }); instance.appearance.effects.push(plugin()); plugin_change_draws_as_new(with_art(d, vec![instance]), ID, small.clone(), big.clone()); @@ -1711,7 +1711,7 @@ fn live_objects_follow_the_plugins_installed() { // Symbol `Shaped` is a square with the plug-in effect. let mut d = Document::new(200.0, 100.0); let art = black(&mut d, Rect::new(-20.0, -20.0, 20.0, 20.0)); - d.symbols.push(vectorcraft_doc::Symbol { name: "Shaped".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Shaped".into(), art: Arc::new(art) }); let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Shaped".into(), xf: Affine::translate((100.0, 50.0)) }); let envelope = arc_envelope(&mut d, vec![instance], true); plugin_change_draws_as_new(with_art(d, vec![envelope]), ID, small.clone(), big.clone()); @@ -1753,7 +1753,7 @@ fn pattern_and_symbol_art_with_plugin_effects_follow_the_plugins_installed() { // the instance's box, from (80, 30) to (120, 70). let mut d = Document::new(200.0, 100.0); let art = filled(&mut d, rectangle(Rect::new(-20.0, -20.0, 20.0, 20.0)), Paint::solid(Color::BLACK), vec![plugin()]); - d.symbols.push(vectorcraft_doc::Symbol { name: "Shaped".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Shaped".into(), art: Arc::new(art) }); let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Shaped".into(), xf: Affine::translate((100.0, 50.0)) }); let mut group = Node::group(d.alloc_id(), vec![Arc::new(instance)]); group.appearance.effects.push(drop_shadow()); @@ -1839,7 +1839,7 @@ fn pattern_tiles_draw_edits_to_what_their_art_shows() { let doc = |pattern: &str, effects: Vec<vectorcraft_doc::Effect>| { let mut d = Document::new(200.0, 100.0); let art = symbol_art(&mut d); - d.symbols.push(vectorcraft_doc::Symbol { name: "S".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); let shown = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "S".into(), xf: Affine::translate((10.0, 10.0)) }); d.patterns.push(tile("Stamps", shown)); d.patterns.push(checks(Color::rgb(1.0, 0.0, 0.0))); @@ -1890,10 +1890,10 @@ fn rasters_draw_symbol_brush_and_image_edits() { // A group of an instance of symbol `A`, whose art shows symbol `S`, and a green square. let mut d = Document::new(200.0, 100.0); let art = symbol_art(&mut d); - d.symbols.push(vectorcraft_doc::Symbol { name: "S".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); let shown = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "S".into(), xf: Affine::IDENTITY }); let a = Node::group(d.alloc_id(), vec![Arc::new(shown)]); - d.symbols.push(vectorcraft_doc::Symbol { name: "A".into(), art: Arc::new(a) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "A".into(), art: Arc::new(a) }); let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "A".into(), xf: Affine::translate((50.0, 50.0)) }); let green = vectorcraft_doc::Appearance::basic(Paint::solid(Color::rgb(0.0, 0.8, 0.0)), Paint::None, 0.0); let square = Node::path(d.alloc_id(), rectangle(Rect::new(120.0, 30.0, 160.0, 70.0)), green); @@ -2067,7 +2067,7 @@ fn proof_doc() -> Document { let spot = filled(&mut d, rectangle(Rect::new(110.0, 10.0, 150.0, 50.0)), spot, vec![blur]); let yellow = filled(&mut d, rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), Paint::solid(Color::cmyk(0.0, 0.0, 1.0, 0.0)), vec![]); let art = Node::group(d.alloc_id(), vec![Arc::new(yellow)]); - d.symbols.push(vectorcraft_doc::Symbol { name: "S".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "S".into(), xf: Affine::translate((175.0, 75.0)) }); with_art(d, vec![cyan, circle, white, spot, instance]) } @@ -2228,7 +2228,7 @@ fn symbol_instances_draw_as_groups_of_their_placed_art() { let circle = vectorcraft_geom::shapes::ellipse(Rect::new(-6.0, -6.0, 6.0, 6.0)); let ap = vectorcraft_doc::Appearance::basic(Paint::solid(Color::rgb(1.0, 0.8, 0.0)), Paint::solid(Color::BLACK), 1.0); let circle = Node::path(d.alloc_id(), circle, ap); - d.symbols.push(vectorcraft_doc::Symbol { name: "U".into(), art: Arc::new(circle) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "U".into(), art: Arc::new(circle) }); let id = d.alloc_id(); d.insert(Some(l), usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: "U".into(), xf: Affine::translate((175.0, 25.0)) })).unwrap(); // `groups` holds the same art in place of the instances: groups, and the circle as a path. @@ -2272,7 +2272,7 @@ fn inline_graphics_keep_their_placed_art_between_frames() { use vectorcraft_doc::text::{CharStyle, InlineArt, TextObject, TextRun}; let mut d = Document::new(200.0, 100.0); let art = symbol_art(&mut d); - d.symbols.push(vectorcraft_doc::Symbol { name: "S".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); let style = CharStyle { size: 24.0, ..Default::default() }; let mut t = TextObject::point(vectorcraft_geom::Point::new(10.0, 50.0), "A", style.clone()); t.runs.push(TextRun::inline(InlineArt::new("S"), style.clone())); diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index f5c963c0de..85f7505dde 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -300,7 +300,7 @@ fn symbol_doc(effects: Vec<Effect>) -> Document { shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), ); - d.symbols.push(Symbol { name: "Square".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Square".into(), art: Arc::new(art) }); let mut n = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Square".into(), xf: Affine::translate((50.0, 50.0)) }); n.appearance.effects = effects; doc_with(d, n) @@ -469,7 +469,7 @@ fn a_transform_effect_on_a_group_symbol_or_envelope_moves_and_scales_the_gradien t.id = NodeId(500); // The type in a group, as the art of a symbol, and in an envelope that leaves it as it is. let mut symbols = Document::new(100.0, 100.0); - symbols.symbols.push(Symbol { name: "Type".into(), art: Arc::new(t.clone()) }); + symbols.symbols.push(Symbol { dynamic: false, name: "Type".into(), art: Arc::new(t.clone()) }); let holders = [ doc_with(Document::new(100.0, 100.0), Node::group(NodeId(0), vec![Arc::new(t.clone())])), doc_with(symbols, Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Type".into(), xf: Affine::IDENTITY })), diff --git a/crates/render/src/tests/placed_document.rs b/crates/render/src/tests/placed_document.rs index 60e08a6a5b..8ce2953cdf 100644 --- a/crates/render/src/tests/placed_document.rs +++ b/crates/render/src/tests/placed_document.rs @@ -281,7 +281,11 @@ fn a_ready_bitmap_draws_again_where_its_file_shows() { let brush = vectorcraft_brush::Brush { name: "Cards".into(), kind: vectorcraft_brush::BrushKind::Scatter(scatter) }; vectorcraft_brush::store(&mut brushed, &[brush]); assert_eq!(placed_area(&brushed, &only_a), Changed::Everything); - d.symbols.push(vectorcraft_doc::Symbol { name: "Card".into(), art: Arc::new(placed_node(65, "area-a", 40.0, 20.0, Affine::IDENTITY)) }); + d.symbols.push(vectorcraft_doc::Symbol { + dynamic: false, + name: "Card".into(), + art: Arc::new(placed_node(65, "area-a", 40.0, 20.0, Affine::IDENTITY)), + }); assert_eq!(placed_area(&d, &only_a), Changed::Everything); } diff --git a/crates/render/src/tests/rasterize.rs b/crates/render/src/tests/rasterize.rs index 798d2f6d50..3f27ddfebe 100644 --- a/crates/render/src/tests/rasterize.rs +++ b/crates/render/src/tests/rasterize.rs @@ -310,7 +310,7 @@ fn rasterize_and_shadows_paint_in_stack_order() { Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0), ); art.appearance.effects.push(Effect { id: shadow.0.into(), params: shadow.1.clone(), visible: true }); - d.symbols.push(vectorcraft_doc::Symbol { name: "Shadowed".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Shadowed".into(), art: Arc::new(art) }); let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Shadowed".into(), xf: Affine::translate((20.0, 20.0)) }); instance.appearance.effects.push(Effect { id: "rasterize".into(), params: json!({}), visible: true }); let l = d.layers[0].id; diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index e88ad85098..358cbd38b1 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -653,7 +653,7 @@ impl Writer<'_> { /// by a transform under which the def would not look as the canvas paints it ([`Reuse`]). fn symbol_use(&mut self, sym: &vectorcraft_doc::Symbol, inst: &Node, xf: Affine) -> Option<String> { // SVG Tiny has no `<symbol>`. - if self.tiny() || vectorcraft_brush::stain(inst).is_some() { + if self.tiny() || vectorcraft_brush::stain(inst).is_some() || !inst.extras().symbol_overrides.is_empty() { return None; } if !self.symbols.contains_key(&sym.name) { diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index c2220f9d8f..0e0b8127ef 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -186,7 +186,7 @@ impl Importer { let name = unique_name(self.name_of(&sym), |n| self.doc.symbols.iter().any(|s| s.name == n)); let reuse = Reuse::of(&self.doc, &art); let made = SymbolMade { name: name.clone(), art: without_ids(&art), reuse }; - self.doc.symbols.push(vectorcraft_doc::Symbol { name: name.clone(), art: Arc::new(art) }); + self.doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.clone(), art: Arc::new(art) }); self.symbols.insert(sym, made); if !whole || !reuse.allows(xf) { return None; diff --git a/crates/svg/tests/it/data_attributes.rs b/crates/svg/tests/it/data_attributes.rs index 981662c7c1..752b8f1c3a 100644 --- a/crates/svg/tests/it/data_attributes.rs +++ b/crates/svg/tests/it/data_attributes.rs @@ -230,7 +230,7 @@ fn symbol_document(name: &str) -> Document { let mut doc = import(&svg(r#"<rect id="instance" width="20" height="20"/>"#)).unwrap(); let id = named(&doc, "instance").id; let art = doc.node(id).unwrap().clone(); - doc.symbols.push(vectorcraft_doc::Symbol { name: name.into(), art: std::sync::Arc::new(art) }); + doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: std::sync::Arc::new(art) }); let instance = doc.node_mut(id).unwrap(); instance.appearance = vectorcraft_doc::Appearance::default().into(); instance.kind = vectorcraft_doc::NodeKind::SymbolInstance { symbol: name.into(), xf: vectorcraft_geom::Affine::IDENTITY }; diff --git a/crates/svg/tests/it/encoding_profile_fonts.rs b/crates/svg/tests/it/encoding_profile_fonts.rs index 0cbb61b489..f0ea9804d0 100644 --- a/crates/svg/tests/it/encoding_profile_fonts.rs +++ b/crates/svg/tests/it/encoding_profile_fonts.rs @@ -140,7 +140,7 @@ fn tiny_has_no_filters_masks_symbols_or_style_sheets() { Some(Box::new(OpacityMask::new(Node::path(d.alloc_id(), shapes::ellipse(Rect::new(80.0, 10.0, 130.0, 60.0)), fill(255, 255, 255)), true))); add(&mut d, b); let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(-5.0, -5.0, 5.0, 5.0)), fill(0, 128, 0)); - d.symbols.push(Symbol { name: "Dot".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(art) }); add(&mut d, Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((200.0, 30.0)) })); let mut c = Node::path( vectorcraft_doc::NodeId(0), diff --git a/crates/svg/tests/it/import_live.rs b/crates/svg/tests/it/import_live.rs index 0bd80c5d45..395986a66e 100644 --- a/crates/svg/tests/it/import_live.rs +++ b/crates/svg/tests/it/import_live.rs @@ -376,7 +376,7 @@ fn symbols_and_effects_export_import_export_is_stable() { shapes::ellipse(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::rgb8(200, 30, 30)), Paint::None, 0.0), ); - d.symbols.push(vectorcraft_doc::Symbol { name: "Dot".into(), art: Arc::new(dot) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(dot) }); let l = d.layers[0].id; for x in [10.0, 60.0] { let id = d.alloc_id(); diff --git a/crates/svg/tests/it/symbols_layers.rs b/crates/svg/tests/it/symbols_layers.rs index bc3645a7f8..1e581ed37e 100644 --- a/crates/svg/tests/it/symbols_layers.rs +++ b/crates/svg/tests/it/symbols_layers.rs @@ -28,7 +28,7 @@ fn symbol_doc(stroke: f64, xfs: &[Affine]) -> Document { let mut d = Document::new(200.0, 120.0); let ap = Appearance::basic(Paint::solid(Color::rgb8(30, 90, 220)), Paint::solid(Color::BLACK), stroke); let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), ap); - d.symbols.push(Symbol { name: "My Mark".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "My Mark".into(), art: Arc::new(art) }); for xf in xfs { instance(&mut d, "My Mark", *xf); } @@ -108,7 +108,7 @@ fn pattern_paints_in_symbols_stay_on_the_page() { d.patterns.push(def); let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::basic(pattern_paint("Checks"), Paint::None, 0.0)); - d.symbols.push(Symbol { name: "Tiles".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Tiles".into(), art: Arc::new(art) }); instance(&mut d, "Tiles", Affine::translate((10.0, 10.0))); instance(&mut d, "Tiles", Affine::translate((105.0, 37.0))); let svg = export(&d, &ExportOptions::default()); @@ -143,7 +143,7 @@ fn masks_in_symbols_move_with_the_art_when_linked() { let mut mask = vectorcraft_doc::OpacityMask::new(shape, true); mask.linked = linked; art.extras_mut().mask = Some(Box::new(mask)); - d.symbols.push(Symbol { name: "Half".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Half".into(), art: Arc::new(art) }); instance(&mut d, "Half", Affine::translate((10.0, 10.0))); instance(&mut d, "Half", Affine::translate((15.0, 50.0))); let svg = export(&d, &ExportOptions::default()); @@ -160,7 +160,7 @@ fn symbols_inside_themselves_end() { let inner = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Loop".into(), xf: Affine::translate((5.0, 0.0)) }); let mut g = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(inner)], clip: false }); g.name = Some("g".into()); - d.symbols.push(Symbol { name: "Loop".into(), art: Arc::new(g) }); + d.symbols.push(Symbol { dynamic: false, name: "Loop".into(), art: Arc::new(g) }); instance(&mut d, "Loop", Affine::translate((20.0, 20.0))); let svg = export(&d, &ExportOptions::default()); assert!(import(&svg).is_ok(), "{svg}"); diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 5620be4d54..46b66599b9 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -675,6 +675,7 @@ mod tests { assert_eq!(sampled_hex(&a), "#0000ff"); // A symbol of a green square, placed at (300, 300) and doubled. d.symbols.push(vectorcraft_doc::Symbol { + dynamic: false, name: "Green".into(), art: filled_rect(Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(Color::rgb(0.0, 1.0, 0.0))), }); @@ -693,8 +694,9 @@ mod tests { use vectorcraft_geom::{Affine, Rect}; let (mut d, _) = doc_with_halves(); let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); - d.symbols.push(vectorcraft_doc::Symbol { name: "Red".into(), art: filled_rect(Rect::new(0.0, 0.0, 20.0, 10.0), red) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Red".into(), art: filled_rect(Rect::new(0.0, 0.0, 20.0, 10.0), red) }); d.symbols.push(vectorcraft_doc::Symbol { + dynamic: false, name: "Tiled".into(), art: filled_rect(Rect::new(0.0, 0.0, 20.0, 10.0), vectorcraft_doc::pattern::pattern_paint("Halves")), }); @@ -730,7 +732,7 @@ mod tests { let red = || Paint::solid(Color::rgb(1.0, 0.0, 0.0)); let pair = Node::group(NodeId(0), vec![filled_rect(Rect::new(0.0, 0.0, 10.0, 10.0), red()), filled_rect(Rect::new(20.0, 0.0, 30.0, 10.0), red())]); - d.symbols.push(vectorcraft_doc::Symbol { name: "Pair".into(), art: Arc::new(pair) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Pair".into(), art: Arc::new(pair) }); let (l, inst) = (d.layers[0].id, d.alloc_id()); let mut n = Node::new(inst, NodeKind::SymbolInstance { symbol: "Pair".into(), xf: Affine::translate((100.0, 140.0)) }); n.appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0))); @@ -744,7 +746,7 @@ mod tests { // A 200 pt tile holding an instance of a 180 pt green bar, which reaches far past the // square an instance is measured by without its symbol. let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); - d.symbols.push(vectorcraft_doc::Symbol { name: "Bar".into(), art: filled_rect(Rect::new(0.0, 0.0, 180.0, 10.0), green) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Bar".into(), art: filled_rect(Rect::new(0.0, 0.0, 180.0, 10.0), green) }); let bar = Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::IDENTITY })); let mut bars = vectorcraft_doc::PatternDef::new("Bars", vec![bar]); bars.tile = Rect::new(0.0, 0.0, 200.0, 10.0); @@ -779,15 +781,19 @@ mod tests { let instance = |name: String| Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name, xf: Affine::IDENTITY })); for i in 0..12 { let art = Node::group(NodeId(0), (0..4).map(|_| instance(format!("Fan{}", i + 1))).collect()); - d.symbols.push(Symbol { name: format!("Fan{i}"), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: format!("Fan{i}"), art: Arc::new(art) }); } - d.symbols.push(Symbol { name: "Fan12".into(), art: filled_rect(Rect::new(300.0, 300.0, 400.0, 400.0), pattern_paint("Nest8")) }); + d.symbols.push(Symbol { + dynamic: false, + name: "Fan12".into(), + art: filled_rect(Rect::new(300.0, 300.0, 400.0, 400.0), pattern_paint("Nest8")), + }); // "Deep0" to "Deep99": one instance of the next; "Deep100" a green square. for i in 0..100 { - d.symbols.push(Symbol { name: format!("Deep{i}"), art: instance(format!("Deep{}", i + 1)) }); + d.symbols.push(Symbol { dynamic: false, name: format!("Deep{i}"), art: instance(format!("Deep{}", i + 1)) }); } let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); - d.symbols.push(Symbol { name: "Deep100".into(), art: filled_rect(Rect::new(300.0, 0.0, 400.0, 100.0), green) }); + d.symbols.push(Symbol { dynamic: false, name: "Deep100".into(), art: filled_rect(Rect::new(300.0, 0.0, 400.0, 100.0), green) }); let l = d.layers[0].id; for name in ["Fan0", "Deep0"] { let inst = d.alloc_id(); diff --git a/crates/ui-egui/src/dialogs/symbol_options.rs b/crates/ui-egui/src/dialogs/symbol_options.rs index f6b09c3112..a8814a9e02 100644 --- a/crates/ui-egui/src/dialogs/symbol_options.rs +++ b/crates/ui-egui/src/dialogs/symbol_options.rs @@ -1,9 +1,11 @@ -//! Symbol Options: name, Export Type (Graphic or Movie Clip) and Registration for a new symbol +//! Symbol Options: name, Export Type (Graphic or Movie Clip), Symbol Type (Dynamic or Static) and +//! Registration for a new symbol //! from the selection (`symbol.new`), or for the current symbol in the Symbols panel //! (`symbol.options`). //! //! Fields: `name`, `nineSlice` (bool) with `sliceLeft` / `sliceTop` / `sliceRight` / `sliceBottom` -//! (percent of the symbol's size), `exportType` (`movieClip` | `graphic`), `registration` (0..8, the 9-point grid; +//! (percent of the symbol's size), `exportType` (`movieClip` | `graphic`), `type` (`dynamic` | +//! `static`; a new symbol is dynamic), `registration` (0..8, the 9-point grid; //! 4 = centre), `__edit` (true when editing an existing symbol). Help: //! <https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html>. @@ -38,7 +40,7 @@ fn slice_params(d: &Dialog) -> Value { if d.bool("nineSlice") { json!({ "nineSlice": true, "nineSliceGuides": [l, t, r, b] }) } else { json!({ "nineSlice": false }) } } -/// Export Type choices: (value, label). Illustrator's default is Movie Clip. +/// Export Type choices: (value, label). The reference app's default is Movie Clip. const EXPORT_TYPES: [(&str, &str); 2] = [("movieClip", "Movie Clip"), ("graphic", "Graphic")]; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Symbol Options").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM }; @@ -50,7 +52,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> { return Err("nothing selected".into()); } let name = st.doc.unique_symbol_name("New Symbol"); - let mut fields = json!({ "name": name, "exportType": "movieClip", "registration": 4, "__edit": false }); + let mut fields = json!({ "name": name, "exportType": "movieClip", "type": "dynamic", "registration": 4, "__edit": false }); if let Some(o) = fields.as_object_mut() { o.extend(slice_fields(None)); } @@ -76,9 +78,11 @@ pub fn open_edit(app: &mut VectorcraftApp, name: Option<&str>) -> Result<Value, }; let export = st.doc.symbol_export_type(&name).id(); let registration = st.doc.symbol_registration(&name).0; + let kind = if st.doc.symbols.iter().any(|s| s.name == name && s.dynamic) { "dynamic" } else { "static" }; let mut fields = json!({ "name": name, "exportType": export, + "type": kind, "registration": registration, "__edit": true, "__from": name, @@ -103,6 +107,17 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { d.fields.insert("exportType".into(), json!(value)); } ui.end_row(); + label(ui, tl!("Symbol Type:")); + // A dynamic symbol's instances may change the appearance of parts of its art and stay linked. + ui.horizontal(|ui| { + let cur = d.str("type"); + for (value, text) in [("dynamic", tl!("Dynamic Symbol")), ("static", tl!("Static Symbol"))] { + if widgets::radio(ui, text, cur == value, true) { + d.fields.insert("type".into(), json!(value)); + } + } + }); + ui.end_row(); label(ui, tl!("Registration:")); let cur = d.fields.get("registration").and_then(Value::as_u64).unwrap_or(4) as usize; if let Some(i) = widgets::reference_point(ui, cur) { @@ -134,18 +149,19 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { return Err("name is empty".into()); } let export = d.str("exportType"); + let kind = d.str("type"); let registration = d.fields.get("registration").and_then(Value::as_u64).unwrap_or(4); let edit = d.fields.get("__edit").and_then(Value::as_bool).unwrap_or(false); let r = if edit { let from = d.fields.get("__from").and_then(Value::as_str).unwrap_or(name); - let mut params = json!({ "name": from, "exportType": export, "registration": registration }); + let mut params = json!({ "name": from, "exportType": export, "type": kind, "registration": registration }); merge(&mut params, slice_params(d)); if from != name { params["newName"] = json!(name); } app.run("symbol.options", params) } else { - let mut params = json!({ "name": name, "exportType": export, "registration": registration }); + let mut params = json!({ "name": name, "exportType": export, "type": kind, "registration": registration }); merge(&mut params, slice_params(d)); app.run("symbol.new", params) }; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bf02bfbf4c..39e9235fa3 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5971,3 +5971,15 @@ breakText Glyphs Глифи Odia Ория Urdu Урду VectorCraft {release} and later (version {n}) VectorCraft {release} и по-нови (версия {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Тип на символа: + Dynamic Symbol Динамичен символ + Static Symbol Статичен символ + Symbol Instance Appearance Външен вид на екземпляра на символ + Reset Symbol Instance Нулиране на екземпляра на символ +@msg type must be static or dynamic, not {v} type трябва да е static или dynamic, а не {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` е статичен символ: първо задайте типа на символа на „Динамичен“ +@msg path must be a list of child indices path трябва да е списък с индекси на дъщерни обекти +@msg no object at path {shown} in the symbol's art в графиката на символа няма обект на пътя {shown} +@msg give fill, stroke, opacity and/or blend задайте fill, stroke, opacity и/или blend +@msg pass newName, registration, exportType, nineSlice and/or type задайте newName, registration, exportType, nineSlice и/или type diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a22b6b9854..ba39e61c97 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6004,3 +6004,15 @@ shape Open Otvoren Odia Odija Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} i novije (verzija {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Vrsta simbola: + Dynamic Symbol Dinamički simbol + Static Symbol Statički simbol + Symbol Instance Appearance Izgled instance simbola + Reset Symbol Instance Vrati instancu simbola na početno +@msg type must be static or dynamic, not {v} type mora biti static ili dynamic, a ne {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` je statički simbol: prvo postavite vrstu simbola na Dinamički +@msg path must be a list of child indices path mora biti lista indeksa podređenih objekata +@msg no object at path {shown} in the symbol's art nema objekta na putanji {shown} u grafici simbola +@msg give fill, stroke, opacity and/or blend navedite fill, stroke, opacity i/ili blend +@msg pass newName, registration, exportType, nineSlice and/or type navedite newName, registration, exportType, nineSlice i/ili type diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 1086b60b89..dad0439567 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6077,3 +6077,15 @@ breakText Glyphs Glifs Odia Oriya Urdu Urdú VectorCraft {release} and later (version {n}) VectorCraft {release} i posteriors (versió {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Tipus de símbol: + Dynamic Symbol Símbol dinàmic + Static Symbol Símbol estàtic + Symbol Instance Appearance Aparença de la instància de símbol + Reset Symbol Instance Restableix la instància de símbol +@msg type must be static or dynamic, not {v} type ha de ser static o dynamic, no {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` és un símbol estàtic: primer establiu el tipus de símbol a Dinàmic +@msg path must be a list of child indices path ha de ser una llista d’índexs de fills +@msg no object at path {shown} in the symbol's art no hi ha cap objecte al camí {shown} de l’art del símbol +@msg give fill, stroke, opacity and/or blend indiqueu fill, stroke, opacity i/o blend +@msg pass newName, registration, exportType, nineSlice and/or type indiqueu newName, registration, exportType, nineSlice i/o type diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 52a61db5c8..a660cdb216 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6087,3 +6087,15 @@ breakText Glyphs Glyfy Odia Urijština Urdu Urdština VectorCraft {release} and later (version {n}) VectorCraft {release} a novější (verze {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Typ symbolu: + Dynamic Symbol Dynamický symbol + Static Symbol Statický symbol + Symbol Instance Appearance Vzhled instance symbolu + Reset Symbol Instance Obnovit instanci symbolu +@msg type must be static or dynamic, not {v} type musí být static nebo dynamic, ne {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` je statický symbol: nejprve nastavte jeho typ symbolu na Dynamický +@msg path must be a list of child indices path musí být seznam indexů potomků +@msg no object at path {shown} in the symbol's art v kresbě symbolu není na cestě {shown} žádný objekt +@msg give fill, stroke, opacity and/or blend zadejte fill, stroke, opacity a/nebo blend +@msg pass newName, registration, exportType, nineSlice and/or type zadejte newName, registration, exportType, nineSlice a/nebo type diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 2b79b23dc6..96bcb3327c 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5985,3 +5985,15 @@ breakText Glyphs Glyffer Odia Oriya Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} og nyere (version {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Symboltype: + Dynamic Symbol Dynamisk symbol + Static Symbol Statisk symbol + Symbol Instance Appearance Symbolforekomstens udseende + Reset Symbol Instance Nulstil symbolforekomst +@msg type must be static or dynamic, not {v} type skal være static eller dynamic, ikke {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` er et statisk symbol: indstil først symboltypen til Dynamisk +@msg path must be a list of child indices path skal være en liste over underordnede indekser +@msg no object at path {shown} in the symbol's art intet objekt ved stien {shown} i symbolets grafik +@msg give fill, stroke, opacity and/or blend angiv fill, stroke, opacity og/eller blend +@msg pass newName, registration, exportType, nineSlice and/or type angiv newName, registration, exportType, nineSlice og/eller type diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 328205b3a0..65a846eb7c 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5672,3 +5672,15 @@ breakText Glyphs Glyphen Odia Oriya Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} und neuer (Version {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Symboltyp: + Dynamic Symbol Dynamisches Symbol + Static Symbol Statisches Symbol + Symbol Instance Appearance Aussehen der Symbolinstanz + Reset Symbol Instance Symbolinstanz zurücksetzen +@msg type must be static or dynamic, not {v} type muss static oder dynamic sein, nicht {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` ist ein statisches Symbol: Stellen Sie zuerst den Symboltyp auf „Dynamisch“ ein +@msg path must be a list of child indices path muss eine Liste von Kindindizes sein +@msg no object at path {shown} in the symbol's art kein Objekt am Pfad {shown} in der Grafik des Symbols +@msg give fill, stroke, opacity and/or blend geben Sie fill, stroke, opacity und/oder blend an +@msg pass newName, registration, exportType, nineSlice and/or type geben Sie newName, registration, exportType, nineSlice und/oder type an diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bd0a4834de..6426946db6 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6039,3 +6039,15 @@ breakText Glyphs Γλύφοι Odia Όντια Urdu Ούρντου VectorCraft {release} and later (version {n}) VectorCraft {release} και νεότερες (έκδοση {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Τύπος συμβόλου: + Dynamic Symbol Δυναμικό σύμβολο + Static Symbol Στατικό σύμβολο + Symbol Instance Appearance Εμφάνιση στιγμιότυπου συμβόλου + Reset Symbol Instance Επαναφορά στιγμιότυπου συμβόλου +@msg type must be static or dynamic, not {v} το type πρέπει να είναι static ή dynamic, όχι {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first το `{name}` είναι στατικό σύμβολο: ορίστε πρώτα τον τύπο συμβόλου σε Δυναμικό +@msg path must be a list of child indices το path πρέπει να είναι λίστα δεικτών θυγατρικών αντικειμένων +@msg no object at path {shown} in the symbol's art δεν υπάρχει αντικείμενο στη διαδρομή {shown} στο γραφικό του συμβόλου +@msg give fill, stroke, opacity and/or blend δώστε fill, stroke, opacity ή/και blend +@msg pass newName, registration, exportType, nineSlice and/or type δώστε newName, registration, exportType, nineSlice ή/και type diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index aa29fafd25..104ed8668a 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6029,3 +6029,15 @@ breakText Glyphs Glifos Odia Oriya Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} y posteriores (versión {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Tipo de símbolo: + Dynamic Symbol Símbolo dinámico + Static Symbol Símbolo estático + Symbol Instance Appearance Apariencia de la instancia de símbolo + Reset Symbol Instance Restablecer instancia de símbolo +@msg type must be static or dynamic, not {v} type debe ser static o dynamic, no {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` es un símbolo estático: primero establezca su tipo de símbolo en Dinámico +@msg path must be a list of child indices path debe ser una lista de índices de hijos +@msg no object at path {shown} in the symbol's art no hay ningún objeto en la ruta {shown} del arte del símbolo +@msg give fill, stroke, opacity and/or blend indique fill, stroke, opacity y/o blend +@msg pass newName, registration, exportType, nineSlice and/or type indique newName, registration, exportType, nineSlice y/o type diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index b6a15979c0..1c8f92623c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6117,3 +6117,15 @@ breakText Glyphs Merkit Odia Orija Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} ja uudemmat (versio {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Symbolin tyyppi: + Dynamic Symbol Dynaaminen symboli + Static Symbol Staattinen symboli + Symbol Instance Appearance Symboli-ilmentymän ulkoasu + Reset Symbol Instance Palauta symboli-ilmentymä +@msg type must be static or dynamic, not {v} type-arvon on oltava static tai dynamic, ei {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` on staattinen symboli: aseta ensin sen symbolin tyypiksi Dynaaminen +@msg path must be a list of child indices path-arvon on oltava luettelo alikohteiden indeksejä +@msg no object at path {shown} in the symbol's art symbolin kuvituksessa ei ole objektia polussa {shown} +@msg give fill, stroke, opacity and/or blend anna fill, stroke, opacity ja/tai blend +@msg pass newName, registration, exportType, nineSlice and/or type anna newName, registration, exportType, nineSlice ja/tai type diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index f16a049277..6f0fe8aca3 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6084,3 +6084,15 @@ breakText Glyphs Glyphes Odia Odia Urdu Ourdou VectorCraft {release} and later (version {n}) VectorCraft {release} et ultérieures (version {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Type de symbole : + Dynamic Symbol Symbole dynamique + Static Symbol Symbole statique + Symbol Instance Appearance Aspect de l'instance de symbole + Reset Symbol Instance Réinitialiser l'instance de symbole +@msg type must be static or dynamic, not {v} type doit être static ou dynamic, et non {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` est un symbole statique : définissez d'abord son type de symbole sur Dynamique +@msg path must be a list of child indices path doit être une liste d'indices d'enfants +@msg no object at path {shown} in the symbol's art aucun objet au chemin {shown} dans l'illustration du symbole +@msg give fill, stroke, opacity and/or blend indiquez fill, stroke, opacity et/ou blend +@msg pass newName, registration, exportType, nineSlice and/or type indiquez newName, registration, exportType, nineSlice et/ou type diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 37e40c442b..10f83807ee 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6073,3 +6073,15 @@ breakText Glyphs Glifák Odia Odia Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} és újabb (verzió: {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Szimbólum típusa: + Dynamic Symbol Dinamikus szimbólum + Static Symbol Statikus szimbólum + Symbol Instance Appearance Szimbólumpéldány megjelenése + Reset Symbol Instance Szimbólumpéldány visszaállítása +@msg type must be static or dynamic, not {v} a type értéke static vagy dynamic lehet, nem {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` statikus szimbólum: előbb állítsa a szimbólum típusát Dinamikusra +@msg path must be a list of child indices a path gyermekindexek listája kell legyen +@msg no object at path {shown} in the symbol's art a szimbólum grafikájában nincs objektum a(z) {shown} útvonalon +@msg give fill, stroke, opacity and/or blend adja meg a fill, stroke, opacity és/vagy blend értékét +@msg pass newName, registration, exportType, nineSlice and/or type adja meg a newName, registration, exportType, nineSlice és/vagy type értékét diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 1b46b5d862..6cdd3a8cf3 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5985,3 +5985,15 @@ breakText Glyphs Glif Odia Oriya Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} dan yang lebih baru (versi {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Jenis simbol: + Dynamic Symbol Simbol dinamis + Static Symbol Simbol statis + Symbol Instance Appearance Tampilan instans simbol + Reset Symbol Instance Atur ulang instans simbol +@msg type must be static or dynamic, not {v} type harus static atau dynamic, bukan {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` adalah simbol statis: setel dulu jenis simbolnya ke Dinamis +@msg path must be a list of child indices path harus berupa daftar indeks anak +@msg no object at path {shown} in the symbol's art tidak ada objek di jalur {shown} dalam karya seni simbol +@msg give fill, stroke, opacity and/or blend berikan fill, stroke, opacity dan/atau blend +@msg pass newName, registration, exportType, nineSlice and/or type berikan newName, registration, exportType, nineSlice dan/atau type diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 701468a834..51ae7f5efb 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5706,3 +5706,15 @@ breakText Glyphs Glifi Odia Odia Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} e successive (versione {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Tipo di simbolo: + Dynamic Symbol Simbolo dinamico + Static Symbol Simbolo statico + Symbol Instance Appearance Aspetto dell'istanza di simbolo + Reset Symbol Instance Reimposta istanza di simbolo +@msg type must be static or dynamic, not {v} type deve essere static o dynamic, non {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` è un simbolo statico: imposta prima il tipo di simbolo su Dinamico +@msg path must be a list of child indices path deve essere un elenco di indici figlio +@msg no object at path {shown} in the symbol's art nessun oggetto al percorso {shown} nella grafica del simbolo +@msg give fill, stroke, opacity and/or blend specifica fill, stroke, opacity e/o blend +@msg pass newName, registration, exportType, nineSlice and/or type specifica newName, registration, exportType, nineSlice e/o type diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 7057e12d7b..850e481820 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5773,3 +5773,15 @@ breakText Glyphs 字形 Odia オディア語 Urdu ウルドゥー語 VectorCraft {release} and later (version {n}) VectorCraft {release} 以降 (バージョン {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: シンボルの種類: + Dynamic Symbol ダイナミックシンボル + Static Symbol スタティックシンボル + Symbol Instance Appearance シンボルインスタンスのアピアランス + Reset Symbol Instance シンボルインスタンスをリセット +@msg type must be static or dynamic, not {v} type は static または dynamic にしてください({v} は無効です) +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` はスタティックシンボルです。先にシンボルの種類をダイナミックに設定してください +@msg path must be a list of child indices path は子のインデックスのリストにしてください +@msg no object at path {shown} in the symbol's art シンボルのアートのパス {shown} にオブジェクトがありません +@msg give fill, stroke, opacity and/or blend fill、stroke、opacity、blend のいずれかを指定してください +@msg pass newName, registration, exportType, nineSlice and/or type newName、registration、exportType、nineSlice、type のいずれかを指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8af3007e15..6242e6e05d 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6076,3 +6076,15 @@ breakText Glyphs გლიფები Odia ორია Urdu ურდუ VectorCraft {release} and later (version {n}) VectorCraft {release} და უფრო ახალი (ვერსია {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: სიმბოლოს ტიპი: + Dynamic Symbol დინამიკური სიმბოლო + Static Symbol სტატიკური სიმბოლო + Symbol Instance Appearance სიმბოლოს ეგზემპლარის იერსახე + Reset Symbol Instance სიმბოლოს ეგზემპლარის ჩამოყრა +@msg type must be static or dynamic, not {v} type უნდა იყოს static ან dynamic და არა {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` სტატიკური სიმბოლოა: ჯერ სიმბოლოს ტიპად დააყენეთ „დინამიკური“ +@msg path must be a list of child indices path უნდა იყოს შვილობილი ინდექსების სია +@msg no object at path {shown} in the symbol's art სიმბოლოს გრაფიკაში გზაზე {shown} ობიექტი არ არის +@msg give fill, stroke, opacity and/or blend მიუთითეთ fill, stroke, opacity და/ან blend +@msg pass newName, registration, exportType, nineSlice and/or type მიუთითეთ newName, registration, exportType, nineSlice და/ან type diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 6156029dbb..b9d96eed04 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5669,3 +5669,15 @@ breakText Glyphs 글리프 Odia 오리야어 Urdu 우르두어 VectorCraft {release} and later (version {n}) VectorCraft {release} 이상 (버전 {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: 심볼 유형: + Dynamic Symbol 동적 심볼 + Static Symbol 정적 심볼 + Symbol Instance Appearance 심볼 인스턴스 모양새 + Reset Symbol Instance 심볼 인스턴스 재설정 +@msg type must be static or dynamic, not {v} type은 static 또는 dynamic이어야 합니다({v}는 안 됨) +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}`은(는) 정적 심볼입니다. 먼저 심볼 유형을 동적으로 설정하세요 +@msg path must be a list of child indices path는 자식 인덱스 목록이어야 합니다 +@msg no object at path {shown} in the symbol's art 심볼 아트의 경로 {shown}에 개체가 없습니다 +@msg give fill, stroke, opacity and/or blend fill, stroke, opacity 및/또는 blend를 지정하세요 +@msg pass newName, registration, exportType, nineSlice and/or type newName, registration, exportType, nineSlice 및/또는 type을 지정하세요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ea641dab79..6a227c3948 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6029,3 +6029,15 @@ breakText Glyphs Glyphs Odia Odia Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} en nieuwer (versie {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Symbooltype: + Dynamic Symbol Dynamisch symbool + Static Symbol Statisch symbool + Symbol Instance Appearance Uiterlijk van symboolinstantie + Reset Symbol Instance Symboolinstantie opnieuw instellen +@msg type must be static or dynamic, not {v} type moet static of dynamic zijn, niet {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` is een statisch symbool: stel eerst het symbooltype in op Dynamisch +@msg path must be a list of child indices path moet een lijst met onderliggende indexen zijn +@msg no object at path {shown} in the symbol's art geen object op pad {shown} in de illustratie van het symbool +@msg give fill, stroke, opacity and/or blend geef fill, stroke, opacity en/of blend op +@msg pass newName, registration, exportType, nineSlice and/or type geef newName, registration, exportType, nineSlice en/of type op diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index a1f22e4d78..9443b2488f 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5942,3 +5942,15 @@ breakText Glyphs Glify Odia Orija Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} i nowsze (wersja {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Typ symbolu: + Dynamic Symbol Symbol dynamiczny + Static Symbol Symbol statyczny + Symbol Instance Appearance Wygląd wystąpienia symbolu + Reset Symbol Instance Resetuj wystąpienie symbolu +@msg type must be static or dynamic, not {v} type musi mieć wartość static lub dynamic, a nie {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` jest symbolem statycznym: najpierw ustaw jego typ symbolu na Dynamiczny +@msg path must be a list of child indices path musi być listą indeksów elementów podrzędnych +@msg no object at path {shown} in the symbol's art brak obiektu w ścieżce {shown} w grafice symbolu +@msg give fill, stroke, opacity and/or blend podaj fill, stroke, opacity i/lub blend +@msg pass newName, registration, exportType, nineSlice and/or type podaj newName, registration, exportType, nineSlice i/lub type diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4b1d5f83fe..e61e7a1a41 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6006,3 +6006,15 @@ breakText Glyphs Glifos Odia Oriá Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} e posteriores (versão {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Tipo de símbolo: + Dynamic Symbol Símbolo dinâmico + Static Symbol Símbolo estático + Symbol Instance Appearance Aparência da instância de símbolo + Reset Symbol Instance Redefinir instância de símbolo +@msg type must be static or dynamic, not {v} type deve ser static ou dynamic, não {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` é um símbolo estático: defina primeiro o tipo de símbolo como Dinâmico +@msg path must be a list of child indices path deve ser uma lista de índices de filhos +@msg no object at path {shown} in the symbol's art nenhum objeto no caminho {shown} na arte do símbolo +@msg give fill, stroke, opacity and/or blend informe fill, stroke, opacity e/ou blend +@msg pass newName, registration, exportType, nineSlice and/or type informe newName, registration, exportType, nineSlice e/ou type diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 3f05c0190f..eb5449f0f4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6064,3 +6064,15 @@ breakText Glyphs Глифы Odia Ория Urdu Урду VectorCraft {release} and later (version {n}) VectorCraft {release} и новее (версия {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Тип символа: + Dynamic Symbol Динамический символ + Static Symbol Статический символ + Symbol Instance Appearance Оформление экземпляра символа + Reset Symbol Instance Сбросить экземпляр символа +@msg type must be static or dynamic, not {v} type должен быть static или dynamic, а не {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` — статический символ: сначала задайте для него тип символа «Динамический» +@msg path must be a list of child indices path должен быть списком индексов дочерних объектов +@msg no object at path {shown} in the symbol's art в графике символа нет объекта по пути {shown} +@msg give fill, stroke, opacity and/or blend укажите fill, stroke, opacity и/или blend +@msg pass newName, registration, exportType, nineSlice and/or type укажите newName, registration, exportType, nineSlice и/или type diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index adabea465d..a5cd18975a 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6139,3 +6139,15 @@ breakText Glyphs Glyfer Odia Oriya Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} och senare (version {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Symboltyp: + Dynamic Symbol Dynamisk symbol + Static Symbol Statisk symbol + Symbol Instance Appearance Symbolinstansens utseende + Reset Symbol Instance Återställ symbolinstans +@msg type must be static or dynamic, not {v} type måste vara static eller dynamic, inte {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` är en statisk symbol: ställ först in symboltypen på Dynamisk +@msg path must be a list of child indices path måste vara en lista med underordnade index +@msg no object at path {shown} in the symbol's art inget objekt vid sökvägen {shown} i symbolens bild +@msg give fill, stroke, opacity and/or blend ange fill, stroke, opacity och/eller blend +@msg pass newName, registration, exportType, nineSlice and/or type ange newName, registration, exportType, nineSlice och/eller type diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 88017e1917..36d2676d31 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6044,3 +6044,15 @@ breakText Glyphs Glifler Odia Oriya dili Urdu Urduca VectorCraft {release} and later (version {n}) VectorCraft {release} ve sonrası (sürüm {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Sembol Türü: + Dynamic Symbol Dinamik Sembol + Static Symbol Statik Sembol + Symbol Instance Appearance Sembol Örneği Görünümü + Reset Symbol Instance Sembol Örneğini Sıfırla +@msg type must be static or dynamic, not {v} type static veya dynamic olmalıdır, {v} değil +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` statik bir semboldür: önce Sembol Türünü Dinamik olarak ayarlayın +@msg path must be a list of child indices path alt öğe dizinlerinden oluşan bir liste olmalıdır +@msg no object at path {shown} in the symbol's art sembolün çiziminde {shown} yolunda nesne yok +@msg give fill, stroke, opacity and/or blend fill, stroke, opacity ve/veya blend verin +@msg pass newName, registration, exportType, nineSlice and/or type newName, registration, exportType, nineSlice ve/veya type verin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index c0533166d8..2ae65e2764 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5686,3 +5686,15 @@ breakText Glyphs Гліфи Odia Одія Urdu Урду VectorCraft {release} and later (version {n}) VectorCraft {release} і новіші (версія {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Тип символу: + Dynamic Symbol Динамічний символ + Static Symbol Статичний символ + Symbol Instance Appearance Оформлення екземпляра символу + Reset Symbol Instance Скинути екземпляр символу +@msg type must be static or dynamic, not {v} type має бути static або dynamic, а не {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` — статичний символ: спершу встановіть для нього тип символу «Динамічний» +@msg path must be a list of child indices path має бути списком індексів дочірніх об’єктів +@msg no object at path {shown} in the symbol's art у графіці символу немає об’єкта за шляхом {shown} +@msg give fill, stroke, opacity and/or blend вкажіть fill, stroke, opacity та/або blend +@msg pass newName, registration, exportType, nineSlice and/or type вкажіть newName, registration, exportType, nineSlice та/або type diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 3ade68399e..3ba54b1246 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5689,3 +5689,15 @@ breakText Glyphs Glyph Odia Tiếng Odia Urdu Tiếng Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} trở lên (phiên bản {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: Kiểu ký hiệu: + Dynamic Symbol Ký hiệu động + Static Symbol Ký hiệu tĩnh + Symbol Instance Appearance Diện mạo của đối tượng ký hiệu + Reset Symbol Instance Đặt lại đối tượng ký hiệu +@msg type must be static or dynamic, not {v} type phải là static hoặc dynamic, không phải {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` là ký hiệu tĩnh: trước tiên hãy đặt Kiểu ký hiệu thành Động +@msg path must be a list of child indices path phải là danh sách chỉ số con +@msg no object at path {shown} in the symbol's art không có đối tượng tại đường dẫn {shown} trong hình của ký hiệu +@msg give fill, stroke, opacity and/or blend hãy cung cấp fill, stroke, opacity và/hoặc blend +@msg pass newName, registration, exportType, nineSlice and/or type hãy cung cấp newName, registration, exportType, nineSlice và/hoặc type diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b3f76cc2b6..7608eec561 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5929,3 +5929,15 @@ breakText Glyphs 字形 Odia 奥里亚语 Urdu 乌尔都语 VectorCraft {release} and later (version {n}) VectorCraft {release} 及更高版本 (版本 {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: 符号类型: + Dynamic Symbol 动态符号 + Static Symbol 静态符号 + Symbol Instance Appearance 符号实例外观 + Reset Symbol Instance 重置符号实例 +@msg type must be static or dynamic, not {v} type 必须是 static 或 dynamic,而不是 {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` 是静态符号:请先将其符号类型设为动态 +@msg path must be a list of child indices path 必须是子项索引列表 +@msg no object at path {shown} in the symbol's art 符号图稿中路径 {shown} 处没有对象 +@msg give fill, stroke, opacity and/or blend 请提供 fill、stroke、opacity 和/或 blend +@msg pass newName, registration, exportType, nineSlice and/or type 请提供 newName、registration、exportType、nineSlice 和/或 type diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index fd750354a3..1482f45727 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5726,3 +5726,15 @@ breakText Glyphs 字符 Odia 歐利亞文 Urdu 烏都文 VectorCraft {release} and later (version {n}) VectorCraft {release} 及更新版本 (版本 {n}) +# Symbol Options › Symbol Type (dynamic symbols) + Symbol Type: 符號類型: + Dynamic Symbol 動態符號 + Static Symbol 靜態符號 + Symbol Instance Appearance 符號實體外觀 + Reset Symbol Instance 重設符號實體 +@msg type must be static or dynamic, not {v} type 必須是 static 或 dynamic,而不是 {v} +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` 是靜態符號:請先將其符號類型設為動態 +@msg path must be a list of child indices path 必須是子項索引清單 +@msg no object at path {shown} in the symbol's art 符號圖稿中路徑 {shown} 處沒有物件 +@msg give fill, stroke, opacity and/or blend 請提供 fill、stroke、opacity 和/或 blend +@msg pass newName, registration, exportType, nineSlice and/or type 請提供 newName、registration、exportType、nineSlice 和/或 type diff --git a/crates/ui-egui/src/panels/brushes/tests.rs b/crates/ui-egui/src/panels/brushes/tests.rs index 0aef4fb634..e4c5b9d764 100644 --- a/crates/ui-egui/src/panels/brushes/tests.rs +++ b/crates/ui-egui/src/panels/brushes/tests.rs @@ -731,7 +731,7 @@ fn previews_follow_the_swatches_images_and_pattern_options_their_art_uses() { } vectorcraft_brush::store(d, &brushes); for (name, art) in [("Ink Symbol", &inked), ("Picture Symbol", &pictured), ("Stripes Symbol", &striped), ("Fade Symbol", &faded)] { - d.symbols.push(Symbol { name: name.into(), art: Arc::new(art.clone()) }); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art.clone()) }); } Ok(()) }) diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index c0ab7f5e9a..f6f6724e56 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -136,6 +136,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if is_live { actions.push((tl!("Expand Shape"), "object.expandShape")); } + // A dynamic symbol instance with appearance changes of its own: Reset shows the symbol's again. + if super::symbols::changed_instances_selected(app) { + actions.push((tl!("Reset"), "symbol.instance.reset")); + } if multi_color(app, ui.ctx()) { actions.push((tl!("Recolor"), "ui.recolorDialog")); } diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 49acb3e8af..c4059b8d58 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1666,3 +1666,21 @@ fn offset_path_and_simplify_are_not_quick_actions_for_type_alone() { let texts = tall(&mut app, &ctx, vec![]); assert!(shows(&texts, "Offset Path") && shows(&texts, "Simplify"), "type and a path: {texts:?}"); } + +/// A dynamic symbol instance with appearance changes of its own has Reset in Quick Actions, which +/// drops them (#4938); without changes there is no Reset. +#[test] +fn reset_is_a_quick_action_for_a_changed_dynamic_instance() { + let mut app = new_app(); + let (a, b) = (rect(&mut app, 20.0, 20.0, 40.0, 40.0), rect(&mut app, 80.0, 20.0, 40.0, 40.0)); + let inst = app.run("symbol.new", json!({"ids": [a, b], "type": "dynamic"})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + let ctx = egui::Context::default(); + assert!(!shows(&tall(&mut app, &ctx, vec![]), "Reset"), "nothing to reset"); + app.run("symbol.instance.setAppearance", json!({"path": [0], "fill": "#ff0000"})).unwrap(); + let texts = tall(&mut app, &ctx, vec![]); + press(&mut app, &ctx, text_at(&texts, "Reset").center()); + let id = vectorcraft_doc::NodeId(inst.as_u64().unwrap()); + assert!(app.session.doc().unwrap().doc.node(id).unwrap().extras().symbol_overrides.is_empty()); + assert!(!shows(&tall(&mut app, &ctx, vec![]), "Reset")); +} diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index bc77f8e4c1..b5b3058954 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -137,18 +137,29 @@ fn current(app: &mut VectorcraftApp) -> Option<String> { app.run("symbol.list", json!({})).ok().and_then(|v| v["current"].as_str().map(str::to_string)) } -fn has_instances_selected(app: &VectorcraftApp) -> bool { +/// Does the selection hold (in it or in its groups) a symbol instance that `wanted` takes? +fn instance_selected(app: &VectorcraftApp, wanted: impl Fn(&Node) -> bool) -> bool { app.session.active().is_some_and(|st| { st.selection.objects.iter().any(|id| { let mut any = false; if let Some(n) = st.doc.node(*id) { - n.walk(&mut |c| any |= matches!(c.kind, NodeKind::SymbolInstance { .. })); + n.walk(&mut |c| any |= matches!(c.kind, NodeKind::SymbolInstance { .. }) && wanted(c)); } any }) }) } +fn has_instances_selected(app: &VectorcraftApp) -> bool { + instance_selected(app, |_| true) +} + +/// Does the selection hold a symbol instance with appearance changes of its own (a dynamic +/// symbol's), which Reset drops? +pub(crate) fn changed_instances_selected(app: &VectorcraftApp) -> bool { + instance_selected(app, |c| !c.extras().symbol_overrides.is_empty()) +} + /// The symbols of the selected objects when every one is a symbol instance; `None` otherwise. fn selected_instance_symbols(app: &VectorcraftApp) -> Option<Vec<String>> { let st = app.session.active()?; @@ -242,7 +253,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); let zone = ui.interact(list_rect, ui.scope_id().with("symbols-drop"), Sense::hover()); if let Some(ids) = widgets::art_drop(ui, &zone) - && let Err(e) = app.run("symbol.new", json!({ "ids": ids })) + && let Err(e) = app.run("symbol.new", json!({ "ids": ids, "type": "dynamic" })) { app.status(e); } @@ -269,9 +280,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.add_space((ui.available_width() - 2.0 * 28.0).max(0.0)); if widgets::icon_button_enabled(ui, "dc-new-item", tl!("New Symbol"), false, has_sel, 24.0).clicked() { - // Alt skips Symbol Options: the symbol is made under the default name. - let cmd = if ui.input(|i| i.modifiers.alt) { "symbol.new" } else { "ui.symbolOptions" }; - app.run(cmd, json!({})).ok(); + // Alt skips Symbol Options: the symbol is made under the default name, dynamic as the + // dialog's default. + let (cmd, p) = if ui.input(|i| i.modifiers.alt) { ("symbol.new", json!({"type": "dynamic"})) } else { ("ui.symbolOptions", json!({})) }; + app.run(cmd, p).ok(); } // Alt deletes an unused symbol without asking; a symbol with instances still asks. if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Symbol"), false, sel.is_some(), 24.0).clicked() @@ -303,12 +315,13 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { { crate::dialogs::symbol_delete::ask(app, n, false); } - let items: [(&str, bool, &str, Value); 6] = [ + let items: [(&str, bool, &str, Value); 7] = [ (tl!("Symbol Options…"), sel.is_some(), "ui.symbolOptions", json!({"edit": true, "name": sel})), (tl!("Edit Symbol"), inst, "symbol.edit", json!({})), (tl!("Place Symbol Instance"), sel.is_some(), "symbol.place", name.clone()), (tl!("Replace Symbol"), inst && sel.is_some(), "symbol.replace", name.clone()), (tl!("Break Link to Symbol"), inst, "symbol.breakLink", json!({})), + (tl!("Reset Symbol Instance"), changed_instances_selected(app), "symbol.instance.reset", json!({})), (tl!("Select All Instances"), sel.is_some(), "symbol.selectInstances", name), ]; for (label, enabled, cmd, params) in items { @@ -600,10 +613,12 @@ mod tests { assert!(symbols(&mut app).is_empty(), "no symbol before OK"); assert_eq!(app.ui.dialog.as_ref().unwrap().str("name"), "New Symbol"); assert_eq!(app.ui.dialog.as_ref().unwrap().str("exportType"), "movieClip"); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("type"), "dynamic", "Symbol Type: a new symbol is dynamic"); crate::dialogs::confirm(&mut app).unwrap(); assert!(app.ui.dialog.is_none()); let list = app.run("symbol.list", json!({})).unwrap(); assert_eq!(list["symbols"][0]["exportType"], "movieClip"); + assert_eq!(list["symbols"][0]["type"], "dynamic"); // The next one is offered a name no symbol has, and OK keeps the name typed and Export Type. app.run("shape.rectangle", json!({"x": 60, "y": 10, "width": 30, "height": 20})).unwrap(); app.run("ui.symbolOptions", json!({})).unwrap(); @@ -614,13 +629,18 @@ mod tests { assert_eq!(symbols(&mut app), ["New Symbol", "Badge"]); let list = app.run("symbol.list", json!({})).unwrap(); assert_eq!(list["symbols"][1]["exportType"], "graphic"); - // Symbol Options on the current symbol renames and keeps Export Type. + // Symbol Options on the current symbol renames, keeps Export Type and sets Symbol Type. app.run("ui.symbolOptions", json!({"edit": true, "name": "Badge"})).unwrap(); assert_eq!(app.ui.dialog.as_ref().unwrap().str("exportType"), "graphic"); app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!("Mark")); + app.ui.dialog.as_mut().unwrap().fields.insert("type".into(), json!("static")); crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(symbols(&mut app), ["New Symbol", "Mark"]); assert_eq!(app.run("symbol.list", json!({})).unwrap()["symbols"][1]["exportType"], "graphic"); + assert_eq!(app.run("symbol.list", json!({})).unwrap()["symbols"][1]["type"], "static"); + app.run("ui.symbolOptions", json!({"edit": true, "name": "Mark"})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("type"), "static"); + app.ui.dialog = None; // Enable Guides for 9-Slice Scaling stores the guides (percent in the dialog) and reopens as set. assert!(app.run("symbol.list", json!({})).unwrap()["symbols"][1]["nineSlice"].is_null()); app.run("ui.symbolOptions", json!({"edit": true, "name": "Mark"})).unwrap(); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index fe9f554155..1d84d38623 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (exports draw artboard background colors, #4937) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (native format: dynamic symbols, #4938) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -90,7 +90,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Format | Illustrator | Ours: open/place | Ours: save/export | Fidelity and tests | |---|---|---|---|---| -| VectorCraft `.vectorcraft` / `.vctemplate` | — | yes | yes | lossless JSON, versioned, save down to v1; property-tested round trips (`format/tests/prop_format.rs`); documents with a lot of path data are written as compact JSON, about a fifth of the size (#1492); a save falls back to a plain fsync and to writing elsewhere and copying in when the folder refuses the usual steps (#1625, #1649, part of #1620; not confirmed on a real network share); the size limits on embedded data also apply to files read from memory (#1783), and saving over a private file on Unix leaves no readable temporary copy beside it (#1778) | +| VectorCraft `.vectorcraft` / `.vctemplate` | — | yes | yes | lossless JSON, versioned, save down to v1; property-tested round trips (`format/tests/prop_format.rs`); documents with a lot of path data are written as compact JSON, about a fifth of the size (#1492); a save falls back to a plain fsync and to writing elsewhere and copying in when the folder refuses the usual steps (#1625, #1649, part of #1620; not confirmed on a real network share); the size limits on embedded data also apply to files read from memory (#1783), and saving over a private file on Unix leaves no readable temporary copy beside it (#1778); a dynamic symbol's type (`dynamic` on the symbol) and an instance's appearance changes to its art (`symbol_overrides`, each path at most 64 deep, counted against the object budget) are written only when set, so documents without them save as before (#4938) | | Illustrator template `.ait` | open, save | yes | PDF-compatible only, from Save as Template (`.vctemplate` stays its default) | New from Template opens a saved `.ait` untitled with its layers and art (`tests_pdfedit.rs`) | | Illustrator `.ai` | open, save | yes (PDF-compatible + editing-data structure, File Info) | PDF-compatible, or legacy version 7 (layers and groups) | see above; no real-file corpus | | PDF | open, place, save | yes (layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160) | @@ -131,6 +131,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Native format: a symbol's Symbol Type (`dynamic`) and a dynamic symbol instance's appearance changes to objects of its art (`symbol_overrides`) round-trip; both are left out when unset, so other documents save unchanged (#4938). `.ai` reading and writing of dynamic symbols remains. | | 2026-11-01 | minor | Exports draw each artboard's background color behind its art (#4937): PNG, JPEG, GIF, TIFF, WebP, BMP, Targa and PSD (a layer of its own; on a transparent background too), PDF, SVG and EPS pages, a `.ai` file's PDF pages and PostScript and PDF print; `includeArtboardFill: false` leaves it out. Files with editing data (Preserve Editing, `.ai`, EPS, native) keep it as the artboard's color and reopen without extra art. Not read from the reference app's own `.ai` data, nor written to it. DXF, EMF and WMF leave it out | | 2026-10-31 | minor | PDF import finds an installed font whose PDF name holds hyphens (`Noto-Sans-Bold` is Noto Sans, Bold: the longest part before a hyphen that names an installed family) and a composite font by its CIDFont's name rather than its base name, which ends in the CMap's (`Name-Identity-H`, [ISO 32000-1 §9.7.6.1](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)); a missing font is split only before a style part (`Helvetica-BoldOblique`), so it is reported as `MS PGothic`, not `MS`; scores unchanged (estimated) | | 2026-10-31 | minor | DXF export (2000–2018): the LAYOUT objects wrote the paper image origin as a point at group codes 148 and 158, but PLOTSETTINGS defines 148 and 149 and no 158, so strict readers could reject the file (Autodesk Fusion reported "DXF File failed to insert", #3085). They now write 148/149, the shade plot mode, resolution and DPI (76–78, 2004 and later) and flag 1024 on the Model layout; the plot style ACDBPLACEHOLDER no longer carries a subclass marker. Test `r2000_and_later_files_have_the_structure_cad_apps_require` (required sections and table entries, handles and references, LAYOUT group codes); exports pass ezdxf's recover and audit; not tested in Fusion itself; scores unchanged | diff --git a/docs/gaps.md b/docs/gaps.md index d8fa3849ba..5c04e87040 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (G13: artboard background colors in exports and print, #4937; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (G5: dynamic symbols, #4938; estimate 15–26 → 14–24 h) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -57,7 +57,7 @@ stage ([ROADMAP.md](../ROADMAP.md)). | 8 | [G2 Photoshop-style raster effects and the Effect Gallery](#g2-photoshop-style-raster-effects-and-the-effect-gallery) | 1–2 | no | [effects-parity.md](effects-parity.md) | | 9 | [G13 Illustrator 2026 (30.x) additions](#g13-illustrator-2026-30x-additions) | 13–23 | no | [target-app-parity.md](target-app-parity.md) | | 10 | [G14 Pen hardware beyond Windows pressure](#g14-pen-hardware-beyond-windows-pressure) | 4–10 | Wayland pressure | [hardware-parity.md](hardware-parity.md) | -| 11 | [G5 Brushes, symbols and libraries](#g5-brushes-symbols-and-libraries) | 16–27 | no | [target-app-parity.md](target-app-parity.md) | +| 11 | [G5 Brushes, symbols and libraries](#g5-brushes-symbols-and-libraries) | 15–25 | no | [target-app-parity.md](target-app-parity.md) | | 12 | [G3 3D and Materials](#g3-3d-and-materials) | 25–45 | no | [effects-parity.md](effects-parity.md) | | 13 | [G7 Views and windows](#g7-views-and-windows) | 15–25 | no | [ui-parity.md](ui-parity.md) | | 14 | [G6 Automation and scripting](#g6-automation-and-scripting) | 4–8 | no | [target-app-parity.md](target-app-parity.md) | @@ -521,7 +521,13 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall any place and size, narrowed by Appearance, Size and the artboards to search, take an edit of any one of them in proportion, as one undo step ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)); on a group (#4939), the groups like it (the same objects at the same places, moved or scaled) take an edit - made to an object inside it at the object in the same place ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)). + made to an object inside it at the object in the same place ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)); + dynamic symbols (#4938): Symbol Options › Symbol Type (Dynamic Symbol / Static Symbol; `type` on + `symbol.new` / `symbol.options` / `symbol.list`), an instance's own fill, stroke, opacity and blend for an + object of a dynamic symbol's art (`symbol.instance.setAppearance`, by child-index path), drawn and exported + with the instance; redefining the symbol keeps each change whose object remains, Break Link bakes them, + Reset (`symbol.instance.reset`, the Properties panel and the Symbols panel menu) drops them, and making the + symbol static drops them; stored in the native format. Color eyedropper for scatter, art and pattern brushes (Hue Shift colorization; samples canvas art); symbol libraries ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own (one original library generated in code, @@ -541,10 +547,12 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall as a `.vectorcraft` library into the user library folder (listed under User Defined) or a file (`brush.libraries`, `brush.addFromLibrary`, `brush.saveLibrary`, `brush.loadLibrary`). - **Missing:** the Art brush's Overlap; more built-in brush, symbol and graphic-style libraries (original, - generated in code, never Adobe's); dynamic symbols; Global Edit of groups holding type or + generated in code, never Adobe's); dynamic symbols' on-canvas editing (Direct Selection of an object inside a + dynamic instance, with the Fill/Stroke controls and Appearance panel then setting its change) and their `.ai` + read and write; Global Edit of groups holding type or images, rotated copies as matches, Shift-click to leave a match out and highlighting matches before the start; drawing the 9-slice guides on the canvas in symbol edit mode and scaling by them. -- **Estimate:** 15–26 h. +- **Estimate:** 14–24 h. ## G3 3D and Materials @@ -679,6 +687,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | G5: dynamic symbols (#4938): Symbol Options › Symbol Type, per-instance fill, stroke, opacity and blend for objects of a dynamic symbol's art that stay linked (redefining keeps them, Break Link bakes them, Reset and Static drop them; `symbol.instance.setAppearance`, `symbol.instance.reset`; `crates/engine/src/tests/dynamic_symbols.rs`); on-canvas Direct Selection of the parts and `.ai` round trip remain. Estimate 15–26 → 14–24 h. | | 2026-11-01 | minor | G13: Artboard background colors in output (#4937): raster exports (a transparent background too), PDF, SVG and EPS pages, `.ai` files' PDF pages, Export for Screens and print (and its preview) draw each artboard's color behind its art, inside the artboard and in the color's own model; Export for Screens has Include Artboard Fill beside Include Bleed (on by default, remembered; `includeArtboardFill`, also on `document.export` and `file.print`); editing data keeps the color as the artboard's, and Export for Screens' document rows keep it too; estimate unchanged. | | 2026-11-01 | minor | G5: Select › Start Global Edit on a group takes the groups like it (the same objects at the same places, moved or scaled; Appearance, Size and the artboard options apply) and gives an edit made to an object inside one to the object at its place in each of the others, in proportion, as one undo step (#4939); rotated copies and Shift-click exclusion remain. Estimate unchanged. | | 2026-10-31 | minor | G4: PDF import finds an installed font whose PDF name holds hyphens (`Noto-Sans-Bold` is Noto Sans, Bold: the longest part before a hyphen that names an installed family) and a composite font by its CIDFont's name rather than its base name, which ends in the CMap's (`Name-Identity-H`, [ISO 32000-1 §9.7.6.1](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)); a missing font is split only before a style part (`Helvetica-BoldOblique`), so it is reported as `MS PGothic`, not `MS`. Estimate unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index c0eafc23c3..9a85428f7a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1553,14 +1553,30 @@ Guides) can't be picked. An artboard guide is picked, drawn and snapped to acros These families are in the live catalog (`command_list` / `vectorcraft://commands`); the prompt `trace-and-style` already walks Image Trace. Short agent entry points: -- Symbols: `symbol.list` (each row includes `registration` 0..8 and `exportType`: `movieClip`|`graphic`), - `symbol.new {name?, registration?, exportType?, nineSlice?, nineSliceGuides?, ids?}`, - `symbol.options {name?, newName?, registration?, exportType?, nineSlice?, nineSliceGuides?}` (`nineSlice` bool turns +- Symbols: `symbol.list` (each row includes `registration` 0..8, `exportType`: `movieClip`|`graphic` and `type`: + `static`|`dynamic`), + `symbol.new {name?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, ids?}`, + `symbol.options {name?, newName?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?}` (`nineSlice` bool turns 9-slice guides on or off; `nineSliceGuides` is `[left, top, right, bottom]`, fractions 0..1 of the symbol size; rows - of `symbol.list` carry `nineSlice`: the guides or `null`), + of `symbol.list` carry `nineSlice`: the guides or `null`; `type` is Symbol Type, `static` by default for the command + and `dynamic` by default in the Symbol Options dialog), `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}`, `symbol.replace`, `symbol.edit`, `symbol.duplicate`, `symbol.selectInstances {name}`. `symbol.new` and `symbol.duplicate {name, newName?}` trim the white space around the name they are given, as `symbol.options` trims `newName`; a blank one gives "New Symbol" or "<name> copy". +- Dynamic symbols: an instance of a symbol whose `type` is `dynamic` changes the appearance of objects in the symbol's + art for itself only and stays linked. `symbol.instance.setAppearance {id?, path, fill?, stroke?, opacity?, blend?}` + names the object by `path`, child indices in paint order from the art's root down through its groups (`[]` is the + root; `[1, 0]` is the first object of the art's second member when that member is a group). `fill` and `stroke` take + a colour string or the paint params of `paint.setFill` (`color`, `none`, `swatch`, `tint`, `gradient`), `opacity` is + 0..100 and `blend` a blend mode name; `null` gives one back to the symbol. It is refused for a static symbol and for + a path that names no object. `symbol.instance.reset {ids?}` drops the selected instances' changes (the Properties + panel's Reset). Redefining the symbol (`symbol.update`) reshapes every instance and keeps each change whose path the + new art still has; `symbol.breakLink` bakes the changes into the expanded art; `symbol.edit` expands the symbol's own + art; making the symbol static drops them. + +```json +{"name":"run_command","arguments":{"command":"symbol.instance.setAppearance","params":{"id":42,"path":[1],"fill":"#d0021b","opacity":80}}} +``` - The Brushes panel menu's Select All Unused: `brush.unused` (a query) lists the brushes no stroke paints with, in library order, and the panel selects them. Strokes in the art (opacity masks included), symbols, graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and graphic styles count, and so do the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 442dba38ac..726ed94833 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (artboard background colors in exports and print, #4937; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (dynamic symbols, #4938; score unchanged, hours 5–9 → 4–8) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -129,9 +129,9 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, dynamic symbols, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guide settings (stored, not drawn) are done | 5–9 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guide settings (stored, not drawn) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, dynamic symbols, symbol libraries, Start Global Edit, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guide settings (stored, not drawn) are done | 5–9 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, symbol libraries, Start Global Edit, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guide settings (stored, not drawn) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged) | | Live vector effects | 5 | 85% | Outline Object, SVG Filters, a Transform effect in a fill's or stroke's own effects ignoring Transform Patterns and Scale Strokes & Effects | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility); materials, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | @@ -140,7 +140,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Type core | 9 | 80% | Auto-leading style resets are implemented; remaining: hyphenation and justification options, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; colour emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; scores and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Raster effects (Effect Gallery) | 4 | 52% | the Effect Gallery's filter thumbnails and in-dialog preview area ([Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html)) | 1–2 | estimated (raised from 49%: the Effect Gallery shipped, #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `dialogs::effect_gallery::tests::stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; depth estimated | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, dynamic symbols, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration and Export Type (Graphic / Movie Clip) are done | 5–9 | estimated | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration and Export Type (Graphic / Movie Clip) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers panel row context menus and Collect for Export (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated; document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | @@ -1415,10 +1415,15 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Document Tools › New Symbols from Layers makes one symbol of each top-level layer's art (the layers given, else those highlighted in the Layers panel when two or more are, else every layer), named after the layer (a number added when a symbol has that name), with New Symbol's own steps: the art normalized to its natural size, registration in the centre, threaded text keeping the text it shows, and sublayers held as groups. Convert Layers to Symbols does the same and puts an instance of each symbol in place of its layer's art, at the same place and size, selecting the instances; locked layers are skipped then. Empty layers are skipped and reported, all in one undo step (none when nothing is made). Tests: `cmd::addons::document::tests` in `vectorcraft-engine` (a symbol per layer, unique names, empty and locked layers reported, replacement in place, the highlighted layers as the default, bad layer ids refused, one undo step), `new_symbols_from_layers_and_convert_layers_to_symbols` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Document Tools add-on. +## Dynamic symbols (2026-11-01) + +Symbols area (#4938), from the public symbol documentation ([create and place symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html), [edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html)). Symbol Options has Symbol Type (Dynamic Symbol / Static Symbol; the dialog's default is Dynamic, `symbol.new`'s `type` defaults to static so scripts behave as before). An instance of a dynamic symbol keeps its own fill, stroke, opacity and blend for any object of the symbol's art, named by a child-index path (`symbol.instance.setAppearance`), and stays an instance: the canvas, SVG, PDF, EPS, legacy `.ai`, EMF/WMF and DXF writers, effects and Expand draw the art with those changes. Redefining the symbol reshapes every instance and keeps each change whose object the new art still has; Break Link bakes the changes into the art; Edit Symbol expands the symbol's own art; Reset (`symbol.instance.reset`: the Properties panel's Quick Actions and the Symbols panel menu) and making the symbol static drop them. The type is stored on the symbol and the changes on the instance in the native format, both left out when unset, so documents without them save byte for byte as before. Remaining: Direct Selection of an object inside a dynamic instance on the canvas (with the Fill/Stroke controls then setting its change), and reading and writing the type and changes in `.ai` files. Evidence: `crates/engine/src/tests/dynamic_symbols.rs`, `crates/doc/src/symbol_overrides.rs` tests. Score unchanged at 87% (estimated); hours 5–9 → 4–8. + ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Symbols: dynamic symbols (#4938): Symbol Options › Symbol Type, per-instance appearance for objects of a dynamic symbol's art that stays linked through redefinition, Break Link baking, Reset and Static dropping it; evidence added. Score unchanged at 87% (estimated), hours 5–9 → 4–8. | | 2026-11-01 | minor | Artboard background colors in output (#4937): raster exports (a transparent background too), PDF, SVG and EPS pages, `.ai` files' PDF pages, Export for Screens and print (and its preview) draw each artboard's color behind its art, inside the artboard and in the color's own model; Export for Screens has Include Artboard Fill beside Include Bleed (on by default, remembered; `includeArtboardFill`, also on `document.export` and `file.print`); editing data keeps the color as the artboard's, and Export for Screens' document rows keep it too; evidence updated; scores unchanged. | | 2026-11-01 | minor | Selection: Select › Start Global Edit on a group takes the groups like it (the same objects at the same places, moved or scaled; Appearance, Size and the artboard options apply) and gives an edit made to an object inside one to the object at its place in each of the others, in proportion, as one undo step (#4939); Global Edit of rotated copies and Shift-click exclusion remain. Score unchanged at 85% (estimated), hours unchanged. | | 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): New Symbols from Layers (#4927); evidence added; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e9b977ff79..7a68606d7f 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Export for Screens: Include Artboard Fill, #4937) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (dynamic symbols, #4938) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -304,7 +304,8 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; only one built-in library (original, generated in code) | | Brush libraries: Window › Brush Libraries (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; four built-in libraries (original, generated in code) | -| Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (guides stored, not drawn on the canvas); Dynamic/Static symbol type still missing | +| Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (guides stored, not drawn on the canvas); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938) | +| Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; on-canvas Direct Selection of a part inside an instance (with the Fill/Stroke controls then setting its change) remains | | Pathfinder Trim, Merge and Crop remove strokes; Merge joins same-fill objects whatever their strokes | done | #1570 (#1572) | | Pathfinder panel on one group selected alone; a greyed-out button says what it needs | partial | #1450; the group's members are combined; one plain path selected alone stays disabled (the public documentation doesn't say what the operations do to a single path) | | Pathfinder Divide: an open cutting line splits a filled path | done | #1307; straight, crossed, bent and curved cutters, holes and frontmost appearance regression-tested; native automation: independent piece movement, one Undo/Redo, saved-document round trip and window capture; existing bounded-map fallback remains | @@ -385,6 +386,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Dynamic symbols (#4938): Symbol Options › Symbol Type; per-instance appearance for objects of a dynamic symbol's art; Reset in the Properties panel and the Symbols panel menu; on-canvas Direct Selection of the parts remains | | 2026-11-01 | minor | Export for Screens has Include Artboard Fill beside Include Bleed (on by default, remembered; `includeArtboardFill`): the files draw each artboard's background color behind its art, as exports and print now do, and the Print dialog's preview shows it (#4937); scores and estimates unchanged | | 2026-11-01 | minor | Select › Start Global Edit on a group takes the groups like it (the same objects at the same places, moved or scaled; Appearance, Size and the artboard options apply) and gives an edit made to an object inside one to the object at its place in each of the others, in proportion, as one undo step (#4939). Scores and estimates unchanged | | 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): New Symbols from Layers and Convert Layers to Symbols (#4927); scores and estimates unchanged | From cbde11d59307b6419a63ca725162c5996be164e7 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 13:54:42 -0700 Subject: [PATCH 179/260] Fix #2105: the window asks the GPU for no more than it offers eframe's default device descriptor asks for wgpu's default limits (WebGL2 defaults on OpenGL) with 8192 px textures, whatever the adapter offers. A GPU short of any one of them, such as a Raspberry Pi 5's V3D 7.1 (15 inter-stage shader variables on Vulkan, 4096 px textures on OpenGL), failed to create a device, and the window fell back to the software rasterizer. The device now asks for eframe's limits lowered to the adapter's wherever the adapter offers less, and for the adapter's own texture side, which still raises it above 8192 px when the adapter allows more (#1459). --- apps/vectorcraft/src/gpu.rs | 13 ++++++++----- apps/vectorcraft/src/gpu/tests.rs | 29 ++++++++++++++++++++++++++--- apps/vectorcraft/src/main.rs | 11 ++++++----- 3 files changed, 40 insertions(+), 13 deletions(-) diff --git a/apps/vectorcraft/src/gpu.rs b/apps/vectorcraft/src/gpu.rs index 431d403463..00f92405e3 100644 --- a/apps/vectorcraft/src/gpu.rs +++ b/apps/vectorcraft/src/gpu.rs @@ -182,11 +182,14 @@ fn any_hardware(kinds: &[DeviceType]) -> bool { kinds.iter().any(|k| *k != DeviceType::Cpu) } -/// The largest texture side to ask the device for, which bounds the window's surface: the -/// adapter's own limit when it is above eframe's `default` (8192 px), so a window larger than -/// that keeps its surface (#1459). Never below `default`, which is what was asked for before. -pub fn surface_limit(default: u32, adapter: u32) -> u32 { - default.max(adapter) +/// The limits to ask the device for: what eframe `asked` for, lowered to what the `adapter` offers +/// wherever it offers less, so a GPU short of one of them still gets a device (#2105). The texture +/// side, which bounds the window's surface, is the adapter's own, above eframe's 8192 px when the +/// adapter allows more, so a window larger than that keeps its surface (#1459). +pub fn device_limits(asked: wgpu::Limits, adapter: &wgpu::Limits) -> wgpu::Limits { + let mut limits = asked.or_worse_values_from(adapter); + limits.max_texture_dimension_2d = adapter.max_texture_dimension_2d; + limits } /// One adapter, as [`adapter_order`] sees it. diff --git a/apps/vectorcraft/src/gpu/tests.rs b/apps/vectorcraft/src/gpu/tests.rs index 3d13b51579..b1511a232a 100644 --- a/apps/vectorcraft/src/gpu/tests.rs +++ b/apps/vectorcraft/src/gpu/tests.rs @@ -5,11 +5,34 @@ fn gpu(name: &str, backend: Backend, device_type: DeviceType) -> Candidate { } /// #1459: a 9048 px wide window (two display scales' ratio past 8192) fits an adapter that -/// takes 16384 px textures; an adapter with less than eframe asks for changes nothing. +/// takes 16384 px textures. #[test] fn the_surface_may_be_as_large_as_the_adapter_allows() { - assert_eq!(surface_limit(8192, 16384), 16384); - assert_eq!(surface_limit(8192, 4096), 8192); + let adapter = wgpu::Limits { max_texture_dimension_2d: 16384, ..wgpu::Limits::default() }; + let asked = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::default() }; + assert_eq!(device_limits(asked, &adapter).max_texture_dimension_2d, 16384); +} + +/// #2105: a GPU that offers less than eframe asks for on any limit (here a Raspberry Pi 5's V3D 7.1: +/// 15 inter-stage variables on Vulkan, 4096 px textures on OpenGL) gets a device with what it +/// offers, instead of failing and leaving the window to the software rasterizer. A GPU that offers +/// more is asked for no more than before, except for the texture side. +#[test] +fn the_device_asks_for_no_more_than_the_adapter_offers() { + let asked = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::default() }; + let vulkan = wgpu::Limits { max_inter_stage_shader_variables: 15, max_texture_dimension_2d: 7680, ..wgpu::Limits::default() }; + let limits = device_limits(asked.clone(), &vulkan); + assert_eq!((limits.max_inter_stage_shader_variables, limits.max_texture_dimension_2d), (15, 7680)); + assert!(limits.check_limits(&vulkan), "{limits:?}"); + let gl = wgpu::Limits { max_texture_dimension_2d: 4096, ..wgpu::Limits::downlevel_webgl2_defaults() }; + let webgl2 = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::downlevel_webgl2_defaults() }; + let limits = device_limits(webgl2.clone(), &gl); + assert_eq!(limits.max_texture_dimension_2d, 4096); + assert!(limits.check_limits(&gl), "{limits:?}"); + let ample = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::default() }; + assert_eq!(device_limits(asked.clone(), &le), asked); + let better = wgpu::Limits { max_inter_stage_shader_variables: 31, max_texture_dimension_2d: 8192, ..wgpu::Limits::default() }; + assert_eq!(device_limits(asked.clone(), &better), asked, "never more than eframe asked for"); } fn names(c: &[Candidate], order: &[usize]) -> Vec<String> { diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index a7d86d201e..8bb9600af4 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -346,14 +346,15 @@ fn main() -> std::process::ExitCode { // losing the device before the first frame (#1194). `WGPU_DX12_COMPILER` picks another. create.instance_descriptor.backend_options.dx12.shader_compiler = eframe::wgpu::Dx12Compiler::from_env().unwrap_or(eframe::wgpu::Dx12Compiler::Fxc); - // The window's surface may be as large as the adapter allows, not eframe's fixed - // 8192 px: a window stretched over several monitors, or grown by a display scale - // change, otherwise fails to configure its surface and the app closes (#1459). + // The device asks for no more than the adapter offers, so a GPU short of one of + // eframe's limits still gets a device (#2105). The window's surface may be as large as + // the adapter allows, not eframe's fixed 8192 px: a window stretched over several + // monitors, or grown by a display scale change, otherwise fails to configure its + // surface and the app closes (#1459). let device = create.device_descriptor.clone(); create.device_descriptor = std::sync::Arc::new(move |adapter: &eframe::wgpu::Adapter| { let mut descriptor = device(adapter); - let limit = &mut descriptor.required_limits.max_texture_dimension_2d; - *limit = gpu::surface_limit(*limit, adapter.limits().max_texture_dimension_2d); + descriptor.required_limits = gpu::device_limits(descriptor.required_limits, &adapter.limits()); descriptor }); } From af86b2c833f9383b3687ab155db751c4d903880f Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 12:12:00 -0700 Subject: [PATCH 180/260] Objects on Path: double-clicking the tool opens its options Double-clicking the Objects on Path tool opens Objects on Path Tool Options: a nine-point Pivot grid, a Rotate field, Reset (the center and 0) and Save. Save sets the tool's options, which last across tool switches and are saved with the preferences. The tool sends them with each attach, and object.objectsOnPath.attach without pivot or rotate uses them, so they apply to the objects attached next; groups attached before keep theirs. --- crates/engine/src/cmd/objects_on_path.rs | 13 +- crates/engine/src/tests/objects_on_path.rs | 28 ++++ crates/tools/src/objects_on_path.rs | 63 +++++++- crates/tools/src/settings.rs | 2 + crates/ui-egui/src/dialogs.rs | 2 + .../src/dialogs/objects_on_path_options.rs | 137 ++++++++++++++++++ crates/ui-egui/src/dialogs/tests.rs | 31 ++++ crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/toolbar.rs | 6 +- docs/mcp.md | 18 ++- docs/target-app-parity.md | 3 +- 37 files changed, 340 insertions(+), 17 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/objects_on_path_options.rs diff --git a/crates/engine/src/cmd/objects_on_path.rs b/crates/engine/src/cmd/objects_on_path.rs index cbdba5a802..4829d770c4 100644 --- a/crates/engine/src/cmd/objects_on_path.rs +++ b/crates/engine/src/cmd/objects_on_path.rs @@ -5,8 +5,9 @@ //! bottom. Called without a path (Object › Objects on Path › Attach) it chooses the Objects on Path //! tool, whose click on a path attaches the selected objects to that path. The objects go along the //! path column by column from left to right, top to bottom in each column, spread evenly from its -//! first anchor and turned to follow it. `object.objectsOnPath.options` sets the group's Pivot and -//! Rotate, and `object.objectsOnPath.expand` makes it a plain group. +//! first anchor and turned to follow it. Pivot and Rotate come from the command's params, otherwise +//! from the tool's options (Objects on Path Tool Options). `object.objectsOnPath.options` sets the +//! group's Pivot and Rotate, and `object.objectsOnPath.expand` makes it a plain group. //! //! After every edit, [`refresh`] puts the objects of each Objects on Path group that changed back //! on its path: editing the path moves them, an object moved on its own goes back to its place, @@ -38,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> { "Attach", ["Object", "Objects on Path"], None, - "{path?: id of the path to attach to (without it: choose the Objects on Path tool, whose click on a path attaches the selection to it), ids?: the objects to attach (default: the selection; the path is left out of it), pivot?: 0-8 (the reference point of each object that attaches to the path, row by row from the top left; default 4, the center), rotate?: degrees counter-clockwise from upright on the path (default 0)} put the objects and the path in an Objects on Path group: the path at the bottom, the objects spread evenly along it from its first anchor (the last one at the end of an open path) in their order on the canvas, column by column from left to right and top to bottom in each column, each turned to follow the path; editing the path moves them → {id}", + "{path?: id of the path to attach to (without it: choose the Objects on Path tool, whose click on a path attaches the selection to it), ids?: the objects to attach (default: the selection; the path is left out of it), pivot?: 0-8 (the reference point of each object that attaches to the path, row by row from the top left; default: the Objects on Path tool's Pivot, 4, the center, until its options change it), rotate?: degrees counter-clockwise from upright on the path (default: the tool's Rotate, 0 until its options change it)} put the objects and the path in an Objects on Path group: the path at the bottom, the objects spread evenly along it from its first anchor (the last one at the end of an open path) in their order on the canvas, column by column from left to right and top to bottom in each column, each turned to follow the path; editing the path moves them → {id}", has_selection, attach ), @@ -200,7 +201,11 @@ fn attach(s: &mut Session, p: &Value) -> Result<Value> { return Ok(json!({ "tool": TOOL })); }; let path = checked_id(s, path, C)?; - let (pivot, rotate) = pivot_rotate(p, C, CENTER, 0.0)?; + // Without them in `p`, the tool's options (Objects on Path Tool Options) give Pivot and Rotate. + let saved = s.tool_options_of(TOOL); + let tool_pivot = saved.get("pivot").and_then(Value::as_u64).filter(|n| *n <= 8).map_or(CENTER, |n| n as u8); + let tool_rotate = saved.get("rotate").and_then(Value::as_f64).filter(|r| r.is_finite()).unwrap_or(0.0); + let (pivot, rotate) = pivot_rotate(p, C, tool_pivot, tool_rotate)?; let roots = match p.get("ids") { Some(_) => roots_of(&s.doc()?.doc, checked_ids_param(s, p, "ids", C)?), None => selected_roots(s)?, diff --git a/crates/engine/src/tests/objects_on_path.rs b/crates/engine/src/tests/objects_on_path.rs index a6015b158e..a309eb69ba 100644 --- a/crates/engine/src/tests/objects_on_path.rs +++ b/crates/engine/src/tests/objects_on_path.rs @@ -186,6 +186,34 @@ fn pivot_picks_the_point_that_sits_on_the_path() { assert!((b.y0 - 300.0).abs() < 1e-6, "hanging from the line by their top edge: {b:?}"); } +#[test] +fn the_tool_options_set_pivot_and_rotate_for_the_objects_attached_next_only() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let other = line(&mut s, (50.0, 380.0), (350.0, 380.0)); + let third = line(&mut s, (50.0, 200.0), (350.0, 200.0)); + let before = attach(&mut s, path, &[left], json!({})); + let rec = |s: &Session, g: NodeId| { + let r = s.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path.as_deref().map(|r| (r.pivot, r.rotate)); + r.unwrap() + }; + assert_eq!(rec(&s, before), (4, 0.0), "the center, upright"); + // Objects on Path Tool Options' Save (`tool.setOption`): the tool keeps them while another tool + // is chosen. + let values = |v: Value| v.as_object().cloned().unwrap_or_default(); + s.set_tool_options(Some("objectsOnPath"), &values(json!({"pivot": 7, "rotate": 30}))); + assert_eq!(s.tool_options_of("objectsOnPath"), json!({"pivot": 7, "rotate": 30.0})); + let next = attach(&mut s, other, &[middle], json!({})); + assert_eq!(rec(&s, next), (7, 30.0), "the objects attached next take them"); + assert_eq!(rec(&s, before), (4, 0.0), "the ones already attached keep theirs"); + // Values given to the command win over the tool's. + let given = attach(&mut s, third, &[right], json!({"pivot": 1, "rotate": 0})); + assert_eq!(rec(&s, given), (1, 0.0)); + // Reset puts the center and 0 back. + s.set_tool_options(Some("objectsOnPath"), &values(json!({"pivot": 4, "rotate": 0}))); + assert_eq!(s.tool_options_of("objectsOnPath"), json!({"pivot": 4, "rotate": 0.0})); +} + #[test] fn a_closed_path_spreads_the_objects_all_the_way_round_from_its_first_anchor() { let mut s = session(); diff --git a/crates/tools/src/objects_on_path.rs b/crates/tools/src/objects_on_path.rs index b699601ab7..d5be195254 100644 --- a/crates/tools/src/objects_on_path.rs +++ b/crates/tools/src/objects_on_path.rs @@ -1,12 +1,14 @@ //! The Objects on Path tool (#2545): a click on a path attaches the selected objects to it //! (`object.objectsOnPath.attach`). A path they can attach to is highlighted under the pointer, -//! and the pointer shows [`Cursor::ObjectsOnPath`] over it. +//! and the pointer shows [`Cursor::ObjectsOnPath`] over it. The tool's options, `pivot` (0-8, row +//! by row from the top left; 4, the center) and `rotate` (degrees), go with each attach, so they +//! set how the objects attached next attach; groups attached before keep theirs. //! //! Behavior: <https://helpx.adobe.com/illustrator/using/objects-on-path.html>. -use serde_json::json; +use serde_json::{Value, json}; use vectorcraft_doc::NodeId; -use vectorcraft_doc::objects_on_path::{attachable_path, is_objects_on_path}; +use vectorcraft_doc::objects_on_path::{CENTER, attachable_path, is_objects_on_path}; use vectorcraft_geom::{BezPath, Point}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -31,12 +33,21 @@ pub fn target(cx: &ToolContext, p: Point) -> Option<(NodeId, BezPath)> { cx.selection.objects.iter().any(|id| *id != h.leaf).then(|| (h.leaf, path.to_bezpath())) } -#[derive(Default)] pub struct ObjectsOnPathTool { /// The path under the pointer the selection can attach to, and its outline. hover: Option<(NodeId, BezPath)>, /// Where the press was, while the button is down. press: Option<Point>, + /// The reference point of each object attached next (0-8, row by row from the top left). + pivot: u8, + /// The angle of each object attached next, in degrees counter-clockwise from upright on the path. + rotate: f64, +} + +impl Default for ObjectsOnPathTool { + fn default() -> Self { + Self { hover: None, press: None, pivot: CENTER, rotate: 0.0 } + } } impl Tool for ObjectsOnPathTool { @@ -60,7 +71,7 @@ impl Tool for ObjectsOnPathTool { let Some(start) = self.press.take().filter(|q| q.distance(p) < cx.tol(3.0)) else { return vec![] }; let Some((path, _)) = target(cx, start) else { return vec![] }; self.hover = None; - vec![Action::Exec("object.objectsOnPath.attach".into(), json!({ "path": path.0 }))] + vec![Action::Exec("object.objectsOnPath.attach".into(), json!({ "path": path.0, "pivot": self.pivot, "rotate": self.rotate }))] } _ => vec![], } @@ -83,6 +94,28 @@ impl Tool for ObjectsOnPathTool { vec![] } + fn options(&self) -> Value { + json!({ "pivot": self.pivot, "rotate": self.rotate }) + } + + /// `pivot` takes a whole number from 0 to 8 and `rotate` a finite number; other values are + /// ignored. + fn set_option(&mut self, key: &str, value: &Value) { + match key { + "pivot" => { + if let Some(n) = value.as_u64().filter(|n| *n <= 8) { + self.pivot = n as u8; + } + } + "rotate" => { + if let Some(r) = value.as_f64().filter(|r| r.is_finite()) { + self.rotate = r; + } + } + _ => {} + } + } + fn busy(&self) -> bool { self.press.is_some() } @@ -132,6 +165,26 @@ mod tests { assert!(matches!(acts.as_slice(), [Action::Exec(id, p)] if id == "object.objectsOnPath.attach" && p["path"] == line.0), "{acts:?}"); } + #[test] + fn the_click_sends_the_tool_options_pivot_and_rotate() { + let (d, _, square) = doc(); + let mut sel = Selection::default(); + sel.set([square]); + let paint = paint(); + let cx = cx(&d, &sel, &paint); + let mut t = ObjectsOnPathTool::default(); + assert_eq!(t.options(), json!({ "pivot": 4, "rotate": 0.0 }), "the center, upright"); + t.set_option("pivot", &json!(0)); + t.set_option("rotate", &json!(45.5)); + // Values out of range are ignored. + t.set_option("pivot", &json!(9)); + t.set_option("rotate", &json!("x")); + assert_eq!(t.options(), json!({ "pivot": 0, "rotate": 45.5 })); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 300.0)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 200.0, 300.0)); + assert!(matches!(acts.as_slice(), [Action::Exec(_, p)] if p["pivot"] == 0 && p["rotate"] == 45.5), "{acts:?}"); + } + #[test] fn escape_during_the_press_cancels_the_click() { let (d, _, square) = doc(); diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 97d2b327c3..1e94c6d2c4 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -65,6 +65,8 @@ const ROWS: &[Row] = &[ "highlightColor", ], ), + // Objects on Path Tool Options: the Pivot and Rotate of the objects attached next. + (&["objectsOnPath"], None, &["pivot", "rotate"]), (&["artboard"], None, &["moveArt", "scaleArt"]), // The add-ons' tools (`crate::addons`). (&[crate::addons::anchor_eraser::ID], None, &["size", "tolerance", "pressure"]), diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 0f23c2bc4a..f9da884c40 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -66,6 +66,7 @@ pub mod new_color_group; mod new_document; pub mod new_swatch; pub mod new_text_style; +pub mod objects_on_path_options; pub mod office_export; pub mod package; pub(crate) mod path_ops; @@ -377,6 +378,7 @@ registry! { LiquifyOptions: [liquify::KIND] => liquify::SPEC, FreehandOptions: [freehand::KIND] => freehand::SPEC, ShapeBuilderOptions: [shape_builder_options::KIND] => shape_builder_options::SPEC, + ObjectsOnPathOptions: [objects_on_path_options::KIND] => objects_on_path_options::SPEC, FlareOptions: [flare_options::KIND] => flare_options::SPEC, SymbolOptions: [symbol_options::KIND] => symbol_options::SPEC, DeleteSymbol: [symbol_delete::KIND] => symbol_delete::SPEC, diff --git a/crates/ui-egui/src/dialogs/objects_on_path_options.rs b/crates/ui-egui/src/dialogs/objects_on_path_options.rs new file mode 100644 index 0000000000..06aae7f8e0 --- /dev/null +++ b/crates/ui-egui/src/dialogs/objects_on_path_options.rs @@ -0,0 +1,137 @@ +//! Objects on Path Tool Options (double-click the Objects on Path tool): the Pivot and Rotate of +//! the objects the tool attaches next. Groups attached before keep theirs. Save sets them with +//! `tool.setOption {tool: "objectsOnPath", values}`; they last across tool switches and are saved +//! with the preferences. Reset puts the center and 0 back. +//! +//! Fields: `pivot` (0-8, row by row from the top left; 4, the center) and `rotate` (degrees +//! counter-clockwise from upright on the path). +//! +//! Behavior: <https://helpx.adobe.com/illustrator/using/objects-on-path.html>. + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::objects_on_path::CENTER; + +use super::{DialogSpec, run_and_close}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Objects on Path Tool Options. +pub const KIND: &str = "objectsOnPathOptions"; + +/// The tool whose options the dialog edits. +const TOOL: &str = "objectsOnPath"; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, ok: Some("Save"), reset: Some(reset), min_width: 300.0, ..DialogSpec::FORM }; + +/// Width of the label column. +const LABEL_W: f32 = 70.0; + +fn heading(_: &Dialog) -> String { + let label = vectorcraft_tools::tool_info(TOOL).map_or("", |t| t.label); + crate::i18n::fmt(tl!("{tool} Options"), &[("tool", tl!(label))]) +} + +/// Open the tool's options with their current values. +pub fn open(app: &mut VectorcraftApp) -> Value { + let o = app.session.tool_options_of(TOOL); + let fields: Map<String, Value> = ["pivot", "rotate"].iter().filter_map(|key| Some((key.to_string(), o.get(*key)?.clone()))).collect(); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + json!({ "dialog": KIND }) +} + +/// Reset: the center and 0. +fn reset(_: &VectorcraftApp, d: &mut Dialog) { + d.fields.insert("pivot".into(), json!(CENTER)); + d.fields.insert("rotate".into(), json!(0.0)); +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + widgets::label_row(ui, tl!("Pivot:"), LABEL_W, |ui| { + let current = d.f64("pivot", f64::from(CENTER)).clamp(0.0, 8.0) as usize; + if let Some(i) = widgets::reference_point(ui, current) { + d.fields.insert("pivot".into(), json!(i)); + } + }); + ui.add_space(8.0); + widgets::label_row(ui, tl!("Rotate:"), LABEL_W, |ui| { + if let Some(r) = widgets::range_field(ui, "objects-on-path-rotate", d.f64("rotate", 0.0), -360.0..=360.0, "°", 1, 64.0) { + d.fields.insert("rotate".into(), json!(r)); + } + }); + ui.add_space(8.0); + let r = widgets::flat_button(ui, tl!("Reset"), 64.0); + r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Reset"))); + if r.clicked() { + reset(app, d); + } + false +} + +/// Save: set the tool's Pivot and Rotate. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { + let values: Map<String, Value> = ["pivot", "rotate"].iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); + run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app + } + + /// The labels the open dialog paints. + fn painted(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + } + + /// The Pivot and Rotate of the Objects on Path group `g`. + fn record(app: &VectorcraftApp, g: &Value) -> (u8, f64) { + let id = vectorcraft_doc::NodeId(g["id"].as_u64().unwrap()); + let n = app.session.doc().unwrap().doc.node(id).unwrap(); + n.extras().objects_on_path.as_deref().map(|r| (r.pivot, r.rotate)).unwrap() + } + + #[test] + fn double_clicking_the_tool_opens_its_options_and_save_sets_the_next_attach() { + let mut app = app(); + let first = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let line = app.run("shape.line", json!({"x1": 50, "y1": 300, "x2": 350, "y2": 300})).unwrap(); + app.run("select.set", json!({"ids": [first["id"]]})).unwrap(); + let before = app.run("object.objectsOnPath.attach", json!({"path": line["id"]})).unwrap(); + let r = app.run("tool.options", json!({"tool": "objectsOnPath"})).unwrap(); + assert_eq!(r["dialog"], json!(KIND)); + let text = painted(&mut app); + for label in ["Objects on Path Tool Options", "Pivot:", "Rotate:", "Reset", "Save", "Cancel"] { + assert!(text.contains(label), "{label} in {text}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((d.f64("pivot", -1.0), d.f64("rotate", -1.0)), (4.0, 0.0), "the center and 0"); + d.fields.insert("pivot".into(), json!(7)); + d.fields.insert("rotate".into(), json!(30)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + // They last while another tool is chosen, and the dialog opens on them again. + app.select_tool("objectsOnPath"); + app.select_tool("selection"); + assert_eq!(app.session.tool_options_of(TOOL), json!({"pivot": 7, "rotate": 30.0})); + // The objects attached next take them; the group attached before keeps its own. + let second = app.run("shape.rectangle", json!({"x": 100, "y": 10, "width": 20, "height": 20})).unwrap(); + let other = app.run("shape.line", json!({"x1": 50, "y1": 380, "x2": 350, "y2": 380})).unwrap(); + app.run("select.set", json!({"ids": [second["id"]]})).unwrap(); + let next = app.run("object.objectsOnPath.attach", json!({"path": other["id"]})).unwrap(); + assert_eq!(record(&app, &next), (7, 30.0)); + assert_eq!(record(&app, &before), (4, 0.0)); + // Reset puts the center and 0 back, and Save keeps them. + app.run("tool.options", json!({"tool": "objectsOnPath"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("pivot", -1.0), d.f64("rotate", -1.0)), (7.0, 30.0)); + super::super::reset(&mut app).unwrap(); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options_of(TOOL), json!({"pivot": 4, "rotate": 0.0})); + } +} diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 6c65ea6d23..4fc17b097e 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1368,6 +1368,37 @@ fn artboard_options_x_and_y_count_from_the_ruler_origin_at_the_reference_point() assert!(has(&shown, "Width:") && !has(&shown, "X:") && !has(&shown, "Y:"), "{shown:?}"); } +/// Objects on Path Tool Options: a click on one of the nine Pivot points and a typed Rotate set the +/// fields, Enter saves them as the tool's options, and the Reset button puts the center and 0 back. +#[test] +fn objects_on_path_tool_options_pivot_grid_rotate_field_and_reset() { + let mut app = app(); + app.run("tool.options", json!({"tool": "objectsOnPath"})).unwrap(); + let mut f = Frames::new(); + let bottom = f.control(&mut app, "Bottom", egui::accesskit::Role::RadioButton); + f.press(&mut app, bottom, true); + f.press(&mut app, bottom, false); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("pivot", -1.0), 7.0); + // The field is right of the 70 pt label column. + let shown = f.texts(&mut app); + let label = shown.iter().find(|(t, _)| t == "Rotate:").unwrap_or_else(|| panic!("no Rotate: in {shown:?}")).1; + let at = egui::pos2(label.left() + 70.0 + 30.0, label.center().y); + f.press(&mut app, at, true); + f.press(&mut app, at, false); + f.run(&mut app, vec![egui::Event::Text("45".into())]); + f.key(&mut app, egui::Key::Enter, egui::Modifiers::NONE); + assert!(app.ui.dialog.is_none(), "Enter saves the dialog"); + assert_eq!(app.session.tool_options_of("objectsOnPath"), json!({"pivot": 7, "rotate": 45.0})); + app.run("tool.options", json!({"tool": "objectsOnPath"})).unwrap(); + let reset = f.button(&mut app, "Reset"); + f.press(&mut app, reset, true); + f.press(&mut app, reset, false); + let d = app.ui.dialog.as_ref().expect("Reset keeps the dialog open"); + assert_eq!((d.f64("pivot", -1.0), d.f64("rotate", -1.0)), (4.0, 0.0)); + confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options_of("objectsOnPath"), json!({"pivot": 4, "rotate": 0.0})); +} + /// #1876: a new Width or Height in Artboard Options keeps the reference point where it was, as the /// Transform panel's does: about the center by default, so X and Y still read the same, and from /// the top-left corner with that reference point. diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 39e9235fa3..7f98dbf009 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1426,6 +1426,8 @@ font-technology Variable Променливи Attach Прикрепяне Objects on Path Options Опции за обекти по пътя Objects on Path Tool Инструмент „Обекти по пътя“ + Pivot: Опорна точка: + Rotate: Завъртане: Attach Objects on Path Прикрепяне на обекти към пътя Expand Objects on Path Разширяване на обекти по пътя Release Live Paint Освобождаване на динамично оцветяване diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index ba39e61c97..7184e1b278 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1610,6 +1610,8 @@ digits Malayalam Malajalam Attach Priloži Objects on Path Options Opcije objekata na putanji Objects on Path Tool Alat objekti na putanji + Pivot: Tačka okretanja: + Rotate: Rotacija: Attach Objects on Path Priloži objekte na putanju Expand Objects on Path Proširi objekte na putanji Release Live Paint Oslobodi živo bojenje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index dad0439567..6e05cf66c6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2640,6 +2640,8 @@ digits Malayalam Malaiàlam Objects on Path Objectes sobre el traçat Objects on Path Options Opcions dels objectes sobre el traçat Objects on Path Tool Eina d’objectes sobre el traçat + Pivot: Punt de pivot: + Rotate: Rotació: Objects using them keep their look but are no longer linked. Els objectes que les utilitzen conserven l’aspecte, però ja no estan enllaçats. Ocean Ripple Onada oceànica Ocean Ripple… Onada oceànica… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a660cdb216..07f5c23743 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1636,6 +1636,8 @@ digits Malayalam Malajálamské Attach Připojit Objects on Path Options Možnosti objektů na cestě Objects on Path Tool Nástroj Objekty na cestě + Pivot: Otočný bod: + Rotate: Otočení: Attach Objects on Path Připojit objekty na cestu Expand Objects on Path Rozložit objekty na cestě Release Live Paint Uvolnit živou malbu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 96bcb3327c..c8919058c1 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5396,6 +5396,8 @@ swatch Bright Violet Kraftig violet Attach Tilknyt Objects on Path Options Indstillinger for objekter på kurve Objects on Path Tool Objekter på kurve-værktøj + Pivot: Omdrejningspunkt: + Rotate: Rotation: Attach Objects on Path Tilknyt objekter til kurve Expand Objects on Path Udvid objekter på kurve Release Live Paint Frigør live-maling diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 65a846eb7c..6b85051139 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1460,6 +1460,8 @@ file-filter Templates Vorlagen Attach Anhängen Objects on Path Options Optionen für Objekte auf Pfad Objects on Path Tool Objekte-auf-Pfad-Werkzeug + Pivot: Drehpunkt: + Rotate: Drehung: Attach Objects on Path Objekte an Pfad anhängen Expand Objects on Path Objekte auf Pfad umwandeln Release Live Paint „Interaktiv malen“ zurückwandeln diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 6426946db6..b465d8a657 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1390,6 +1390,8 @@ font-technology Variable Μεταβλητές Attach Προσάρτηση Objects on Path Options Επιλογές αντικειμένων σε διαδρομή Objects on Path Tool Αντικείμενα σε διαδρομή (Objects on Path Tool) + Pivot: Σημείο περιστροφής: + Rotate: Περιστροφή: Attach Objects on Path Προσάρτηση αντικειμένων σε διαδρομή Expand Objects on Path Επέκταση αντικειμένων σε διαδρομή Release Live Paint Αποδέσμευση δυναμικής βαφής diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 104ed8668a..413277af4d 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1464,6 +1464,8 @@ font-technology Variable Variables Attach Adjuntar Objects on Path Options Opciones de objetos en trazado Objects on Path Tool Herramienta Objetos en trazado + Pivot: Pivote: + Rotate: Rotación: Attach Objects on Path Adjuntar objetos al trazado Expand Objects on Path Expandir objetos en trazado Release Live Paint Soltar pintura interactiva diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1c8f92623c..3011e59738 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1609,6 +1609,8 @@ digits Malayalam Malajalam Attach Kiinnitä Objects on Path Options Objektit polulla -asetukset Objects on Path Tool Objektit polulla -työkalu + Pivot: Kiertopiste: + Rotate: Kierto: Attach Objects on Path Kiinnitä objektit polulle Expand Objects on Path Laajenna objektit polulla Release Live Paint Vapauta elävä maalaus diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6f0fe8aca3..310996719a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1464,6 +1464,8 @@ font-technology Variable Variables Attach Attacher Objects on Path Options Options d’objets sur tracé Objects on Path Tool Outil Objets sur tracé + Pivot: Pivot : + Rotate: Rotation : Attach Objects on Path Attacher des objets au tracé Expand Objects on Path Décomposer les objets sur tracé Release Live Paint Annuler la peinture dynamique diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 10f83807ee..deef0995f3 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1861,6 +1861,8 @@ file-filter Templates Sablonok Attach Csatolás Objects on Path Options Objektumok útvonalon beállításai Objects on Path Tool Objektumok útvonalon + Pivot: Forgáspont: + Rotate: Elforgatás: Attach Objects on Path Objektumok csatolása útvonalhoz Expand Objects on Path Objektumok útvonalon kibontása Release Live Paint Élő festés megszüntetése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 6cdd3a8cf3..9aef8450bb 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5396,6 +5396,8 @@ swatch Bright Violet Violet cerah Attach Tempelkan Objects on Path Options Opsi objek pada jalur Objects on Path Tool Alat objek pada jalur + Pivot: Titik poros: + Rotate: Rotasi: Attach Objects on Path Tempelkan objek pada jalur Expand Objects on Path Perluas objek pada jalur Release Live Paint Lepaskan Live Paint diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 51ae7f5efb..304c48f4ba 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1484,6 +1484,8 @@ file-filter Templates Modelli Attach Aggancia Objects on Path Options Opzioni oggetti su tracciato Objects on Path Tool Strumento Oggetti su tracciato + Pivot: Perno: + Rotate: Rotazione: Attach Objects on Path Aggancia oggetti al tracciato Expand Objects on Path Espandi oggetti su tracciato Release Live Paint Rilascia pittura dinamica diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 850e481820..4ae7d6fd88 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1774,6 +1774,8 @@ digits Malayalam マラヤーラム数字 Attach アタッチ Objects on Path Options パス上のオブジェクトオプション Objects on Path Tool パス上のオブジェクトツール + Pivot: ピボット: + Rotate: 回転: Attach Objects on Path パス上のオブジェクトをアタッチ Expand Objects on Path パス上のオブジェクトを拡張 Release Live Paint ライブペイントを解除 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 6242e6e05d..261074cff8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5302,6 +5302,8 @@ imageTrace Outline კონტური Attach მიმაგრება Objects on Path Options ტრაექტორიაზე ობიექტების პარამეტრები Objects on Path Tool ტრაექტორიაზე ობიექტების ხელსაწყო + Pivot: საყრდენი წერტილი: + Rotate: შემობრუნება: Attach Objects on Path ობიექტების ტრაექტორიაზე მიმაგრება Expand Objects on Path ტრაექტორიაზე ობიექტების გაშლა Release Live Paint ცოცხალი შეღებვის მოხსნა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index b9d96eed04..05f3c38602 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1764,6 +1764,8 @@ digits Malayalam 말라얄람어 Attach 부착 Objects on Path Options 패스 위 개체 옵션 Objects on Path Tool 패스 위 개체 도구 + Pivot: 피벗: + Rotate: 회전: Attach Objects on Path 패스 위 개체 부착 Expand Objects on Path 패스 위 개체 확장 Release Live Paint 라이브 페인트 해제 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 6a227c3948..579a6458e3 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5407,6 +5407,8 @@ swatch Bright Violet Felviolet Attach Koppelen Objects on Path Options Opties voor objecten op pad Objects on Path Tool Objecten-op-pad-gereedschap + Pivot: Draaipunt: + Rotate: Rotatie: Attach Objects on Path Objecten aan pad koppelen Expand Objects on Path Objecten op pad uitbreiden Release Live Paint Live Paint vrijgeven diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 9443b2488f..3ec4a22e2c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1554,6 +1554,8 @@ digits Malayalam Malajalam Attach Dołącz Objects on Path Options Opcje obiektów na ścieżce Objects on Path Tool Narzędzie Obiekty na ścieżce + Pivot: Punkt obrotu: + Rotate: Obrót: Attach Objects on Path Dołącz obiekty do ścieżki Expand Objects on Path Rozszerz obiekty na ścieżce Release Live Paint Uwolnij aktywne malowanie diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e61e7a1a41..01a472f100 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1270,6 +1270,8 @@ Attach Anexar Objects on Path Options Opções de Objetos no Caminho Objects on Path Tool Ferramenta Objetos no Caminho + Pivot: Pivô: + Rotate: Rotação: Attach Objects on Path Anexar Objetos ao Caminho Expand Objects on Path Expandir Objetos no Caminho Release Live Paint Liberar Pintura ao Vivo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index eb5449f0f4..f54d63b6be 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1482,6 +1482,8 @@ file-filter Templates Шаблоны Attach Прикрепить Objects on Path Options Параметры объектов на контуре Objects on Path Tool Инструмент «Объекты на контуре» + Pivot: Опорная точка: + Rotate: Поворот: Attach Objects on Path Прикрепить объекты к контуру Expand Objects on Path Разобрать объекты на контуре Release Live Paint Освободить быструю заливку diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index a5cd18975a..295726ef6c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1428,6 +1428,8 @@ font-technology Variable Variabla Attach Fäst Objects on Path Options Alternativ för objekt på bana Objects on Path Tool Verktyg för objekt på bana + Pivot: Pivotpunkt: + Rotate: Rotation: Attach Objects on Path Fäst objekt på bana Expand Objects on Path Expandera objekt på bana Release Live Paint Släpp direktmålning diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 36d2676d31..a360aa1fdd 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5375,6 +5375,8 @@ theme Appearance Görünüm Objects on Path Yol Üzerindeki Nesneler Objects on Path Options Yol Üzerindeki Nesneler Seçenekleri Objects on Path Tool Yol Üzerindeki Nesneler Aracı + Pivot: Pivot noktası: + Rotate: Döndürme: Photocopy Fotokopi Photocopy… Fotokopi… Plaster Alçı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 2ae65e2764..298eb966c3 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1478,6 +1478,8 @@ file-filter Templates Шаблони Attach Прикріпити Objects on Path Options Параметри об’єктів на контурі Objects on Path Tool Інструмент «Об’єкти на контурі» + Pivot: Опорна точка: + Rotate: Поворот: Attach Objects on Path Прикріпити об’єкти до контуру Expand Objects on Path Розібрати об’єкти на контурі Release Live Paint Звільнити швидку заливку diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 3ba54b1246..4980968699 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1701,6 +1701,8 @@ digits Hindi Hindi Attach Gắn Objects on Path Options Tùy chọn đối tượng trên đường dẫn Objects on Path Tool Công cụ Đối tượng trên đường dẫn + Pivot: Điểm trục: + Rotate: Xoay: Attach Objects on Path Gắn đối tượng lên đường dẫn Expand Objects on Path Mở rộng đối tượng trên đường dẫn Release Live Paint Giải phóng tô trực tiếp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 7608eec561..061e6bf07b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1412,6 +1412,8 @@ file-filter Templates 模板 Attach 附加 Objects on Path Options 路径上的对象选项 Objects on Path Tool 路径上的对象工具 + Pivot: 枢轴: + Rotate: 旋转: Attach Objects on Path 附加路径上的对象 Expand Objects on Path 扩展路径上的对象 Release Live Paint 释放实时上色 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1482f45727..79d62390de 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1449,6 +1449,8 @@ file-filter Templates 範本 Attach 附加 Objects on Path Options 路徑上的物件選項 Objects on Path Tool 路徑上的物件工具 + Pivot: 樞軸: + Rotate: 旋轉: Attach Objects on Path 附加路徑上的物件 Expand Objects on Path 展開路徑上的物件 Release Live Paint 釋放即時上色 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 355da568fb..20f6d4b239 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -691,7 +691,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (pt), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values})", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (pt), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index a766b6a45f..a3bcaa83f8 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -327,8 +327,8 @@ fn flyout_press(ui: &Ui, resp: &egui::Response, rect: egui::Rect) -> Option<Flyo /// Options; the Print Tiling tool's resets the print tiling. As in the reference app, the Hand /// tool's fits the artboard in the window, the Zoom tool's shows it at 100%, the Rotate, Scale, /// Reflect and Shear tools' are their Object › Transform dialogs, the selection tools' are the -/// Move dialog, and the Pencil, Paintbrush, Smooth, Blob Brush, Eraser and Shape Builder tools' are -/// their Tool Options, as are the Line Segment, Arc, Rectangular Grid and Polar Grid tools' +/// Move dialog, and the Pencil, Paintbrush, Smooth, Blob Brush, Eraser, Shape Builder and Objects +/// on Path tools' are their Tool Options, as are the Line Segment, Arc, Rectangular Grid and Polar Grid tools' /// ([`crate::dialogs::shapes::open_options`]). The Type on a Path and Vertical Type on a Path /// tools' are Type on a Path Options for the selected type on a path. pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result<serde_json::Value, String> { @@ -362,6 +362,8 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result<serde_json:: Ok(json!({ "dialog": crate::dialogs::perspective_options::KIND })) } "shapeBuilder" => Ok(crate::dialogs::shape_builder_options::open(app)), + // The Objects on Path tool: the Pivot and Rotate of the objects it attaches next. + "objectsOnPath" => Ok(crate::dialogs::objects_on_path_options::open(app)), // The Line Segment, Arc and grid tools: their Tool Options, the options of their next // drag and click. _ if crate::dialogs::shapes::OPTION_TOOLS.contains(&tool) => crate::dialogs::shapes::open_options(app, tool), diff --git a/docs/mcp.md b/docs/mcp.md index 9a85428f7a..2b4c2ee3c2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5691,10 +5691,12 @@ opacity mask and appearance (Release on a group around the keys and spine when t the path in their order on the canvas, column by column from left to right and top to bottom in each column. The first one sits on the path's first anchor, the last one sits on the end of an open path, and the others are spread evenly between them by length; on a closed path the gaps run all the way round. The attachment point of each object (`pivot`, -0 to 8 row by row from the top left of its bounds without strokes; default 4, the center) sits on the path, and the -object is turned to the path's direction there. An object rotated by other than a multiple of 90° is first turned to -the nearest multiple. `rotate` tilts every object by that many degrees counter-clockwise. Without `path`, the command -chooses the Objects on Path tool (`objectsOnPath`), whose click on a path sends `{path}`. As the path, the command +0 to 8 row by row from the top left of its bounds without strokes) sits on the path, and the object is turned to the +path's direction there. An object rotated by other than a multiple of 90° is first turned to the nearest multiple. +`rotate` tilts every object by that many degrees counter-clockwise. Without `pivot` or `rotate`, the command uses the +Objects on Path tool's options (4, the center, and 0 until they are changed). Without `path`, the command chooses the +Objects on Path tool (`objectsOnPath`), whose click on a path sends `{path, pivot, rotate}` from its options. As the +path, the command refuses a guide, a compound path, type, a path without length, a path already in an Objects on Path group, a clipping path, and a path inside a compound path, blend, envelope, repeat or Intertwine group. As objects, it skips layers and refuses graphs, objects already in an Objects on Path group, clipping paths, and objects inside a blend, @@ -5711,7 +5713,15 @@ on Path groups or objects in them), or on the groups of the selection when `ids` the group with an `objects_on_path` record; SVG, PDF and the other exports write the path and the objects as plain art. +In the desktop app, double-clicking the Objects on Path tool (`tool.options {tool: "objectsOnPath"}`) opens Objects on +Path Tool Options (dialog `objectsOnPathOptions`): the nine-point Pivot grid and the Rotate field (°). Save sets the +tool's options (`tool.setOption {tool: "objectsOnPath", values: {pivot, rotate}}`), which the objects attached next +use; groups attached before keep their Pivot and Rotate. Reset (or Cancel while Alt, Option on macOS, is held, or +`ui.dialogReset`) puts the center and 0 back and keeps the dialog open. The options last across tool switches and are +saved with the preferences. + ```json +{"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"objectsOnPath","values":{"pivot":7,"rotate":30}}}} {"name":"run_command","arguments":{"command":"object.objectsOnPath.attach","params":{"path":30,"ids":[12,15,18]}}} {"name":"run_command","arguments":{"command":"object.objectsOnPath.options","params":{"pivot":7,"rotate":15}}} {"name":"run_command","arguments":{"command":"object.objectsOnPath.expand","params":{}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 726ed94833..d1d72271c5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -930,7 +930,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When the object the Blend tool picked first is deleted or undone away before the second click, the next click on an object picks that object first instead of doing nothing. Regression tests: `blend_tool_picks_again_when_its_first_pick_is_gone` in `meshblend.rs` and `the_blend_tool_picks_again_when_its_first_pick_is_deleted` in `tests/blendopts.rs`. Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected. With the Blend tool, Escape drops the object clicked first and stops the next click adding to the blend just made, so the next click picks a new first object; the document and the selection stay as they are. Regression tests: `escape_drops_the_blend_tools_first_pick` in `meshblend.rs` and `tests/blendopts.rs`. - Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`). Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. The Space, Move All, Rotate All and Select/Move widgets, Detach, the tool's options dialog and the Properties panel section are missing. + Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`). Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. The Space, Move All, Rotate All and Select/Move widgets, Detach and the Properties panel section are missing. + Double-clicking the Objects on Path tool opens Objects on Path Tool Options ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)): the nine-point Pivot grid and the Rotate field set the attachment point and angle of the objects attached next, and groups already attached keep theirs; Reset puts the center and 0° back. Save keeps the options across tool switches and saves them with the preferences (`tool.setOption {tool: "objectsOnPath"}`). - **Paint and appearance (M3):** - **CSS swatch libraries:** fractional linear and radial gradient stop positions are preserved, so nearby stops such as 12.5% and 12.890625% remain distinct instead of collapsing to 13%. Reference: [CSS Images 3 color stops](https://www.w3.org/TR/css-images-3/#color-stop-syntax). The original synthetic regression is `palette_io::tests::css_preserves_fractional_gradient_stop_positions` in `crates/color/src/palette_io.rs`. Scores and hours are unchanged. - **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate. From 9ba55b3c032885fd9bb3f5f0c968abd6b860d950 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 12:47:03 -0700 Subject: [PATCH 181/260] Objects on Path: the tool's Rotate stays within -360 to 360 tool.setOption kept any finite rotate, while the Objects on Path Tool Options dialog shows Rotate clamped to -360 to 360 and saves the value it was given, so a rotate of 450 showed as 360 and the next attach used 450. The tool now clamps rotate to -360 to 360, and attach clamps the saved rotate it falls back to the same way. --- crates/engine/src/cmd/objects_on_path.rs | 2 +- crates/tools/src/objects_on_path.rs | 12 +++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/objects_on_path.rs b/crates/engine/src/cmd/objects_on_path.rs index 4829d770c4..eebdd3e046 100644 --- a/crates/engine/src/cmd/objects_on_path.rs +++ b/crates/engine/src/cmd/objects_on_path.rs @@ -204,7 +204,7 @@ fn attach(s: &mut Session, p: &Value) -> Result<Value> { // Without them in `p`, the tool's options (Objects on Path Tool Options) give Pivot and Rotate. let saved = s.tool_options_of(TOOL); let tool_pivot = saved.get("pivot").and_then(Value::as_u64).filter(|n| *n <= 8).map_or(CENTER, |n| n as u8); - let tool_rotate = saved.get("rotate").and_then(Value::as_f64).filter(|r| r.is_finite()).unwrap_or(0.0); + let tool_rotate = saved.get("rotate").and_then(Value::as_f64).filter(|r| r.is_finite()).map_or(0.0, |r| r.clamp(-360.0, 360.0)); let (pivot, rotate) = pivot_rotate(p, C, tool_pivot, tool_rotate)?; let roots = match p.get("ids") { Some(_) => roots_of(&s.doc()?.doc, checked_ids_param(s, p, "ids", C)?), diff --git a/crates/tools/src/objects_on_path.rs b/crates/tools/src/objects_on_path.rs index d5be195254..f08dc93139 100644 --- a/crates/tools/src/objects_on_path.rs +++ b/crates/tools/src/objects_on_path.rs @@ -98,8 +98,8 @@ impl Tool for ObjectsOnPathTool { json!({ "pivot": self.pivot, "rotate": self.rotate }) } - /// `pivot` takes a whole number from 0 to 8 and `rotate` a finite number; other values are - /// ignored. + /// `pivot` takes a whole number from 0 to 8 and `rotate` a finite number, clamped to -360 to + /// 360; other values are ignored. fn set_option(&mut self, key: &str, value: &Value) { match key { "pivot" => { @@ -109,7 +109,7 @@ impl Tool for ObjectsOnPathTool { } "rotate" => { if let Some(r) = value.as_f64().filter(|r| r.is_finite()) { - self.rotate = r; + self.rotate = r.clamp(-360.0, 360.0); } } _ => {} @@ -180,6 +180,12 @@ mod tests { t.set_option("pivot", &json!(9)); t.set_option("rotate", &json!("x")); assert_eq!(t.options(), json!({ "pivot": 0, "rotate": 45.5 })); + // Rotate is kept within the dialog's -360 to 360. + t.set_option("rotate", &json!(450)); + assert_eq!(t.options()["rotate"], 360.0); + t.set_option("rotate", &json!(-720.5)); + assert_eq!(t.options()["rotate"], -360.0); + t.set_option("rotate", &json!(45.5)); t.pointer(&cx, &ev(PointerKind::Down, 200.0, 300.0)); let acts = t.pointer(&cx, &ev(PointerKind::Up, 200.0, 300.0)); assert!(matches!(acts.as_slice(), [Action::Exec(_, p)] if p["pivot"] == 0 && p["rotate"] == 45.5), "{acts:?}"); From a6ee76ad353622a48bcb5a17f0480808e3bdf894 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 13:01:53 -0700 Subject: [PATCH 182/260] i18n: French Pivot and Rotate labels put a no-break space before the colon --- crates/ui-egui/src/i18n/fr.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 310996719a..6f42e2d4d7 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1464,8 +1464,8 @@ font-technology Variable Variables Attach Attacher Objects on Path Options Options d’objets sur tracé Objects on Path Tool Outil Objets sur tracé - Pivot: Pivot : - Rotate: Rotation : + Pivot: Pivot : + Rotate: Rotation : Attach Objects on Path Attacher des objets au tracé Expand Objects on Path Décomposer les objets sur tracé Release Live Paint Annuler la peinture dynamique From fa2186656841d5aaee01b4b5d367574884d86982 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 1 Nov 2026 04:53:50 +0700 Subject: [PATCH 183/260] Properties: an Objects on Path group shows Objects on Path Options with Pivot and Rotate Squashed from #4985 onto main. --- crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/panels/properties.rs | 69 +++++++++++++++++ crates/ui-egui/src/panels/properties/tests.rs | 74 +++++++++++++++++++ docs/target-app-parity.md | 1 + 29 files changed, 196 insertions(+) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 7f98dbf009..59f1b30908 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1425,6 +1425,8 @@ font-technology Variable Променливи Objects on Path Обекти по пътя Attach Прикрепяне Objects on Path Options Опции за обекти по пътя + Pivot: Опорна точка: + Rotate: Завъртане: Objects on Path Tool Инструмент „Обекти по пътя“ Pivot: Опорна точка: Rotate: Завъртане: diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 7184e1b278..9229cafa1e 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1609,6 +1609,8 @@ digits Malayalam Malajalam Objects on Path Objekti na putanji Attach Priloži Objects on Path Options Opcije objekata na putanji + Pivot: Tačka oslonca: + Rotate: Rotacija: Objects on Path Tool Alat objekti na putanji Pivot: Tačka okretanja: Rotate: Rotacija: diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 6e05cf66c6..08d2245891 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2639,6 +2639,8 @@ digits Malayalam Malaiàlam Objects Objectes Objects on Path Objectes sobre el traçat Objects on Path Options Opcions dels objectes sobre el traçat + Pivot: Punt de pivot: + Rotate: Rotació: Objects on Path Tool Eina d’objectes sobre el traçat Pivot: Punt de pivot: Rotate: Rotació: diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 07f5c23743..44d15943ed 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1635,6 +1635,8 @@ digits Malayalam Malajálamské Objects on Path Objekty na cestě Attach Připojit Objects on Path Options Možnosti objektů na cestě + Pivot: Otočný bod: + Rotate: Otočení: Objects on Path Tool Nástroj Objekty na cestě Pivot: Otočný bod: Rotate: Otočení: diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index c8919058c1..988a2a2c32 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5395,6 +5395,8 @@ swatch Bright Violet Kraftig violet Objects on Path Objekter på kurve Attach Tilknyt Objects on Path Options Indstillinger for objekter på kurve + Pivot: Omdrejningspunkt: + Rotate: Rotation: Objects on Path Tool Objekter på kurve-værktøj Pivot: Omdrejningspunkt: Rotate: Rotation: diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 6b85051139..7db08925d3 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1459,6 +1459,8 @@ file-filter Templates Vorlagen Objects on Path Objekte auf Pfad Attach Anhängen Objects on Path Options Optionen für Objekte auf Pfad + Pivot: Drehpunkt: + Rotate: Drehung: Objects on Path Tool Objekte-auf-Pfad-Werkzeug Pivot: Drehpunkt: Rotate: Drehung: diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b465d8a657..58bc668b27 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1389,6 +1389,8 @@ font-technology Variable Μεταβλητές Objects on Path Αντικείμενα σε διαδρομή Attach Προσάρτηση Objects on Path Options Επιλογές αντικειμένων σε διαδρομή + Pivot: Σημείο περιστροφής: + Rotate: Περιστροφή: Objects on Path Tool Αντικείμενα σε διαδρομή (Objects on Path Tool) Pivot: Σημείο περιστροφής: Rotate: Περιστροφή: diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 413277af4d..cbf7839c49 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1463,6 +1463,8 @@ font-technology Variable Variables Objects on Path Objetos en trazado Attach Adjuntar Objects on Path Options Opciones de objetos en trazado + Pivot: Pivote: + Rotate: Rotación: Objects on Path Tool Herramienta Objetos en trazado Pivot: Pivote: Rotate: Rotación: diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 3011e59738..84b2dbe9e2 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1608,6 +1608,8 @@ digits Malayalam Malajalam Objects on Path Objektit polulla Attach Kiinnitä Objects on Path Options Objektit polulla -asetukset + Pivot: Kiintopiste: + Rotate: Kierto: Objects on Path Tool Objektit polulla -työkalu Pivot: Kiertopiste: Rotate: Kierto: diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6f42e2d4d7..3624578308 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1463,6 +1463,8 @@ font-technology Variable Variables Objects on Path Objets sur tracé Attach Attacher Objects on Path Options Options d’objets sur tracé + Pivot: Pivot : + Rotate: Rotation : Objects on Path Tool Outil Objets sur tracé Pivot: Pivot : Rotate: Rotation : diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index deef0995f3..3bed2740f7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1860,6 +1860,8 @@ file-filter Templates Sablonok Objects on Path Objektumok útvonalon Attach Csatolás Objects on Path Options Objektumok útvonalon beállításai + Pivot: Forgáspont: + Rotate: Elforgatás: Objects on Path Tool Objektumok útvonalon Pivot: Forgáspont: Rotate: Elforgatás: diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 9aef8450bb..92790c89b7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5395,6 +5395,8 @@ swatch Bright Violet Violet cerah Objects on Path Objek pada jalur Attach Tempelkan Objects on Path Options Opsi objek pada jalur + Pivot: Titik pivot: + Rotate: Rotasi: Objects on Path Tool Alat objek pada jalur Pivot: Titik poros: Rotate: Rotasi: diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 304c48f4ba..2cd2b1d3fa 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1483,6 +1483,8 @@ file-filter Templates Modelli Objects on Path Oggetti su tracciato Attach Aggancia Objects on Path Options Opzioni oggetti su tracciato + Pivot: Perno: + Rotate: Rotazione: Objects on Path Tool Strumento Oggetti su tracciato Pivot: Perno: Rotate: Rotazione: diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4ae7d6fd88..da19a5f6d2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1773,6 +1773,8 @@ digits Malayalam マラヤーラム数字 Objects on Path パス上のオブジェクト Attach アタッチ Objects on Path Options パス上のオブジェクトオプション + Pivot: ピボット: + Rotate: 回転: Objects on Path Tool パス上のオブジェクトツール Pivot: ピボット: Rotate: 回転: diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 261074cff8..9a71c03fac 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5301,6 +5301,8 @@ imageTrace Outline კონტური Objects on Path ობიექტები ტრაექტორიაზე Attach მიმაგრება Objects on Path Options ტრაექტორიაზე ობიექტების პარამეტრები + Pivot: საყრდენი წერტილი: + Rotate: შემობრუნება: Objects on Path Tool ტრაექტორიაზე ობიექტების ხელსაწყო Pivot: საყრდენი წერტილი: Rotate: შემობრუნება: diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 05f3c38602..72ee2e656c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1763,6 +1763,8 @@ digits Malayalam 말라얄람어 Objects on Path 패스 위 개체 Attach 부착 Objects on Path Options 패스 위 개체 옵션 + Pivot: 피벗: + Rotate: 회전: Objects on Path Tool 패스 위 개체 도구 Pivot: 피벗: Rotate: 회전: diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 579a6458e3..050c2cb438 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5406,6 +5406,8 @@ swatch Bright Violet Felviolet Objects on Path Objecten op pad Attach Koppelen Objects on Path Options Opties voor objecten op pad + Pivot: Draaipunt: + Rotate: Rotatie: Objects on Path Tool Objecten-op-pad-gereedschap Pivot: Draaipunt: Rotate: Rotatie: diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 3ec4a22e2c..ee7f18fd2a 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1553,6 +1553,8 @@ digits Malayalam Malajalam Objects on Path Obiekty na ścieżce Attach Dołącz Objects on Path Options Opcje obiektów na ścieżce + Pivot: Punkt obrotu: + Rotate: Obrót: Objects on Path Tool Narzędzie Obiekty na ścieżce Pivot: Punkt obrotu: Rotate: Obrót: diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 01a472f100..43a673e249 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1269,6 +1269,8 @@ Objects on Path Objetos no Caminho Attach Anexar Objects on Path Options Opções de Objetos no Caminho + Pivot: Pivô: + Rotate: Rotação: Objects on Path Tool Ferramenta Objetos no Caminho Pivot: Pivô: Rotate: Rotação: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f54d63b6be..7edf206e7f 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1481,6 +1481,8 @@ file-filter Templates Шаблоны Objects on Path Объекты на контуре Attach Прикрепить Objects on Path Options Параметры объектов на контуре + Pivot: Точка опоры: + Rotate: Поворот: Objects on Path Tool Инструмент «Объекты на контуре» Pivot: Опорная точка: Rotate: Поворот: diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 295726ef6c..477e0c9c2b 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1427,6 +1427,8 @@ font-technology Variable Variabla Objects on Path Objekt på bana Attach Fäst Objects on Path Options Alternativ för objekt på bana + Pivot: Pivotpunkt: + Rotate: Rotation: Objects on Path Tool Verktyg för objekt på bana Pivot: Pivotpunkt: Rotate: Rotation: diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a360aa1fdd..83e2906133 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5374,6 +5374,8 @@ theme Appearance Görünüm Note Paper… Not Kâğıdı… Objects on Path Yol Üzerindeki Nesneler Objects on Path Options Yol Üzerindeki Nesneler Seçenekleri + Pivot: Pivot noktası: + Rotate: Rotasyon: Objects on Path Tool Yol Üzerindeki Nesneler Aracı Pivot: Pivot noktası: Rotate: Döndürme: diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 298eb966c3..ffee17a12f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1477,6 +1477,8 @@ file-filter Templates Шаблони Objects on Path Об’єкти на контурі Attach Прикріпити Objects on Path Options Параметри об’єктів на контурі + Pivot: Точка опори: + Rotate: Поворот: Objects on Path Tool Інструмент «Об’єкти на контурі» Pivot: Опорна точка: Rotate: Поворот: diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4980968699..154f3f866e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1700,6 +1700,8 @@ digits Hindi Hindi Objects on Path Đối tượng trên đường dẫn Attach Gắn Objects on Path Options Tùy chọn đối tượng trên đường dẫn + Pivot: Điểm xoay: + Rotate: Xoay: Objects on Path Tool Công cụ Đối tượng trên đường dẫn Pivot: Điểm trục: Rotate: Xoay: diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 061e6bf07b..fabb541c46 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1411,6 +1411,8 @@ file-filter Templates 模板 Objects on Path 路径上的对象 Attach 附加 Objects on Path Options 路径上的对象选项 + Pivot: 枢轴: + Rotate: 旋转: Objects on Path Tool 路径上的对象工具 Pivot: 枢轴: Rotate: 旋转: diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 79d62390de..b6b48a2ae6 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1448,6 +1448,8 @@ file-filter Templates 範本 Objects on Path 路徑上的物件 Attach 附加 Objects on Path Options 路徑上的物件選項 + Pivot: 樞軸: + Rotate: 旋轉: Objects on Path Tool 路徑上的物件工具 Pivot: 樞軸: Rotate: 旋轉: diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index f6f6724e56..a8f736e5ac 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -65,6 +65,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { trace_section(app, ui, &preset, view); divider(ui); } + if let Some(oop) = selected_objects_on_path(app) { + objects_on_path_section(app, ui, &oop); + divider(ui); + } if matches!(first.as_ref().map(|n| &n.kind), Some(NodeKind::Text(_))) { type_sections(app, ui); divider(ui); @@ -359,6 +363,71 @@ fn trace_section(app: &mut VectorcraftApp, ui: &mut Ui, preset: &str, view: vect }); } +/// The Objects on Path groups selected with nothing else: their ids, and the Pivot and Rotate they +/// share (`None` where they differ). +struct ObjectsOnPathSelection { + ids: Vec<u64>, + pivot: Option<u8>, + rotate: Option<f64>, +} + +/// The selection as Objects on Path groups ([`ObjectsOnPathSelection`]), when every selected +/// object is one. +fn selected_objects_on_path(app: &VectorcraftApp) -> Option<ObjectsOnPathSelection> { + let st = app.session.active()?; + let mut out: Option<ObjectsOnPathSelection> = None; + for id in &st.selection.objects { + let rec = st.doc.node(*id)?.extras().objects_on_path.as_deref()?; + match &mut out { + None => out = Some(ObjectsOnPathSelection { ids: vec![id.0], pivot: Some(rec.pivot), rotate: Some(rec.rotate) }), + Some(s) => { + s.ids.push(id.0); + if s.pivot != Some(rec.pivot) { + s.pivot = None; + } + if s.rotate != Some(rec.rotate) { + s.rotate = None; + } + } + } + } + out +} + +/// The Objects on Path Options of the selected Objects on Path groups: Pivot, the point of each +/// object that attaches to the path, and Rotate, the angle each object tilts by from upright on the +/// path, as the help page places them in the Properties panel +/// (<https://helpx.adobe.com/illustrator/using/objects-on-path.html>). A change goes to every +/// selected group in one undo step (`object.objectsOnPath.options`). Where the groups differ, no +/// Pivot square is chosen and Rotate is blank. +fn objects_on_path_section(app: &mut VectorcraftApp, ui: &mut Ui, oop: &ObjectsOnPathSelection) { + section_header(ui, tl!("Objects on Path Options")); + let fw = super::field_width(ui); + let set = |app: &mut VectorcraftApp, mut p: serde_json::Value| { + p["ids"] = json!(oop.ids); + if let Err(e) = app.run("object.objectsOnPath.options", p) { + app.status(e); + } + }; + egui::Grid::new("props-objects-on-path").num_columns(2).spacing([6.0, 6.0]).show(ui, |ui| { + dim_label(ui, tl!("Pivot:")); + // 9 is no square: the groups' pivots differ. + if let Some(i) = widgets::reference_point(ui, oop.pivot.map_or(9, usize::from)) + && oop.pivot.is_none_or(|p| usize::from(p) != i) + { + set(app, json!({ "pivot": i })); + } + ui.end_row(); + dim_label(ui, tl!("Rotate:")); + if let Some(a) = widgets::spin_plain(ui, "props-oop-rotate", oop.rotate, "°", 2, fw, 15.0, -360.0, &super::transform::ANGLE_PRESETS) + && oop.rotate != Some(a) + { + set(app, json!({ "rotate": a })); + } + ui.end_row(); + }); +} + /// Whether the selection uses more than one colour (`recolor.colors`), which offers the Recolor /// quick action; cached per document revision. fn multi_color(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index c4059b8d58..4dd7d4f223 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1684,3 +1684,77 @@ fn reset_is_a_quick_action_for_a_changed_dynamic_instance() { assert!(app.session.doc().unwrap().doc.node(id).unwrap().extras().symbol_overrides.is_empty()); assert!(!shows(&tall(&mut app, &ctx, vec![]), "Reset")); } + +/// Two 20 pt squares attached to a horizontal line in an Objects on Path group (`rotate` degrees), +/// with the group selected → the group. +fn objects_on_path(app: &mut VectorcraftApp, y: f64, rotate: f64) -> Value { + let line = app.run("shape.line", json!({"x1": 20, "y1": y, "x2": 380, "y2": y})).unwrap()["id"].clone(); + let a = rect(app, 40.0, y - 60.0, 20.0, 20.0); + let b = rect(app, 80.0, y - 60.0, 20.0, 20.0); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let group = app.run("object.objectsOnPath.attach", json!({"path": line, "rotate": rotate})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + group +} + +/// The Pivot and Rotate of the Objects on Path group `id`. +fn pivot_rotate(app: &VectorcraftApp, id: &Value) -> (u8, f64) { + let d = &app.session.active().unwrap().doc; + let rec = d.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().extras().objects_on_path.as_deref().unwrap(); + (rec.pivot, rec.rotate) +} + +/// The Objects on Path Options section alone. +fn objects_on_path_options(app: &mut VectorcraftApp, ui: &mut Ui) { + if let Some(oop) = selected_objects_on_path(app) { + objects_on_path_section(app, ui, &oop); + } +} + +/// The help page's Objects on Path Options section of the Properties panel shows for an Objects on +/// Path group selected on its own or with other such groups, and not for a plain group, an object +/// or an Objects on Path group selected with another object. +#[test] +fn objects_on_path_groups_show_objects_on_path_options() { + let mut app = new_app(); + let ctx = egui::Context::default(); + let group = objects_on_path(&mut app, 150.0, 0.0); + let texts = tall(&mut app, &ctx, vec![]); + assert!(shows(&texts, "Objects on Path Options") && shows(&texts, "Pivot:") && shows(&texts, "Rotate:"), "one group: {texts:?}"); + let other = objects_on_path(&mut app, 250.0, 0.0); + app.run("select.set", json!({"ids": [group, other]})).unwrap(); + assert!(shows(&tall(&mut app, &ctx, vec![]), "Objects on Path Options"), "two groups"); + let r = rect(&mut app, 300.0, 20.0, 40.0, 40.0); + app.run("select.set", json!({"ids": [group, r]})).unwrap(); + assert!(!shows(&tall(&mut app, &ctx, vec![]), "Objects on Path Options"), "a group and a rectangle"); + app.run("select.set", json!({"ids": [r]})).unwrap(); + assert!(!shows(&tall(&mut app, &ctx, vec![]), "Objects on Path Options"), "a rectangle"); + let s = rect(&mut app, 340.0, 20.0, 20.0, 20.0); + app.run("select.set", json!({"ids": [r, s]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + assert!(!shows(&tall(&mut app, &ctx, vec![]), "Objects on Path Options"), "a plain group"); +} + +/// A click on a Pivot square and a typed Rotate each set the selected groups' Objects on Path +/// Options in one undo step: one group's, and two groups' at once, where Rotate starts blank as +/// the groups' angles differ. +#[test] +fn objects_on_path_options_set_pivot_and_rotate_in_one_undo_step() { + let (mut app, ctx) = reference_setup(&[]); + let group = objects_on_path(&mut app, 150.0, 0.0); + let depth = undo_depth(&app); + click_named(&mut app, &ctx, objects_on_path_options, "Top Left"); + assert_eq!(pivot_rotate(&app, &group), (0, 0.0), "Pivot: top left"); + assert_eq!(undo_depth(&app), depth + 1, "one undo step"); + type_over(&mut app, &ctx, objects_on_path_options, "0°", "30"); + assert_eq!(pivot_rotate(&app, &group), (0, 30.0), "Rotate: 30°"); + assert_eq!(undo_depth(&app), depth + 2, "one undo step"); + let other = objects_on_path(&mut app, 250.0, 45.0); + app.run("select.set", json!({"ids": [group, other]})).unwrap(); + let texts = panel_frame(&mut app, &ctx, vec![], objects_on_path_options); + assert!(!shows(&texts, "30°") && !shows(&texts, "45°"), "Rotate is blank: {texts:?}"); + let depth = undo_depth(&app); + click_named(&mut app, &ctx, objects_on_path_options, "Bottom Right"); + assert_eq!((pivot_rotate(&app, &group), pivot_rotate(&app, &other)), ((8, 30.0), (8, 45.0)), "both groups' Pivot"); + assert_eq!(undo_depth(&app), depth + 1, "one undo step for both groups"); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d1d72271c5..89b2ae9463 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -930,6 +930,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When the object the Blend tool picked first is deleted or undone away before the second click, the next click on an object picks that object first instead of doing nothing. Regression tests: `blend_tool_picks_again_when_its_first_pick_is_gone` in `meshblend.rs` and `the_blend_tool_picks_again_when_its_first_pick_is_deleted` in `tests/blendopts.rs`. Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected. With the Blend tool, Escape drops the object clicked first and stops the next click adding to the blend just made, so the next click picks a new first object; the document and the selection stay as they are. Regression tests: `escape_drops_the_blend_tools_first_pick` in `meshblend.rs` and `tests/blendopts.rs`. + Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`), and with Objects on Path groups selected the Properties panel's Objects on Path Options section shows them as a nine-point Pivot grid and a Rotate field with common angles, each change one undo step for every selected group. Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. The Space, Move All, Rotate All and Select/Move widgets, Detach and the tool's options dialog are missing. Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`). Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. The Space, Move All, Rotate All and Select/Move widgets, Detach and the Properties panel section are missing. Double-clicking the Objects on Path tool opens Objects on Path Tool Options ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)): the nine-point Pivot grid and the Rotate field set the attachment point and angle of the objects attached next, and groups already attached keep theirs; Reset puts the center and 0° back. Save keeps the options across tool switches and saves them with the preferences (`tool.setOption {tool: "objectsOnPath"}`). - **Paint and appearance (M3):** From cdc3a03a1ddda2c7b663583356f8afaff2c0916d Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 04:55:09 +0700 Subject: [PATCH 184/260] Objects on Path: one catalog row each for Pivot and Rotate, one Objects on Path parity entry --- crates/ui-egui/src/i18n/bg.tsv | 2 -- crates/ui-egui/src/i18n/bs.tsv | 2 -- crates/ui-egui/src/i18n/ca.tsv | 2 -- crates/ui-egui/src/i18n/cs.tsv | 2 -- crates/ui-egui/src/i18n/da.tsv | 2 -- crates/ui-egui/src/i18n/de.tsv | 2 -- crates/ui-egui/src/i18n/el.tsv | 2 -- crates/ui-egui/src/i18n/es.tsv | 2 -- crates/ui-egui/src/i18n/fi.tsv | 2 -- crates/ui-egui/src/i18n/fr.tsv | 2 -- crates/ui-egui/src/i18n/hu.tsv | 2 -- crates/ui-egui/src/i18n/id.tsv | 2 -- crates/ui-egui/src/i18n/it.tsv | 2 -- crates/ui-egui/src/i18n/ja.tsv | 2 -- crates/ui-egui/src/i18n/ka.tsv | 2 -- crates/ui-egui/src/i18n/ko.tsv | 2 -- crates/ui-egui/src/i18n/nl.tsv | 2 -- crates/ui-egui/src/i18n/pl.tsv | 2 -- crates/ui-egui/src/i18n/pt-br.tsv | 2 -- crates/ui-egui/src/i18n/ru.tsv | 2 -- crates/ui-egui/src/i18n/sv.tsv | 2 -- crates/ui-egui/src/i18n/tr.tsv | 2 -- crates/ui-egui/src/i18n/uk.tsv | 2 -- crates/ui-egui/src/i18n/vi.tsv | 2 -- crates/ui-egui/src/i18n/zh-hans.tsv | 2 -- crates/ui-egui/src/i18n/zh-hant.tsv | 2 -- docs/target-app-parity.md | 3 +-- 27 files changed, 1 insertion(+), 54 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 59f1b30908..96df01e214 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1428,8 +1428,6 @@ font-technology Variable Променливи Pivot: Опорна точка: Rotate: Завъртане: Objects on Path Tool Инструмент „Обекти по пътя“ - Pivot: Опорна точка: - Rotate: Завъртане: Attach Objects on Path Прикрепяне на обекти към пътя Expand Objects on Path Разширяване на обекти по пътя Release Live Paint Освобождаване на динамично оцветяване diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9229cafa1e..2d3acc7d3d 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1612,8 +1612,6 @@ digits Malayalam Malajalam Pivot: Tačka oslonca: Rotate: Rotacija: Objects on Path Tool Alat objekti na putanji - Pivot: Tačka okretanja: - Rotate: Rotacija: Attach Objects on Path Priloži objekte na putanju Expand Objects on Path Proširi objekte na putanji Release Live Paint Oslobodi živo bojenje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 08d2245891..f9648d21a9 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2642,8 +2642,6 @@ digits Malayalam Malaiàlam Pivot: Punt de pivot: Rotate: Rotació: Objects on Path Tool Eina d’objectes sobre el traçat - Pivot: Punt de pivot: - Rotate: Rotació: Objects using them keep their look but are no longer linked. Els objectes que les utilitzen conserven l’aspecte, però ja no estan enllaçats. Ocean Ripple Onada oceànica Ocean Ripple… Onada oceànica… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 44d15943ed..e5a6bc1da2 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1638,8 +1638,6 @@ digits Malayalam Malajálamské Pivot: Otočný bod: Rotate: Otočení: Objects on Path Tool Nástroj Objekty na cestě - Pivot: Otočný bod: - Rotate: Otočení: Attach Objects on Path Připojit objekty na cestu Expand Objects on Path Rozložit objekty na cestě Release Live Paint Uvolnit živou malbu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 988a2a2c32..e6c0987edc 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5398,8 +5398,6 @@ swatch Bright Violet Kraftig violet Pivot: Omdrejningspunkt: Rotate: Rotation: Objects on Path Tool Objekter på kurve-værktøj - Pivot: Omdrejningspunkt: - Rotate: Rotation: Attach Objects on Path Tilknyt objekter til kurve Expand Objects on Path Udvid objekter på kurve Release Live Paint Frigør live-maling diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7db08925d3..8abc9ca13a 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1462,8 +1462,6 @@ file-filter Templates Vorlagen Pivot: Drehpunkt: Rotate: Drehung: Objects on Path Tool Objekte-auf-Pfad-Werkzeug - Pivot: Drehpunkt: - Rotate: Drehung: Attach Objects on Path Objekte an Pfad anhängen Expand Objects on Path Objekte auf Pfad umwandeln Release Live Paint „Interaktiv malen“ zurückwandeln diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 58bc668b27..f8be1cf381 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1392,8 +1392,6 @@ font-technology Variable Μεταβλητές Pivot: Σημείο περιστροφής: Rotate: Περιστροφή: Objects on Path Tool Αντικείμενα σε διαδρομή (Objects on Path Tool) - Pivot: Σημείο περιστροφής: - Rotate: Περιστροφή: Attach Objects on Path Προσάρτηση αντικειμένων σε διαδρομή Expand Objects on Path Επέκταση αντικειμένων σε διαδρομή Release Live Paint Αποδέσμευση δυναμικής βαφής diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index cbf7839c49..a73a9155a4 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1466,8 +1466,6 @@ font-technology Variable Variables Pivot: Pivote: Rotate: Rotación: Objects on Path Tool Herramienta Objetos en trazado - Pivot: Pivote: - Rotate: Rotación: Attach Objects on Path Adjuntar objetos al trazado Expand Objects on Path Expandir objetos en trazado Release Live Paint Soltar pintura interactiva diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 84b2dbe9e2..ba97335bf9 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1611,8 +1611,6 @@ digits Malayalam Malajalam Pivot: Kiintopiste: Rotate: Kierto: Objects on Path Tool Objektit polulla -työkalu - Pivot: Kiertopiste: - Rotate: Kierto: Attach Objects on Path Kiinnitä objektit polulle Expand Objects on Path Laajenna objektit polulla Release Live Paint Vapauta elävä maalaus diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3624578308..c3892ba3d5 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1466,8 +1466,6 @@ font-technology Variable Variables Pivot: Pivot : Rotate: Rotation : Objects on Path Tool Outil Objets sur tracé - Pivot: Pivot : - Rotate: Rotation : Attach Objects on Path Attacher des objets au tracé Expand Objects on Path Décomposer les objets sur tracé Release Live Paint Annuler la peinture dynamique diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 3bed2740f7..e701b93aaf 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1863,8 +1863,6 @@ file-filter Templates Sablonok Pivot: Forgáspont: Rotate: Elforgatás: Objects on Path Tool Objektumok útvonalon - Pivot: Forgáspont: - Rotate: Elforgatás: Attach Objects on Path Objektumok csatolása útvonalhoz Expand Objects on Path Objektumok útvonalon kibontása Release Live Paint Élő festés megszüntetése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 92790c89b7..493618378d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5398,8 +5398,6 @@ swatch Bright Violet Violet cerah Pivot: Titik pivot: Rotate: Rotasi: Objects on Path Tool Alat objek pada jalur - Pivot: Titik poros: - Rotate: Rotasi: Attach Objects on Path Tempelkan objek pada jalur Expand Objects on Path Perluas objek pada jalur Release Live Paint Lepaskan Live Paint diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 2cd2b1d3fa..9d8d581fad 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1486,8 +1486,6 @@ file-filter Templates Modelli Pivot: Perno: Rotate: Rotazione: Objects on Path Tool Strumento Oggetti su tracciato - Pivot: Perno: - Rotate: Rotazione: Attach Objects on Path Aggancia oggetti al tracciato Expand Objects on Path Espandi oggetti su tracciato Release Live Paint Rilascia pittura dinamica diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index da19a5f6d2..b8f6cdd5aa 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1776,8 +1776,6 @@ digits Malayalam マラヤーラム数字 Pivot: ピボット: Rotate: 回転: Objects on Path Tool パス上のオブジェクトツール - Pivot: ピボット: - Rotate: 回転: Attach Objects on Path パス上のオブジェクトをアタッチ Expand Objects on Path パス上のオブジェクトを拡張 Release Live Paint ライブペイントを解除 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9a71c03fac..d5046acac3 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5304,8 +5304,6 @@ imageTrace Outline კონტური Pivot: საყრდენი წერტილი: Rotate: შემობრუნება: Objects on Path Tool ტრაექტორიაზე ობიექტების ხელსაწყო - Pivot: საყრდენი წერტილი: - Rotate: შემობრუნება: Attach Objects on Path ობიექტების ტრაექტორიაზე მიმაგრება Expand Objects on Path ტრაექტორიაზე ობიექტების გაშლა Release Live Paint ცოცხალი შეღებვის მოხსნა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 72ee2e656c..8c8d194c93 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1766,8 +1766,6 @@ digits Malayalam 말라얄람어 Pivot: 피벗: Rotate: 회전: Objects on Path Tool 패스 위 개체 도구 - Pivot: 피벗: - Rotate: 회전: Attach Objects on Path 패스 위 개체 부착 Expand Objects on Path 패스 위 개체 확장 Release Live Paint 라이브 페인트 해제 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 050c2cb438..b2b799c9a8 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5409,8 +5409,6 @@ swatch Bright Violet Felviolet Pivot: Draaipunt: Rotate: Rotatie: Objects on Path Tool Objecten-op-pad-gereedschap - Pivot: Draaipunt: - Rotate: Rotatie: Attach Objects on Path Objecten aan pad koppelen Expand Objects on Path Objecten op pad uitbreiden Release Live Paint Live Paint vrijgeven diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index ee7f18fd2a..79d3ca69f7 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1556,8 +1556,6 @@ digits Malayalam Malajalam Pivot: Punkt obrotu: Rotate: Obrót: Objects on Path Tool Narzędzie Obiekty na ścieżce - Pivot: Punkt obrotu: - Rotate: Obrót: Attach Objects on Path Dołącz obiekty do ścieżki Expand Objects on Path Rozszerz obiekty na ścieżce Release Live Paint Uwolnij aktywne malowanie diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 43a673e249..c4d69d0187 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1272,8 +1272,6 @@ Pivot: Pivô: Rotate: Rotação: Objects on Path Tool Ferramenta Objetos no Caminho - Pivot: Pivô: - Rotate: Rotação: Attach Objects on Path Anexar Objetos ao Caminho Expand Objects on Path Expandir Objetos no Caminho Release Live Paint Liberar Pintura ao Vivo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 7edf206e7f..3f328f94d0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1484,8 +1484,6 @@ file-filter Templates Шаблоны Pivot: Точка опоры: Rotate: Поворот: Objects on Path Tool Инструмент «Объекты на контуре» - Pivot: Опорная точка: - Rotate: Поворот: Attach Objects on Path Прикрепить объекты к контуру Expand Objects on Path Разобрать объекты на контуре Release Live Paint Освободить быструю заливку diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 477e0c9c2b..eee2ef8859 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1430,8 +1430,6 @@ font-technology Variable Variabla Pivot: Pivotpunkt: Rotate: Rotation: Objects on Path Tool Verktyg för objekt på bana - Pivot: Pivotpunkt: - Rotate: Rotation: Attach Objects on Path Fäst objekt på bana Expand Objects on Path Expandera objekt på bana Release Live Paint Släpp direktmålning diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 83e2906133..324ab77e06 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5377,8 +5377,6 @@ theme Appearance Görünüm Pivot: Pivot noktası: Rotate: Rotasyon: Objects on Path Tool Yol Üzerindeki Nesneler Aracı - Pivot: Pivot noktası: - Rotate: Döndürme: Photocopy Fotokopi Photocopy… Fotokopi… Plaster Alçı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index ffee17a12f..6ada758d86 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1480,8 +1480,6 @@ file-filter Templates Шаблони Pivot: Точка опори: Rotate: Поворот: Objects on Path Tool Інструмент «Об’єкти на контурі» - Pivot: Опорна точка: - Rotate: Поворот: Attach Objects on Path Прикріпити об’єкти до контуру Expand Objects on Path Розібрати об’єкти на контурі Release Live Paint Звільнити швидку заливку diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 154f3f866e..1aa0e91c69 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1703,8 +1703,6 @@ digits Hindi Hindi Pivot: Điểm xoay: Rotate: Xoay: Objects on Path Tool Công cụ Đối tượng trên đường dẫn - Pivot: Điểm trục: - Rotate: Xoay: Attach Objects on Path Gắn đối tượng lên đường dẫn Expand Objects on Path Mở rộng đối tượng trên đường dẫn Release Live Paint Giải phóng tô trực tiếp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index fabb541c46..f0e7b021ca 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1414,8 +1414,6 @@ file-filter Templates 模板 Pivot: 枢轴: Rotate: 旋转: Objects on Path Tool 路径上的对象工具 - Pivot: 枢轴: - Rotate: 旋转: Attach Objects on Path 附加路径上的对象 Expand Objects on Path 扩展路径上的对象 Release Live Paint 释放实时上色 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b6b48a2ae6..d6b7bc23e7 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1451,8 +1451,6 @@ file-filter Templates 範本 Pivot: 樞軸: Rotate: 旋轉: Objects on Path Tool 路徑上的物件工具 - Pivot: 樞軸: - Rotate: 旋轉: Attach Objects on Path 附加路徑上的物件 Expand Objects on Path 展開路徑上的物件 Release Live Paint 釋放即時上色 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 89b2ae9463..4a17438055 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -930,8 +930,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When the object the Blend tool picked first is deleted or undone away before the second click, the next click on an object picks that object first instead of doing nothing. Regression tests: `blend_tool_picks_again_when_its_first_pick_is_gone` in `meshblend.rs` and `the_blend_tool_picks_again_when_its_first_pick_is_deleted` in `tests/blendopts.rs`. Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected. With the Blend tool, Escape drops the object clicked first and stops the next click adding to the blend just made, so the next click picks a new first object; the document and the selection stay as they are. Regression tests: `escape_drops_the_blend_tools_first_pick` in `meshblend.rs` and `tests/blendopts.rs`. - Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`), and with Objects on Path groups selected the Properties panel's Objects on Path Options section shows them as a nine-point Pivot grid and a Rotate field with common angles, each change one undo step for every selected group. Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. The Space, Move All, Rotate All and Select/Move widgets, Detach and the tool's options dialog are missing. - Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`). Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. The Space, Move All, Rotate All and Select/Move widgets, Detach and the Properties panel section are missing. + Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`), and with Objects on Path groups selected the Properties panel's Objects on Path Options section shows them as a nine-point Pivot grid and a Rotate field with common angles, each change one undo step for every selected group. Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. The Space, Move All, Rotate All and Select/Move widgets and Detach are missing. Double-clicking the Objects on Path tool opens Objects on Path Tool Options ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)): the nine-point Pivot grid and the Rotate field set the attachment point and angle of the objects attached next, and groups already attached keep theirs; Reset puts the center and 0° back. Save keeps the options across tool switches and saves them with the preferences (`tool.setOption {tool: "objectsOnPath"}`). - **Paint and appearance (M3):** - **CSS swatch libraries:** fractional linear and radial gradient stop positions are preserved, so nearby stops such as 12.5% and 12.890625% remain distinct instead of collapsing to 13%. Reference: [CSS Images 3 color stops](https://www.w3.org/TR/css-images-3/#color-stop-syntax). The original synthetic regression is `palette_io::tests::css_preserves_fractional_gradient_stop_positions` in `crates/color/src/palette_io.rs`. Scores and hours are unchanged. From dc6440d5238aa02cdfe536669c0891eb8b04261b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 13:02:13 -0700 Subject: [PATCH 185/260] Fix #2960: Recolor Artwork keeps its Preserve checkboxes between uses Recolor Artwork opened with Preserve White and Black on and Grays off every time, so clearing them had to be repeated on each use. OK on art now keeps the three checkboxes in the UI state (recolor_preserve, saved with the other remembered dialog fields), and the dialog opens with them. Cancel leaves them as the last OK set them. --- crates/ui-egui/src/dialogs/recolor.rs | 18 ++++++++++++++---- crates/ui-egui/src/state.rs | 5 +++++ crates/ui-egui/src/tests/recolor.rs | 21 +++++++++++++++++++++ 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 6050af15a3..bdd5094095 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -2,8 +2,9 @@ //! previewed live (engine: `recolor.reduce`, `recolor.randomize`, `recolor.apply`). //! //! Assign tab: Colors (Auto, or a count: similar colours merge into rows), Preserve White, Black and -//! Grays, the rows (click to select, Shift or Cmd/Ctrl-click to add; a row's arrow excludes or -//! includes it; the hex field edits its new colour, and a double-click on it opens the Color Picker, +//! Grays (they open as OK on art last left them), the rows (click to select, Shift or Cmd/Ctrl-click +//! to add; a row's arrow excludes or includes it; the hex field edits its new colour, and a +//! double-click on it opens the Color Picker, //! whose OK sets it in the model it was picked in), Merge and Separate, Randomize order or //! saturation and brightness, Reset, the Method and Limit to Library (its folder button imports a //! library file and limits to it; a library's colours apply as its swatches: a spot colour stays a @@ -100,9 +101,12 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { }; // Without art the rows are the group's colours, as they are. let start: Vec<Value> = if art { vec![] } else { assign.iter().map(|k| json!({"from": [k], "to": k})).collect() }; + // The Preserve checkboxes as they were last confirmed (#2960). + let kept = |k: &str, default: bool| app.ui.recolor_preserve.get(k).and_then(Value::as_bool).unwrap_or(default); let fields = json!({ "rows": start, "colors": count, "method": Method::ScaleTints.id(), - "preserveWhite": true, "preserveBlack": true, "preserveGrays": false, "limitTo": limit, + "preserveWhite": kept("preserveWhite", true), "preserveBlack": kept("preserveBlack", true), + "preserveGrays": kept("preserveGrays", false), "limitTo": limit, "group": group, "groupName": if new_group { Some(NEW_GROUP) } else { group }, "tab": "assign", "rule": Harmony::Complementary.id(), "linked": true, "preview": true, "__art": art, "__assign": assign, "__newGroup": new_group, }); @@ -277,7 +281,13 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { let colors: Vec<Value> = rows(&d).into_iter().filter(|r| !excluded(r)).map(|r| r["to"].clone()).collect(); return form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true})); } - form::commit_preview(app, CMD, apply_params(&d)) + let r = form::commit_preview(app, CMD, apply_params(&d))?; + // The Preserve checkboxes (shown with art) open as confirmed here next time (#2960). + if d.bool("__art") { + app.ui.recolor_preserve = + json!({"preserveWhite": d.bool("preserveWhite"), "preserveBlack": d.bool("preserveBlack"), "preserveGrays": d.bool("preserveGrays")}); + } + Ok(r) } /// The preset the fields match: an n-colour job (n rows, Scale Tints), a library, or Custom. diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 2b5c9c379c..63a4f03901 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -563,6 +563,10 @@ pub struct UiState { /// The Average & Join fields confirmed last (`to`; null: never used): its dialog opens on them. #[serde(default)] pub average_join: Value, + /// The Recolor Artwork Preserve checkboxes confirmed last (`preserveWhite`, `preserveBlack`, + /// `preserveGrays`; null: never used): its dialog opens with them (#2960). + #[serde(default)] + pub recolor_preserve: Value, /// The Simplify dialog's fields confirmed last with "Open this dialog with these settings next /// time" ticked (null: not ticked): Object › Path › Simplify opens the dialog on them instead /// of the Simplify slider. @@ -904,6 +908,7 @@ impl Default for UiState { eps_options: Value::Null, offset_path: Value::Null, average_join: Value::Null, + recolor_preserve: Value::Null, simplify: Value::Null, move_options: Value::Null, transform_each: Value::Null, diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 8d38d8d2f7..1abefd25c1 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -238,6 +238,27 @@ fn each_recolor_hex_field_has_its_row_number() { assert!(h.query_by_role_and_label(egui::accesskit::Role::TextInput, "Color").is_none(), "no ambiguous Color field"); } +/// #2960: the Preserve checkboxes open as OK last left them; Cancel keeps what OK left. +#[test] +fn the_preserve_checkboxes_open_as_they_were_last_confirmed() { + let mut app = app(); + art(&mut app, &["#ff0000", "#ffffff", "#000000", "#808080"]); + let preserve = |app: &VectorcraftApp| ["preserveWhite", "preserveBlack", "preserveGrays"].map(|k| field(app, k)); + app.run("ui.recolorDialog", json!({})).unwrap(); + assert_eq!(preserve(&app), [json!(true), json!(true), json!(false)], "a first open"); + set(&mut app, "preserveWhite", json!(false)); + set(&mut app, "preserveBlack", json!(false)); + set(&mut app, "preserveGrays", json!(true)); + dialogs::confirm(&mut app).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("ui.recolorDialog", json!({})).unwrap(); + assert_eq!(preserve(&app), [json!(false), json!(false), json!(true)], "as confirmed"); + set(&mut app, "preserveWhite", json!(true)); + dialogs::cancel(&mut app); + app.run("ui.recolorDialog", json!({})).unwrap(); + assert_eq!(preserve(&app), [json!(false), json!(false), json!(true)], "Cancel keeps what OK left"); +} + /// The rect of the widget drawn `size` big (the wheel is 220 across, its Brightness slider 220 by 22). fn widget_of_size(h: &egui_kittest::Harness<'_, VectorcraftApp>, size: egui::Vec2) -> Rect { h.ctx From 7211dc789ff4aad3908cae1cdaa38154ab50f3c3 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 1 Nov 2026 04:54:28 +0700 Subject: [PATCH 186/260] Eyedropper: color samples match the canvas and stay within their work limit Squashed from #4979 onto main. --- crates/tools/src/xform/eyedropper.rs | 341 +++++++++++++++++++++++++-- 1 file changed, 315 insertions(+), 26 deletions(-) diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 46b66599b9..f2f2149358 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -54,15 +54,25 @@ pub fn paint_color_at(paint: &Paint, bounds: Option<vectorcraft_geom::Rect>, p: } /// How many patterns and symbols deep a sample follows art inside art (tile art painted with a -/// pattern, a symbol whose art holds an instance of another). +/// pattern, a symbol whose art holds an instance of another). Art nested deeper gives no color. const MAX_NESTING: usize = 16; -/// Most tiles of one pattern a sample looks at, front to back, for art that paints the point. +/// How many patterns deep the canvas draws tile art painted with a pattern. A pattern nested +/// deeper, like a pattern the document lacks, draws (and samples) as [`MISSING_PATTERN`]. +const PATTERN_DEPTH: usize = 3; + +/// The gray the canvas fills a pattern with when it does not draw its tiles. +const MISSING_PATTERN: [u8; 3] = [128, 128, 128]; + +/// Most tiles of one pattern a sample looks at, front to back, for art that paints the point. When +/// more tiles reach the point, the sample gives no color. const MAX_TILES: usize = 1_000; -/// Most work one sample does, in objects looked at: each hit test after the first in a document -/// counts the objects of the document and of its symbols, each pattern tile or symbol instance -/// sampled counts the objects of its art, and every hundred tile positions checked count one. +/// Most work one sample does, in objects looked at: each hit test after the first in the sampled +/// document, and each one in the art of a tile or instance, counts the objects of the document it +/// tests and of the symbols, each pattern tile or symbol instance +/// sampled counts the objects of its art, and every hundred tile positions checked, or points of a +/// mesh's patches looked at, count one. /// Art inside art multiplies them; a sample that would need more gives no color. const MAX_WORK: usize = 1_000_000; @@ -76,6 +86,8 @@ struct Sampler<'a> { work: usize, /// The work ran out: the sample gives no color. exhausted: bool, + /// How many patterns the art being sampled is inside. + patterns: usize, } impl Sampler<'_> { @@ -113,7 +125,7 @@ pub(crate) fn sample_color_at(cx: &ToolContext, p: Point) -> Option<Color> { let (doc, opts, raster_sample) = (cx.doc, sample_options(cx), cx.raster_sample); vectorcraft_doc::depth::with_deep_stack(|| { let symbol_nodes = doc.symbols.iter().map(|s| s.art.count()).sum(); - let mut s = Sampler { doc, opts, raster_sample, symbol_nodes, work: MAX_WORK, exhausted: false }; + let mut s = Sampler { doc, opts, raster_sample, symbol_nodes, work: MAX_WORK, exhausted: false, patterns: 0 }; let mut levels: Vec<Option<Document>> = (0..MAX_NESTING).map(|_| None).collect(); let c = color_under(&mut s, doc, &mut levels, p, opts); c.filter(|_| !s.exhausted) @@ -128,10 +140,14 @@ fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option<Document>], let mut passed: HashSet<NodeId> = HashSet::new(); let mut size = None; loop { - // The first hit test is the one a click makes anyway; each one after it may visit every - // object again. - let cost = - if passed.is_empty() { 1 } else { *size.get_or_insert_with(|| s.symbol_nodes + doc.layers.iter().map(|l| l.count()).sum::<usize>()) }; + // The first hit test in the sampled document is the one a click makes anyway; each one + // after it, and every one in the art of a tile or instance, may visit every object again + // and measure the symbols' art. + let cost = if passed.is_empty() && std::ptr::eq(doc, s.doc) { + 1 + } else { + *size.get_or_insert_with(|| s.symbol_nodes + doc.layers.iter().map(|l| l.count()).sum::<usize>()) + }; s.spend(cost)?; let h = hit_test_visible_skipping(doc, p, opts, &|id| passed.contains(&id))?; let id = paint_owner(doc, h.leaf); @@ -168,6 +184,8 @@ fn node_color_at(s: &mut Sampler, levels: &mut [Option<Document>], n: &Node, on_ match &n.kind { NodeKind::Image(_) => image_color_at(s, n, p), NodeKind::Mesh(m) => { + // Finding the patch point looks at 17 × 17 points of every patch: a hundred count as one unit. + s.spend((m.rows as usize).saturating_mul(m.cols as usize).saturating_mul(17 * 17) / 100)?; let (r, c, u, v) = m.locate(p)?; Some(m.color_at(r, c, u, v).0) } @@ -201,7 +219,39 @@ pub(crate) fn has_sampleable_paint(cx: &ToolContext, id: vectorcraft_doc::NodeId /// of its tile art at `p` ([`pattern_color_at`]). fn paint_sample(s: &mut Sampler, levels: &mut [Option<Document>], n: &Node, on_stroke: bool, p: Point) -> Option<Color> { let fill_none = n.proxy_paint(false, None).is_none_or(|(p, ..)| p.is_none()); - let (paint, to_doc, bounds) = n.proxy_paint(on_stroke || fill_none, None)?; + let stroke = on_stroke || fill_none; + // Type takes its paint from its characters, and a colorized object from its colorize paint. + let items: Vec<usize> = n.appearance.items.iter().enumerate().filter(|(_, it)| it.is_fill() != stroke).map(|(i, _)| i).collect(); + if items.is_empty() || matches!(n.kind, NodeKind::Text(_)) || (!stroke && n.extras().colorize.is_some()) { + let (paint, to_doc, bounds) = n.proxy_paint(stroke, None)?; + return paint_color(s, levels, paint, to_doc, bounds, p); + } + // The visible fills (or strokes) from the top: where one leaves a gap, the next shows. Of a + // path's strokes, only the ones that reach `p` count, when any does (a click within the hit + // tolerance of a stroke may reach none). + let mut visible: Vec<usize> = items.into_iter().filter(|&i| n.appearance.items.get(i).is_some_and(|it| it.visible())).collect(); + if stroke && let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }, Some(bp)) = (&n.kind, n.stroke_path()) { + let reach = + |i: &usize| matches!(n.appearance.items.get(*i), Some(vectorcraft_doc::AppearanceItem::Stroke(st)) if st.hits(&bp, *rule, p, 0.0)); + if visible.iter().any(&reach) { + visible.retain(&reach); + } + } + for &i in visible.iter().rev() { + let Some((paint, to_doc, bounds)) = n.proxy_paint(stroke, Some(i)) else { continue }; + if let Some(c) = paint_color(s, levels, paint, to_doc, bounds, p) { + return Some(c); + } + } + None +} + +/// The color `paint`, in a space `to_doc` places in the document and with box `bounds` there, +/// shows at `p`. A pattern gives the color of its tile art at `p` ([`pattern_color_at`]). +fn paint_color(s: &mut Sampler, levels: &mut [Option<Document>], paint: &Paint, to_doc: Affine, bounds: Rect, p: Point) -> Option<Color> { + if paint.is_none() { + return None; + } if let Paint::Pattern { pattern, xf } = paint { return pattern_color_at(s, levels, pattern, to_doc * *xf, p); } @@ -210,13 +260,30 @@ fn paint_sample(s: &mut Sampler, levels: &mut [Option<Document>], n: &Node, on_s } /// The color pattern `name`, placed in the document by `xf`, shows at `p`: the color of the -/// front-most tile art there. A point the tiles leave empty has no color. +/// front-most tile art there. A point the tiles leave empty has no color. A pattern the document +/// lacks, or one more than [`PATTERN_DEPTH`] patterns deep, shows [`MISSING_PATTERN`]. fn pattern_color_at(s: &mut Sampler, levels: &mut [Option<Document>], name: &str, xf: Affine, p: Point) -> Option<Color> { if xf.determinant().abs() < 1e-12 { return None; } + let [r, g, b] = MISSING_PATTERN; + let doc = s.doc; + let Some(def) = doc.patterns.iter().find(|d| d.name == name) else { return Some(Color::rgb8(r, g, b)) }; + if def.art.is_empty() { + return None; + } + if s.patterns >= PATTERN_DEPTH { + return Some(Color::rgb8(r, g, b)); + } + s.patterns += 1; + let c = tiles_color_at(s, levels, def, xf, p); + s.patterns -= 1; + c +} + +/// The color the front-most tile art of pattern `def`, placed in the document by `xf`, shows at `p`. +fn tiles_color_at(s: &mut Sampler, levels: &mut [Option<Document>], def: &vectorcraft_doc::PatternDef, xf: Affine, p: Point) -> Option<Color> { let doc = s.doc; - let def = doc.patterns.iter().find(|d| d.name == name)?; // Sampled in pattern space, one tile at a time from the front, among the tiles whose art reaches // the point (or meets it at an edge). The art moves by whole tiles, and the patterns it is // painted with move with it. @@ -235,10 +302,25 @@ fn pattern_color_at(s: &mut Sampler, levels: &mut [Option<Document>], name: &str let bounds: Vec<Option<Rect>> = def.art.iter().map(|a| a.visual_bounds_with(&symbols)).collect(); let reaches = |m: Affine| bounds.iter().any(|b| b.is_none_or(|b| m.transform_rect_bbox(b).inflate(1e-6, 1e-6).contains(q))); let scaling = vectorcraft_doc::Scaling { patterns: true, ..Default::default() }; + // The tiles are listed as the canvas lists the ones it draws: by the art's bounds without its + // symbols. Listing them looks at every tile position near the point widened by those bounds (at + // most 250,000, past which it lists none): a hundred positions count as one unit, counted first. + let listed = def.art_bounds().unwrap_or(def.tile).union(def.tile); + let (w, h) = (def.width(), def.height()); + let (sx, sy) = def.tile_type.steps(w, h); + let positions = ((near.width() + listed.width() + 2.0 * w) / sx + 3.0) * ((near.height() + listed.height() + 2.0 * h) / sy + 3.0); + if positions.is_finite() && positions > 0.0 { + s.spend(positions.min(250_000.0) as usize / 100)?; + } let offsets = def.offsets_covering(near); // Each tile position is checked against each piece of art: a hundred checks count as one unit. s.spend(offsets.len().saturating_mul(bounds.len().max(1)) / 100)?; - for m in offsets.into_iter().rev().map(|o| def.instance_xf(o)).filter(|m| reaches(*m)).take(MAX_TILES) { + for (k, m) in offsets.into_iter().rev().map(|o| def.instance_xf(o)).filter(|m| reaches(*m)).enumerate() { + // A tile past the limit may paint the point: the sample gives no color. + if k == MAX_TILES { + s.exhausted = true; + return None; + } s.spend(1 + art_nodes)?; let art = def.art.iter().map(|a| { let mut n = (**a).clone(); @@ -256,9 +338,12 @@ fn pattern_color_at(s: &mut Sampler, levels: &mut [Option<Document>], name: &str /// as [`node_color_at`] samples an object, with no tolerance around outlines and strokes: only /// what it paints at `p` counts. The art is hit in the first of `levels`, a scratch document with /// the sampled document's symbols, made on first use and emptied for each new piece of art; art -/// inside it uses the levels after it. With no level left, the art gives no color. +/// inside it uses the levels after it. With no level left, the whole sample gives no color. fn art_color_at(s: &mut Sampler, levels: &mut [Option<Document>], art: impl IntoIterator<Item = Node>, p: Point) -> Option<Color> { - let (slot, deeper) = levels.split_first_mut()?; + let Some((slot, deeper)) = levels.split_first_mut() else { + s.exhausted = true; + return None; + }; let doc = s.doc; let scratch = slot.get_or_insert_with(|| { let mut d = Document::new(1.0, 1.0); @@ -755,6 +840,103 @@ mod tests { assert_eq!(at(&d, 150.0, 155.0), "#00ff00"); } + /// A pattern nested more than three patterns deep, and a pattern the document lacks, sample as + /// the gray the canvas draws them with. + #[test] + fn deep_and_missing_patterns_sample_as_the_canvas_draws_them() { + use vectorcraft_doc::pattern::pattern_paint; + use vectorcraft_geom::Rect; + let (mut d, id) = doc_with_rect(); + // "P0" to "P2": a 10 pt tile filled with the next; "P3" a green tile. + for i in 0..4 { + let fill = if i == 3 { Paint::solid(Color::rgb(0.0, 1.0, 0.0)) } else { pattern_paint(&format!("P{}", i + 1)) }; + let mut def = vectorcraft_doc::PatternDef::new(&format!("P{i}"), vec![filled_rect(Rect::new(0.0, 0.0, 10.0, 10.0), fill)]); + def.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + d.patterns.push(def); + } + let (s, p) = (Selection::default(), paint()); + let mut at = |name: &str| { + d.node_mut(id).unwrap().appearance.set_fill(pattern_paint(name)); + sample_color_at(&cx(&d, &s, &p), Point::new(150.5, 150.5)).map(|c| c.to_hex()) + }; + assert_eq!(at("P1").as_deref(), Some("#00ff00"), "three patterns deep"); + assert_eq!(at("P0").as_deref(), Some("#808080"), "four patterns deep"); + assert_eq!(at("Nope").as_deref(), Some("#808080"), "missing"); + } + + /// Art nested deeper than a sample follows gives no color, rather than the color of what lies + /// below it. + #[test] + fn art_nested_past_the_limit_gives_no_color() { + use std::sync::Arc; + use vectorcraft_doc::{NodeId, Symbol}; + use vectorcraft_geom::{Affine, Rect}; + let (mut d, _) = doc_with_rect(); + // "Deep0" to "Deep19": one instance of the next; "Deep20" a green square over the white + // rectangle. + for i in 0..20 { + let next = Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: format!("Deep{}", i + 1), xf: Affine::IDENTITY })); + d.symbols.push(Symbol { dynamic: false, name: format!("Deep{i}"), art: next }); + } + d.symbols.push(Symbol { + dynamic: false, + name: "Deep20".into(), + art: filled_rect(Rect::new(100.0, 100.0, 200.0, 200.0), Paint::solid(Color::rgb(0.0, 1.0, 0.0))), + }); + let (l, inst) = (d.layers[0].id, d.alloc_id()); + d.insert(Some(l), usize::MAX, Node::new(inst, NodeKind::SymbolInstance { symbol: "Deep0".into(), xf: Affine::IDENTITY })).unwrap(); + let (s, p) = (Selection::default(), paint()); + assert_eq!(sample_color_at(&cx(&d, &s, &p), Point::new(150.5, 150.5)).map(|c| c.to_hex()), None); + } + + /// A pattern with more tiles over the point than a sample looks at gives no color, rather than + /// the color of what lies below it. + #[test] + fn too_many_tiles_over_the_point_give_no_color() { + use vectorcraft_doc::pattern::pattern_paint; + use vectorcraft_geom::{PathData, Rect, SubPath}; + let (mut d, _) = doc_with_rect(); + // An L 0.1 pt thick along the top and left of (0, 0)–(200, 200) on 1 pt tiles: thousands of + // tiles reach (150.5, 150.5), and none of them paints it. + let l: Vec<Point> = [(0.0, 0.0), (200.0, 0.0), (200.0, 0.1), (0.1, 0.1), (0.1, 200.0), (0.0, 200.0)].map(|(x, y)| Point::new(x, y)).into(); + let mut el = (*filled_rect(Rect::new(0.0, 0.0, 1.0, 1.0), Paint::solid(Color::BLACK))).clone(); + if let NodeKind::Path { path, .. } = &mut el.kind { + *path = PathData::single(SubPath::polyline(&l, true)); + } + let mut def = vectorcraft_doc::PatternDef::new("Ls", vec![std::sync::Arc::new(el)]); + def.tile = Rect::new(0.0, 0.0, 1.0, 1.0); + d.patterns.push(def); + let (l, top) = (d.layers[0].id, d.alloc_id()); + let mut over = (*filled_rect(Rect::new(100.0, 100.0, 200.0, 200.0), pattern_paint("Ls"))).clone(); + over.id = top; + d.insert(Some(l), usize::MAX, over).unwrap(); + let (s, p) = (Selection::default(), paint()); + assert_eq!(sample_color_at(&cx(&d, &s, &p), Point::new(150.5, 150.5)).map(|c| c.to_hex()), None); + } + + /// Symbol art in a tile is sampled only in the tiles the canvas draws, which it lists by the + /// art's bounds without its symbols. + #[test] + fn symbol_art_far_outside_its_tile_samples_as_the_canvas_draws_it() { + use std::sync::Arc; + use vectorcraft_doc::NodeId; + use vectorcraft_geom::{Affine, Rect}; + let (mut d, id) = doc_with_rect(); + // A 20 pt tile holding an instance of a 10 pt green square that sits 100 pt right of it. + // The canvas lists only the tile over a point, whose square lies 100 pt away, so it draws + // no green at x 165, where the square of the tile at x 60 would lie, or at x 175. + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Away".into(), art: filled_rect(Rect::new(100.0, 0.0, 110.0, 10.0), green) }); + let away = Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Away".into(), xf: Affine::IDENTITY })); + let mut def = vectorcraft_doc::PatternDef::new("Away", vec![away]); + def.tile = Rect::new(0.0, 0.0, 20.0, 10.0); + d.patterns.push(def); + d.node_mut(id).unwrap().appearance.set_fill(vectorcraft_doc::pattern::pattern_paint("Away")); + let (s, p) = (Selection::default(), paint()); + let at = |x: f64| sample_color_at(&cx(&d, &s, &p), Point::new(x, 155.0)).map(|c| c.to_hex()); + assert_eq!((at(165.0), at(175.0)), (None, None)); + } + /// Patterns whose tile art is painted with the next one, on tiles far smaller than their art, /// symbols whose art holds four instances of the next, and symbols nested far deeper than a /// sample follows: each sample stops within its work limit and gives no color, instead of @@ -766,18 +948,27 @@ mod tests { use vectorcraft_doc::{NodeId, Symbol}; use vectorcraft_geom::{Affine, Rect}; let (mut d, id) = doc_with_rect(); - // "Nest0" to "Nest7": 300 pt art on 1 pt tiles, each painted with the next. "Nest8" doesn't - // exist, so no tile gives a color and every one is tried. - for i in 0..8 { - let mut def = vectorcraft_doc::PatternDef::new( - &format!("Nest{i}"), - vec![filled_rect(Rect::new(0.0, 0.0, 300.0, 300.0), pattern_paint(&format!("Nest{}", i + 1)))], - ); + // "Gap": an L 0.1 pt thick along the top and left of (0, 0)–(20, 20) on 1 pt tiles, which + // reaches every point from hundreds of tiles and paints none at x.5, y.5. + let l: Vec<Point> = [(0.0, 0.0), (20.0, 0.0), (20.0, 0.1), (0.1, 0.1), (0.1, 20.0), (0.0, 20.0)].map(|(x, y)| Point::new(x, y)).into(); + let mut el = (*filled_rect(Rect::new(0.0, 0.0, 1.0, 1.0), Paint::solid(Color::BLACK))).clone(); + if let NodeKind::Path { path, .. } = &mut el.kind { + *path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&l, true)); + } + let mut gap = vectorcraft_doc::PatternDef::new("Gap", vec![Arc::new(el)]); + gap.tile = Rect::new(0.0, 0.0, 1.0, 1.0); + d.patterns.push(gap); + // "Nest0" and "Nest1": 300 pt art on 1 pt tiles, painted with the next ("Gap" after + // "Nest1"), so no tile gives a color and every one is tried. + for i in 0..2 { + let next = if i == 1 { "Gap".to_string() } else { format!("Nest{}", i + 1) }; + let mut def = + vectorcraft_doc::PatternDef::new(&format!("Nest{i}"), vec![filled_rect(Rect::new(0.0, 0.0, 300.0, 300.0), pattern_paint(&next))]); def.tile = Rect::new(0.0, 0.0, 1.0, 1.0); d.patterns.push(def); } d.node_mut(id).unwrap().appearance.set_fill(pattern_paint("Nest0")); - // "Fan0" to "Fan11": four instances of the next symbol; "Fan12" a square filled with "Nest8". + // "Fan0" to "Fan11": four instances of the next symbol; "Fan12" a square filled with "Gap". let instance = |name: String| Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name, xf: Affine::IDENTITY })); for i in 0..12 { let art = Node::group(NodeId(0), (0..4).map(|_| instance(format!("Fan{}", i + 1))).collect()); @@ -786,7 +977,7 @@ mod tests { d.symbols.push(Symbol { dynamic: false, name: "Fan12".into(), - art: filled_rect(Rect::new(300.0, 300.0, 400.0, 400.0), pattern_paint("Nest8")), + art: filled_rect(Rect::new(300.0, 300.0, 400.0, 400.0), pattern_paint("Gap")), }); // "Deep0" to "Deep99": one instance of the next; "Deep100" a green square. for i in 0..100 { @@ -801,12 +992,92 @@ mod tests { } let (s, p) = (Selection::default(), paint()); let start = std::time::Instant::now(); - for at in [Point::new(150.0, 150.0), Point::new(350.0, 350.0), Point::new(350.0, 50.0)] { + for at in [Point::new(150.5, 150.5), Point::new(350.5, 350.5), Point::new(350.5, 50.5)] { assert_eq!(sample_color_at(&cx(&d, &s, &p), at), None, "{at:?}"); } assert!(start.elapsed() < std::time::Duration::from_secs(60), "{:?}", start.elapsed()); } + /// Each hit test in a tile's art may measure the art of every symbol, so it counts the symbols' + /// objects, also when it is the first one in that art and hits nothing. + #[test] + fn hit_tests_in_tile_art_count_the_symbols_they_may_measure() { + use std::sync::Arc; + use vectorcraft_doc::pattern::pattern_paint; + use vectorcraft_doc::{NodeId, Symbol}; + use vectorcraft_geom::{Affine, PathData, Rect, SubPath}; + let (mut d, id) = doc_with_rect(); + // Tile art: an L 0.1 pt thick along the top and left of (0, 0)–(200, 200), which no 1 pt + // tile places over (150.5, 150.5) though the art of a thousand tiles reaches it, and below + // it an instance of "Dots" (200 squares), which most of those tiles place away from it. + let l: Vec<Point> = [(0.0, 0.0), (200.0, 0.0), (200.0, 0.1), (0.1, 0.1), (0.1, 200.0), (0.0, 200.0)].map(|(x, y)| Point::new(x, y)).into(); + let el = filled_rect(Rect::new(0.0, 0.0, 1.0, 1.0), Paint::solid(Color::BLACK)); + let mut el = (*el).clone(); + if let NodeKind::Path { path, .. } = &mut el.kind { + *path = PathData::single(SubPath::polyline(&l, true)); + } + let green = || Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + let dots = (0..200).map(f64::from).map(|k| filled_rect(Rect::new(k, k, k + 0.1, k + 0.1), green())).collect(); + d.symbols.push(Symbol { dynamic: false, name: "Dots".into(), art: Arc::new(Node::group(NodeId(0), dots)) }); + let far = Affine::translate((0.0, -250.0)); + let inst = Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Dots".into(), xf: far })); + let mut def = vectorcraft_doc::PatternDef::new("Dotted", vec![Arc::new(el), inst]); + def.tile = Rect::new(0.0, 0.0, 1.0, 1.0); + d.patterns.push(def); + d.node_mut(id).unwrap().appearance.set_fill(pattern_paint("Dotted")); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let opts = sample_options(&cx); + let symbol_nodes = d.symbols.iter().map(|s| s.art.count()).sum(); + let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes, work: MAX_WORK, exhausted: false, patterns: 0 }; + let mut levels: Vec<Option<Document>> = (0..MAX_NESTING).map(|_| None).collect(); + color_under(&mut s, &d, &mut levels, Point::new(150.5, 150.5), opts); + // The symbols' objects count for each of at least a hundred tiles, not once for the pattern. + assert!(MAX_WORK - s.work >= 100 * symbol_nodes, "{} spent, {symbol_nodes} symbol objects", MAX_WORK - s.work); + } + + /// A gap in an object's top pattern fill shows the object's own fill below it. + #[test] + fn a_gap_in_a_top_fill_samples_the_fill_below() { + use vectorcraft_doc::pattern::pattern_paint; + use vectorcraft_doc::{AppearanceItem, FillLayer}; + use vectorcraft_geom::Rect; + // The rectangle (100, 100)–(200, 200) filled with red 10 pt squares 20 pt apart over blue. + let (mut d, id) = doc_with_rect(); + let mut gappy = + vectorcraft_doc::PatternDef::new("Gappy", vec![filled_rect(Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)))]); + gappy.tile = Rect::new(0.0, 0.0, 20.0, 10.0); + d.patterns.push(gappy); + let ap = &mut d.node_mut(id).unwrap().appearance; + ap.set_fill(pattern_paint("Gappy")); + ap.items.insert(0, AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0))))); + let (s, p) = (Selection::default(), paint()); + let at = |x: f64| sample_color_at(&cx(&d, &s, &p), Point::new(x, 155.0)).map(|c| c.to_hex()); + // x 125 is 5 into a tile, on a red square; x 133 is 13 into one, between them. + assert_eq!((at(125.0), at(133.0)), (Some("#ff0000".to_string()), Some("#0000ff".to_string()))); + // A hidden top fill is not drawn, so the fill below shows on the squares too. + let mut d = d.clone(); + d.node_mut(id).unwrap().appearance.fill_mut().unwrap().visible = false; + let at = |x: f64| sample_color_at(&cx(&d, &s, &p), Point::new(x, 155.0)).map(|c| c.to_hex()); + assert_eq!(at(125.0), Some("#0000ff".to_string())); + } + + /// Of an object's strokes, the topmost one that reaches the point is sampled. + #[test] + fn the_topmost_stroke_that_reaches_the_point_is_sampled() { + use vectorcraft_doc::{AppearanceItem, StrokeLayer}; + // The rectangle (100, 100)–(200, 200) with a 20 pt blue stroke under a 2 pt red one. + let (mut d, id) = doc_with_rect(); + let ap = &mut d.node_mut(id).unwrap().appearance; + ap.items.retain(|it| it.is_fill()); + ap.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 20.0))); + ap.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 2.0))); + let (s, p) = (Selection::default(), paint()); + let at = |x: f64| sample_color_at(&cx(&d, &s, &p), Point::new(x, 150.0)).map(|c| c.to_hex()); + // x 100 is on both strokes; x 94 is on the blue one only. + assert_eq!((at(100.0), at(94.0)), (Some("#ff0000".to_string()), Some("#0000ff".to_string()))); + } + /// A gap between a pattern's tile art shows what lies below it, in the document and in the tile /// art of another pattern. #[test] @@ -867,6 +1138,24 @@ mod tests { assert_eq!(sampled_hex(&a), "#404040"); } + /// Finding the point in a mesh counts the points it looks at in every patch: a 20 × 20 mesh + /// takes more than a thousand units of work. + #[test] + fn mesh_samples_count_the_work_of_finding_the_point() { + use vectorcraft_doc::{Document, GradientMesh}; + let mut d = Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let mesh = GradientMesh::from_surface(20, 20, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|_, _| Color::rgb(0.0, 1.0, 0.0)); + d.insert(Some(l), 0, Node::new(id, NodeKind::Mesh(mesh))).unwrap(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let opts = sample_options(&cx); + let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: 1_000, exhausted: false, patterns: 0 }; + let mut levels: Vec<Option<Document>> = (0..MAX_NESTING).map(|_| None).collect(); + assert_eq!(color_under(&mut s, &d, &mut levels, Point::new(150.0, 150.0), opts).map(|c| c.to_hex()), None); + assert!(s.exhausted); + } + #[test] fn gradient_sampled_along_vector() { let g = vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default()); From 1f5cb914fd497f6b4a754fed4cfaa27aa5b34176 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 10:57:18 -0700 Subject: [PATCH 187/260] Actions: Delete Selection deletes the selected action set Delete Selection in the Actions panel (the bottom bar's trash and the panel menu's new Delete) now deletes the selected action set with its actions and keeps the other sets, after asking. A selected action is still deleted at once. Shift-click on a set's name selects the sets from the current one to it, and one question deletes them together. Default Actions and the last set can be deleted; New Set still works on the empty panel. ui.actionSet.delete {sets?: [index]} does the deletion: an index past the last set is an error before anything is deleted, a recording into a deleted set stops, and a recording into a later set stays in its set. Undo does not restore a deleted set. --- crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/bs.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 6 + crates/ui-egui/src/panels/actions.rs | 268 +++++++++++++++++++++++- crates/ui-egui/src/state.rs | 5 + docs/mcp.md | 6 + docs/target-app-parity.md | 1 + docs/ui-parity.md | 3 +- 33 files changed, 358 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 96df01e214..e2b237f2a8 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -743,6 +743,9 @@ font-technology Variable Променливи No Не Delete Tab Изтриване на табулация Delete the graphic style “{name}”? Изтриване на графичния стил „{name}“? + Delete Action Sets Изтриване на набори от действия + Delete the action set “{name}” and its actions? Изтриване на набора от действия „{name}“ и неговите действия? + Delete the selected action sets and their actions? Изтриване на избраните набори от действия и техните действия? Delete Theme Изтриване на тема Delete theme Изтриване на тема Delete these {n} graphic styles? Изтриване на тези {n} графични стила? diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 2d3acc7d3d..879566d12a 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1544,6 +1544,9 @@ digits Malayalam Malajalam Save to Swatches Sačuvaj u uzorke boja Delete Graphic Style (Alt-click: without asking) Izbriši grafički stil (Alt-klik: bez pitanja) Delete the graphic style “{name}”? Izbrisati grafički stil „{name}”? + Delete Action Sets Izbriši skupove akcija + Delete the action set “{name}” and its actions? Izbrisati skup akcija „{name}” i njegove akcije? + Delete the selected action sets and their actions? Izbrisati odabrane skupove akcija i njihove akcije? Delete these {n} graphic styles? Izbrisati ove grafičke stilove ({n})? Delete this {n} graphic style? Izbrisati ovaj grafički stil ({n})? Graphic Style Libraries Menu Meni biblioteka grafičkih stilova diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f9648d21a9..d0316d8024 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1060,6 +1060,9 @@ No No Delete Tab Suprimeix la tabulació Delete the graphic style “{name}”? Voleu suprimir l’estil gràfic “{name}”? + Delete Action Sets Suprimeix els conjunts d’accions + Delete the action set “{name}” and its actions? Voleu suprimir el conjunt d’accions “{name}” i les seves accions? + Delete the selected action sets and their actions? Voleu suprimir els conjunts d’accions seleccionats i les seves accions? Delete the library “{name}”? Voleu suprimir la biblioteca “{name}”? Delete Theme Suprimeix el tema Delete theme Suprimeix el tema diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index e5a6bc1da2..3e441728aa 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1568,6 +1568,9 @@ digits Malayalam Malajálamské Save to Swatches Uložit do vzorníku Delete Graphic Style (Alt-click: without asking) Odstranit grafický styl (Alt+kliknutí: bez dotazu) Delete the graphic style “{name}”? Odstranit grafický styl „{name}“? + Delete Action Sets Odstranit sady akcí + Delete the action set “{name}” and its actions? Odstranit sadu akcí „{name}“ a její akce? + Delete the selected action sets and their actions? Odstranit vybrané sady akcí a jejich akce? Delete these {n} graphic styles? Odstranit tyto grafické styly ({n})? Delete this {n} graphic style? Odstranit tento grafický styl ({n})? Graphic Style Libraries Menu Nabídka knihoven grafických stylů diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index e6c0987edc..36f923e49e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1481,6 +1481,9 @@ digits Malayalam Malayalam Save to Swatches Gem i farveprøver Delete Graphic Style (Alt-click: without asking) Slet grafisk typografi (Alt-klik: uden at spørge) Delete the graphic style “{name}”? Slet den grafiske typografi »{name}«? + Delete Action Sets Slet handlingssæt + Delete the action set “{name}” and its actions? Slet handlingssættet »{name}« og dets handlinger? + Delete the selected action sets and their actions? Slet de markerede handlingssæt og deres handlinger? Delete these {n} graphic styles? Slet disse {n} grafiske typografier? Delete this {n} graphic style? Slet denne {n} grafiske typografi? Graphic Style Libraries Menu Menu med biblioteker af grafiske typografier diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 8abc9ca13a..6e6dc23930 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -737,6 +737,9 @@ font-technology Variable Variabel No Nein Delete Tab Tabulator löschen Delete the graphic style “{name}”? Grafikstil „{name}“ löschen? + Delete Action Sets Aktionssätze löschen + Delete the action set “{name}” and its actions? Aktionssatz „{name}“ und seine Aktionen löschen? + Delete the selected action sets and their actions? Ausgewählte Aktionssätze und ihre Aktionen löschen? Delete Theme Thema löschen Delete theme Thema löschen Delete these {n} graphic styles? Diese {n} Grafikstile löschen? diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index f8be1cf381..160be58422 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -717,6 +717,9 @@ font-technology Variable Μεταβλητές No Όχι Delete Tab Διαγραφή στηλοθέτη Delete the graphic style “{name}”? Να διαγραφεί το στυλ γραφικών «{name}»; + Delete Action Sets Διαγραφή συνόλων ενεργειών + Delete the action set “{name}” and its actions? Να διαγραφεί το σύνολο ενεργειών «{name}» και οι ενέργειές του; + Delete the selected action sets and their actions? Να διαγραφούν τα επιλεγμένα σύνολα ενεργειών και οι ενέργειές τους; Delete Theme Διαγραφή θέματος Delete theme Διαγραφή θέματος Delete these {n} graphic styles? Να διαγραφούν αυτά τα {n} στυλ γραφικών; diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a73a9155a4..8a682cdc95 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -758,6 +758,9 @@ font-technology Variable Variables No No Delete Tab Eliminar tabulación Delete the graphic style “{name}”? ¿Eliminar el estilo gráfico “{name}”? + Delete Action Sets Eliminar conjuntos de acciones + Delete the action set “{name}” and its actions? ¿Eliminar el conjunto de acciones “{name}” y sus acciones? + Delete the selected action sets and their actions? ¿Eliminar los conjuntos de acciones seleccionados y sus acciones? Delete Theme Eliminar tema Delete theme Eliminar tema Delete these {n} graphic styles? ¿Eliminar estos {n} estilos gráficos? diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index ba97335bf9..6bd598a4b5 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1541,6 +1541,9 @@ digits Malayalam Malajalam Save to Swatches Tallenna värimalleihin Delete Graphic Style (Alt-click: without asking) Poista grafiikkatyyli (Alt-napsautus: kysymättä) Delete the graphic style “{name}”? Poistetaanko grafiikkatyyli ”{name}”? + Delete Action Sets Poista toimintosarjat + Delete the action set “{name}” and its actions? Poistetaanko toimintosarja ”{name}” ja sen toiminnot? + Delete the selected action sets and their actions? Poistetaanko valitut toimintosarjat ja niiden toiminnot? Delete these {n} graphic styles? Poistetaanko nämä {n} grafiikkatyyliä? Delete this {n} graphic style? Poistetaanko tämä {n} grafiikkatyyli? Graphic Style Libraries Menu Grafiikkatyylikirjastojen valikko diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index c3892ba3d5..9e232d2184 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -747,6 +747,9 @@ font-technology Variable Variables Delete Save for Web Preset Supprimer le paramètre prédéfini Enregistrer pour le Web Delete Selected Item Supprimer l’élément sélectionné Delete Selection Supprimer la sélection + Delete Action Sets Supprimer les jeux de scripts + Delete the action set “{name}” and its actions? Supprimer le jeu de scripts « {name} » et ses scripts ? + Delete the selected action sets and their actions? Supprimer les jeux de scripts sélectionnés et leurs scripts ? Delete Slices Supprimer les tranches Delete Spine Point Supprimer le point de la dorsale Delete Stop Supprimer l’étape de dégradé diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e701b93aaf..ffe3360fc8 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -982,6 +982,9 @@ font-technology Variable Változó No Nem Delete Tab Tabulátor törlése Delete the graphic style “{name}”? Törlöd ezt a grafikai stílust: „{name}”? + Delete Action Sets Műveletkészletek törlése + Delete the action set “{name}” and its actions? Törlöd ezt a műveletkészletet és a műveleteit: „{name}”? + Delete the selected action sets and their actions? Törlöd a kijelölt műveletkészleteket és a műveleteiket? Delete the library “{name}”? Törlöd ezt a könyvtárat: „{name}”? Delete Theme Téma törlése Delete theme Téma törlése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 493618378d..d38b743a6d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1481,6 +1481,9 @@ digits Malayalam Malayalam Save to Swatches Simpan ke swatch Delete Graphic Style (Alt-click: without asking) Hapus gaya grafis (Alt+klik: tanpa konfirmasi) Delete the graphic style “{name}”? Hapus gaya grafis “{name}”? + Delete Action Sets Hapus set tindakan + Delete the action set “{name}” and its actions? Hapus set tindakan “{name}” beserta tindakannya? + Delete the selected action sets and their actions? Hapus set tindakan yang dipilih beserta tindakannya? Delete these {n} graphic styles? Hapus {n} gaya grafis ini? Delete this {n} graphic style? Hapus {n} gaya grafis ini? Graphic Style Libraries Menu Menu pustaka gaya grafis diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 9d8d581fad..e1f375654a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -758,6 +758,9 @@ font-technology Variable Variabili No No Delete Tab Elimina tabulazione Delete the graphic style “{name}”? Eliminare lo stile grafico “{name}”? + Delete Action Sets Elimina set di azioni + Delete the action set “{name}” and its actions? Eliminare il set di azioni “{name}” e le sue azioni? + Delete the selected action sets and their actions? Eliminare i set di azioni selezionati e le loro azioni? Delete Theme Elimina tema Delete theme Elimina tema Delete these {n} graphic styles? Eliminare questi {n} stili grafici? diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index b8f6cdd5aa..8fdcd35c3f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1319,6 +1319,9 @@ digits Malayalam マラヤーラム数字 Delete Width Point 幅ポイントを削除 Delete Workspace ワークスペースを削除 Delete the graphic style “{name}”? グラフィックスタイル「{name}」を削除しますか? + Delete Action Sets アクションセットを削除 + Delete the action set “{name}” and its actions? アクションセット「{name}」とそのアクションを削除しますか? + Delete the selected action sets and their actions? 選択したアクションセットとそのアクションを削除しますか? Delete theme テーマを削除 Delete this saved preset この保存済みプリセットを削除 Delete {kind} Style {kind}スタイルを削除 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d5046acac3..b091969fdd 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1398,6 +1398,9 @@ digits Malayalam მალაიალამური Save to Swatches ფერის ნიმუშებში შენახვა Delete Graphic Style (Alt-click: without asking) გრაფიკული სტილის წაშლა (Alt-დაწკაპუნებით: დაუკითხავად) Delete the graphic style “{name}”? წაიშალოს გრაფიკული სტილი „{name}“? + Delete Action Sets მოქმედებების ნაკრებების წაშლა + Delete the action set “{name}” and its actions? წაიშალოს მოქმედებების ნაკრები „{name}“ და მისი მოქმედებები? + Delete the selected action sets and their actions? წაიშალოს მონიშნული მოქმედებების ნაკრებები და მათი მოქმედებები? Delete these {n} graphic styles? წაიშალოს ეს გრაფიკული სტილები ({n})? Delete this {n} graphic style? წაიშალოს ეს გრაფიკული სტილი ({n})? Graphic Style Libraries Menu გრაფიკული სტილების ბიბლიოთეკების მენიუ diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 8c8d194c93..eac09b1b85 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1309,6 +1309,9 @@ digits Malayalam 말라얄람어 Delete Width Point 너비 포인트 삭제 Delete Workspace 작업 영역 삭제 Delete the graphic style “{name}”? 그래픽 스타일 “{name}”을(를) 삭제하시겠습니까? + Delete Action Sets 액션 세트 삭제 + Delete the action set “{name}” and its actions? 액션 세트 “{name}”과(와) 해당 액션을 삭제하시겠습니까? + Delete the selected action sets and their actions? 선택한 액션 세트와 해당 액션을 삭제하시겠습니까? Delete theme 테마 삭제 Delete this saved preset 저장된 이 프리셋 삭제 Delete {kind} Style {kind} 스타일 삭제 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b2b799c9a8..88652875a1 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1495,6 +1495,9 @@ digits Malayalam Malayalam Save to Swatches Opslaan in stalen Delete Graphic Style (Alt-click: without asking) Grafische stijl verwijderen (Alt-klik: zonder vragen) Delete the graphic style “{name}”? De grafische stijl „{name}” verwijderen? + Delete Action Sets Actiesets verwijderen + Delete the action set “{name}” and its actions? De actieset „{name}” en de acties erin verwijderen? + Delete the selected action sets and their actions? De geselecteerde actiesets en de acties erin verwijderen? Delete these {n} graphic styles? Deze {n} grafische stijlen verwijderen? Delete this {n} graphic style? Deze {n} grafische stijl verwijderen? Graphic Style Libraries Menu Menu grafische stijlbibliotheken diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 79d3ca69f7..2761b1fb31 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1481,6 +1481,9 @@ digits Malayalam Malajalam Save to Swatches Zapisz w próbkach Delete Graphic Style (Alt-click: without asking) Usuń styl graficzny (kliknięcie z Alt: bez pytania) Delete the graphic style “{name}”? Usunąć styl graficzny „{name}”? + Delete Action Sets Usuń zestawy operacji + Delete the action set “{name}” and its actions? Usunąć zestaw operacji „{name}” i jego operacje? + Delete the selected action sets and their actions? Usunąć zaznaczone zestawy operacji i ich operacje? Delete these {n} graphic styles? Usunąć te style graficzne ({n})? Delete this {n} graphic style? Usunąć ten styl graficzny ({n})? Graphic Style Libraries Menu Menu bibliotek stylów graficznych diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index c4d69d0187..33e8b45d57 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -675,6 +675,9 @@ Delete Width Point Excluir Ponto de Largura Delete Workspace Excluir Espaço de Trabalho Delete the graphic style “{name}”? Excluir o estilo gráfico “{name}”? + Delete Action Sets Excluir Conjuntos de Ações + Delete the action set “{name}” and its actions? Excluir o conjunto de ações “{name}” e suas ações? + Delete the selected action sets and their actions? Excluir os conjuntos de ações selecionados e suas ações? Delete theme Excluir tema Delete this saved preset Excluir este predefinido salvo Delete {kind} Style Excluir Estilo de {kind} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 3f328f94d0..8bab68b835 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -756,6 +756,9 @@ font-technology Variable Вариативные No Нет Delete Tab Удалить табуляцию Delete the graphic style “{name}”? Удалить графический стиль «{name}»? + Delete Action Sets Удалить наборы действий + Delete the action set “{name}” and its actions? Удалить набор действий «{name}» и его действия? + Delete the selected action sets and their actions? Удалить выбранные наборы действий и их действия? Delete Theme Удалить тему Delete theme Удалить тему Delete these {n} graphic styles? Удалить эти графические стили ({n})? diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index eee2ef8859..572afa011d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -745,6 +745,9 @@ font-technology Variable Variabla No Nej Delete Tab Radera tabb Delete the graphic style “{name}”? Radera grafikstilen ”{name}”? + Delete Action Sets Radera åtgärdsuppsättningar + Delete the action set “{name}” and its actions? Radera åtgärdsuppsättningen ”{name}” och dess åtgärder? + Delete the selected action sets and their actions? Radera de markerade åtgärdsuppsättningarna och deras åtgärder? Delete Theme Radera tema Delete theme Radera tema Delete these {n} graphic styles? Radera dessa {n} grafikstilar? diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 324ab77e06..ffb90dbb95 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -737,6 +737,9 @@ font-technology Variable Değişken No Hayır Delete Tab Sekmeyi Sil Delete the graphic style “{name}”? “{name}” grafik stili silinsin mi? + Delete Action Sets Eylem Setlerini Sil + Delete the action set “{name}” and its actions? “{name}” eylem seti ve eylemleri silinsin mi? + Delete the selected action sets and their actions? Seçili eylem setleri ve eylemleri silinsin mi? Delete Theme Temayı Sil Delete theme Temayı sil Delete these {n} graphic styles? Bu {n} grafik stilleri silinsin mi? diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 6ada758d86..543e4834cf 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -752,6 +752,9 @@ font-technology Variable Варіативні No Ні Delete Tab Видалити табуляцію Delete the graphic style “{name}”? Видалити графічний стиль «{name}»? + Delete Action Sets Видалити набори дій + Delete the action set “{name}” and its actions? Видалити набір дій «{name}» і його дії? + Delete the selected action sets and their actions? Видалити вибрані набори дій і їхні дії? Delete Theme Видалити тему Delete theme Видалити тему Delete these {n} graphic styles? Видалити ці графічні стилі ({n})? diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 1aa0e91c69..78f16ce995 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -878,6 +878,9 @@ font-technology Variable Biến thiên No Không Delete Tab Xóa tab Delete the graphic style “{name}”? Xóa kiểu đồ họa “{name}”? + Delete Action Sets Xóa các bộ hành động + Delete the action set “{name}” and its actions? Xóa bộ hành động “{name}” và các hành động của nó? + Delete the selected action sets and their actions? Xóa các bộ hành động đã chọn và các hành động của chúng? Delete the library “{name}”? Xóa thư viện “{name}”? Delete Theme Xóa bộ màu Delete theme Xóa bộ màu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f0e7b021ca..3249ed52f7 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -701,6 +701,9 @@ No 否 Delete Tab 删除制表位 Delete the graphic style “{name}”? 要删除图形样式“{name}”吗? + Delete Action Sets 删除动作组 + Delete the action set “{name}” and its actions? 要删除动作组“{name}”及其中的动作吗? + Delete the selected action sets and their actions? 要删除所选动作组及其中的动作吗? Delete Theme 删除主题 Delete theme 删除主题 Delete these {n} graphic styles? 要删除这 {n} 个图形样式吗? diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d6b7bc23e7..70c266d79d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -720,6 +720,9 @@ font-technology Variable 可變 No 否 Delete Tab 刪除定位點 Delete the graphic style “{name}”? 要刪除繪圖樣式「{name}」嗎? + Delete Action Sets 刪除動作組 + Delete the action set “{name}” and its actions? 要刪除動作組「{name}」及其中的動作嗎? + Delete the selected action sets and their actions? 要刪除所選動作組及其中的動作嗎? Delete Theme 刪除主題 Delete theme 刪除主題 Delete these {n} graphic styles? 要刪除這 {n} 個繪圖樣式嗎? diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index f85b25d704..5da061cbe0 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -783,6 +783,7 @@ fn run_ui_part11(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result let action = p.get("action").and_then(Value::as_u64).unwrap_or(0) as usize; crate::dialogs::action_batch::open(app, set, action) } + crate::panels::actions::DELETE_SETS => crate::panels::actions::delete_sets(app, p), "ui.shortcutImportDialog" => crate::dialogs::shortcut_import::command(app, p), _ => return None, }; diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 20f6d4b239..c4ef8d753e 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1119,6 +1119,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{set?: index, action?: index} open Batch (dialog `actionBatch`) for the action at set/action (default: the first action of the first set); OK runs action.batch with the dialog's source, destination and overrides", ), + ( + crate::panels::actions::DELETE_SETS, + "Delete Action Sets", + "", + "{sets?: [index]} delete the Actions panel's sets at these indexes (0 is the top set), with their actions (default: the current set). The panel's Delete Selection on selected sets (Shift-click adds a range) asks first, and OK runs this. A recording into a deleted set stops and keeps nothing. An index past the last set is an error → {deleted: n}", + ), ("file.showPackage", "Show Package", "", "{folder} show a package folder (file.package's folder) in the file manager → {folder}"), ( "docInfo.save", diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 105d18f447..d966b78490 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -51,6 +51,79 @@ pub fn play(app: &mut VectorcraftApp, set: usize, idx: usize) -> Result<Value, S app.run("command.batch", json!({"label": a.name, "commands": commands})) } +/// The command that deletes action sets ([`delete_sets`]). +pub const DELETE_SETS: &str = "ui.actionSet.delete"; + +/// The sets Delete Selection deletes: the selected sets ([`crate::state::UiState::action_sets_selected`]) +/// when the current set is one of them, else the current set alone. +fn selected_sets(app: &VectorcraftApp) -> Vec<usize> { + let len = app.ui.action_sets.len(); + let current = app.ui.action_set.filter(|&s| s < len); + let sets: Vec<usize> = app.ui.action_sets_selected.iter().copied().filter(|&s| s < len).collect(); + if current.is_some_and(|c| sets.contains(&c)) { sets } else { current.into_iter().collect() } +} + +/// Delete Selection, from the bottom bar and the panel menu: deletes the selected action, else asks +/// whether to delete the selected sets ([`DELETE_SETS`]). +fn delete_selection(app: &mut VectorcraftApp, ctx: &egui::Context) { + const SELECTED: &str = "actions-selected"; + // A selected action counts only while its set is the current one, as the panel shows it. + if let Some((si, ai)) = pstate::<Option<(usize, usize)>>(ctx, SELECTED).filter(|&(s, _)| app.ui.action_set == Some(s)) { + if let Some(s) = app.ui.action_sets.get_mut(si) + && ai < s.actions.len() + { + s.actions.remove(ai); + set_pstate::<Option<(usize, usize)>>(ctx, SELECTED, None); + } + return; + } + let sets = selected_sets(app); + let message = match sets[..] { + [] => return, + [s] => crate::i18n::fmt( + tl!("Delete the action set “{name}” and its actions?"), + &[("name", app.ui.action_sets.get(s).map_or("", |s| s.name.as_str()))], + ), + _ => tl!("Delete the selected action sets and their actions?").to_string(), + }; + crate::dialogs::confirm::ask(app, &message, "", DELETE_SETS, json!({ "sets": sets })); +} + +/// `ui.actionSet.delete {sets?: [index]}`: deletes the action sets at these indexes, with their +/// actions (default: the current set). A recording into a deleted set stops, and its steps are +/// dropped; a recording into another set goes on. When the current set is deleted, no set is +/// current afterwards. +pub fn delete_sets(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { + let len = app.ui.action_sets.len(); + let mut sets: Vec<usize> = match p.get("sets") { + None | Some(Value::Null) => app.ui.action_set.filter(|&s| s < len).into_iter().collect(), + Some(v) => v + .as_array() + .ok_or("no such action set")? + .iter() + .map(|i| i.as_u64().map(|i| i as usize).filter(|&i| i < len).ok_or("no such action set")) + .collect::<Result<_, _>>()?, + }; + sets.sort_unstable(); + sets.dedup(); + if let Some((rec, ..)) = app.ui.recording.as_mut() { + if sets.contains(rec) { + app.ui.recording = None; + app.session.journal.hold(None); + } else { + *rec -= sets.iter().filter(|&&s| s < *rec).count(); + } + } + for &s in sets.iter().rev() { + app.ui.action_sets.remove(s); + } + if !sets.is_empty() { + app.ui.action_set = app.ui.action_set.filter(|c| !sets.contains(c)).map(|c| c - sets.iter().filter(|&&s| s < c).count()); + app.ui.action_sets_selected.clear(); + } + Ok(json!({ "deleted": sets.len() })) +} + /// The panel's (≡) menu. pub fn menu(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let selected: Option<(usize, usize)> = pstate(ui.ctx(), "actions-selected"); @@ -58,6 +131,9 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut egui::Ui) { if widgets::menu_item(ui, tl!("New Set…"), true, false) { crate::dialogs::action_set_options::open_new(app); } + if widgets::menu_item(ui, tl!("Delete"), has || !selected_sets(app).is_empty(), false) { + delete_selection(app, ui.ctx()); + } let current = app.ui.action_set.filter(|&s| s < app.ui.action_sets.len()); if widgets::menu_item(ui, tl!("Set Options…"), current.is_some(), false) && let Some(s) = current @@ -90,18 +166,28 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { selected = None; } let mut current = app.ui.action_set; + let mut sets_selected = selected_sets(app); + let shift = ui.input(|i| i.modifiers.shift); let mut play_req = None; egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| { for (si, set) in app.ui.action_sets.iter().enumerate() { let (r, resp) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 20.0), egui::Sense::click()); - if current == Some(si) && selected.is_none() { + if sets_selected.contains(&si) && selected.is_none() { ui.painter().rect_filled(r, 0.0, t.row_selected); } else if resp.hovered() { ui.painter().rect_filled(r, 0.0, t.hover); } ui.painter().text(r.left_center(), egui::Align2::LEFT_CENTER, format!("▾ {}", set.name), egui::FontId::proportional(12.5), t.text); if resp.clicked() { - current = Some(si); + // Shift-click selects the sets from the current one to the one clicked; the current + // set stays as it was. + match current { + Some(c) if shift && selected.is_none() && sets_selected.contains(&c) => sets_selected = (c.min(si)..=c.max(si)).collect(), + _ => { + current = Some(si); + sets_selected = vec![si]; + } + } selected = None; } for (ai, a) in set.actions.iter().enumerate() { @@ -129,6 +215,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { if resp.clicked() { selected = Some((si, ai)); current = Some(si); + sets_selected = vec![si]; } if resp.double_clicked() { play_req = Some((si, ai)); @@ -138,6 +225,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { }); set_pstate(ui.ctx(), SELECTED, selected); app.ui.action_set = current; + app.ui.action_sets_selected = sets_selected; widgets::divider(ui); // Bottom bar: stop, record, play, new set, delete. ui.horizontal(|ui| { @@ -174,13 +262,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { if widgets::icon_button(ui, "dc-folder", tl!("Create New Set"), false, 24.0).clicked() { crate::dialogs::action_set_options::open_new(app); } - if widgets::icon_button(ui, "trash-2", tl!("Delete Selection"), false, 24.0).clicked() - && let Some((si, ai)) = selected - && let Some(s) = app.ui.action_sets.get_mut(si) - && ai < s.actions.len() - { - s.actions.remove(ai); - set_pstate::<Option<(usize, usize)>>(ui.ctx(), SELECTED, None); + if widgets::icon_button(ui, "trash-2", tl!("Delete Selection"), false, 24.0).clicked() { + delete_selection(app, ui.ctx()); } if recording { ui.label(egui::RichText::new(tl!("● Recording")).color(egui::Color32::from_rgb(0xe0, 0x30, 0x30))); @@ -309,6 +392,173 @@ mod tests { assert_eq!(names, [("Default Actions", 6), ("Web", 0)], "the clicked set is renamed, the other kept"); } + /// An app with the default set and the sets Mine (two actions) and Other. + fn app_with_sets() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let action = |name: &str| Action { name: name.into(), steps: vec![("object.move".into(), json!({"dx": 1, "dy": 0}))] }; + app.ui.action_sets.push(ActionSet { name: "Mine".into(), actions: vec![action("Nudge"), action("Nudge Again")] }); + app.ui.action_sets.push(ActionSet { name: "Other".into(), actions: vec![] }); + app + } + + fn set_names(app: &VectorcraftApp) -> Vec<String> { + app.ui.action_sets.iter().map(|s| s.name.clone()).collect() + } + + /// The bottom bar's Delete Selection button (stop, record, play, new set, delete). + fn trash(ctx: &egui::Context, app: &mut VectorcraftApp) -> egui::Pos2 { + super::super::tests_appearance::frame_events(ctx, app, vec![], show); + let mut bar = crate::toolbar::tests::widget_rects(ctx, egui::vec2(24.0, 24.0)); + bar.sort_by(|a, b| a.left().total_cmp(&b.left())); + let [_, _, _, _, delete] = bar[..] else { panic!("the bottom bar: {bar:?}") }; + delete.center() + } + + /// A click on the name of set `name` with `modifiers` held. + fn click_set(ctx: &egui::Context, app: &mut VectorcraftApp, name: &str, modifiers: egui::Modifiers) { + use super::super::tests_appearance::{frame_events, text_rect}; + let pos = text_rect(&frame_events(ctx, app, vec![], show), &format!("▾ {name}")).center(); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; + for e in [egui::Event::PointerMoved(pos), button(true), button(false)] { + frame_events(ctx, app, vec![egui::Event::ModifiersChanged(modifiers), e], show); + } + } + + /// The question Delete Selection asks about sets, with the sets OK deletes. + fn asked(app: &VectorcraftApp) -> Option<(String, Value)> { + let d = app.ui.dialog.as_ref()?; + (d.kind == crate::dialogs::confirm::KIND && d.str("__command") == DELETE_SETS) + .then(|| (d.str("message"), d.fields["__params"]["sets"].clone())) + } + + /// Delete Selection with a set selected asks first: Cancel keeps every set, OK deletes the + /// selected set with its actions and keeps the others. + #[test] + fn delete_selection_asks_and_then_deletes_the_selected_set() { + use super::super::tests_appearance::click; + let mut app = app_with_sets(); + let ctx = egui::Context::default(); + click_set(&ctx, &mut app, "Mine", egui::Modifiers::NONE); + let delete = trash(&ctx, &mut app); + click(&ctx, &mut app, delete, show); + let (message, sets) = asked(&app).expect("Delete Selection asks before deleting a set"); + assert_eq!((message.as_str(), sets), ("Delete the action set “Mine” and its actions?", json!([1]))); + crate::dialogs::cancel(&mut app); + assert_eq!(set_names(&app), ["Default Actions", "Mine", "Other"], "Cancel deletes nothing"); + click(&ctx, &mut app, delete, show); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(set_names(&app), ["Default Actions", "Other"], "OK deletes the selected set and its actions"); + assert_eq!(app.ui.action_set, None, "no set is current after the current one is deleted"); + let delete = trash(&ctx, &mut app); + click(&ctx, &mut app, delete, show); + assert!(app.ui.dialog.is_none(), "nothing selected: nothing to ask about"); + } + + /// The panel menu's Delete asks the same question about the selected set, and deletes a + /// selected action at once, as the bottom bar's button does. + #[test] + fn the_panel_menus_delete_deletes_the_selected_set_or_action() { + use super::super::tests_appearance::{click, frame_events, text_rect}; + let mut app = app_with_sets(); + let ctx = egui::Context::default(); + let delete = |ctx: &egui::Context, app: &mut VectorcraftApp| { + let texts = frame_events(ctx, app, vec![], menu); + let item = texts.iter().find(|(s, _)| s.trim() == "Delete").map(|(_, r)| *r).expect("Delete in the menu"); + click(ctx, app, item.center(), menu); + }; + click_set(&ctx, &mut app, "Other", egui::Modifiers::NONE); + delete(&ctx, &mut app); + assert_eq!(asked(&app).map(|(_, sets)| sets), Some(json!([2]))); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(set_names(&app), ["Default Actions", "Mine"]); + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "Nudge").center(), show); + frame_events(&ctx, &mut app, vec![], show); + delete(&ctx, &mut app); + assert!(app.ui.dialog.is_none(), "an action is deleted without a question"); + let actions = app.ui.action_sets[1].actions.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(); + assert_eq!((set_names(&app).len(), actions), (2, vec!["Nudge Again"]), "the action goes, its set stays"); + } + + /// After New Set makes another set current, the panel menu's Delete asks about that set and + /// leaves the action selected before it. + #[test] + fn delete_after_new_set_targets_the_new_set() { + use super::super::tests_appearance::{click, frame_events, text_rect}; + let mut app = app_with_sets(); + let ctx = egui::Context::default(); + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "Nudge").center(), show); + crate::dialogs::action_set_options::open_new(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + let texts = frame_events(&ctx, &mut app, vec![], menu); + let item = texts.iter().find(|(s, _)| s.trim() == "Delete").map(|(_, r)| *r).expect("Delete in the menu"); + click(&ctx, &mut app, item.center(), menu); + assert_eq!(asked(&app).map(|(_, sets)| sets), Some(json!([3])), "the new set, not the action"); + assert_eq!(app.ui.action_sets[1].actions.len(), 2); + } + + /// Shift-click on a set's name selects the sets from the current one to it, and one question + /// deletes them all; the set left out stays. + #[test] + fn shift_click_selects_sets_that_one_question_deletes() { + use super::super::tests_appearance::click; + let mut app = app_with_sets(); + let ctx = egui::Context::default(); + click_set(&ctx, &mut app, "Mine", egui::Modifiers::NONE); + click_set(&ctx, &mut app, "Other", egui::Modifiers::SHIFT); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(1), vec![1, 2]), "the current set stays"); + let delete = trash(&ctx, &mut app); + click(&ctx, &mut app, delete, show); + assert_eq!(asked(&app), Some(("Delete the selected action sets and their actions?".to_string(), json!([1, 2])))); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(set_names(&app), ["Default Actions"]); + // A plain click selects one set again. + app.ui.action_sets.extend([ActionSet { name: "A".into(), actions: vec![] }, ActionSet { name: "B".into(), actions: vec![] }]); + click_set(&ctx, &mut app, "A", egui::Modifiers::NONE); + click_set(&ctx, &mut app, "Default Actions", egui::Modifiers::SHIFT); + click_set(&ctx, &mut app, "B", egui::Modifiers::NONE); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(2), vec![2])); + } + + /// The default set can be deleted, and so can the last set: the panel is then empty, no set is + /// current, and New Set makes a set again. + #[test] + fn deleting_the_default_and_the_last_set_leaves_an_empty_panel() { + use super::super::tests_appearance::click; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + click_set(&ctx, &mut app, "Default Actions", egui::Modifiers::NONE); + let delete = trash(&ctx, &mut app); + click(&ctx, &mut app, delete, show); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.action_sets.is_empty()); + assert_eq!(app.ui.action_set, None); + crate::dialogs::action_set_options::open_new(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((set_names(&app), app.ui.action_set), (vec!["Set 1".to_string()], Some(0)), "New Set works on an empty panel"); + } + + /// `ui.actionSet.delete` keeps a recording into a later set going in the same set, stops one + /// into a deleted set, and refuses an index past the last set. + #[test] + fn deleting_sets_keeps_a_recording_in_its_set() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.ui.action_set = Some(2); + let start = app.session.journal.len(); + app.session.journal.hold(Some(start)); + app.ui.recording = Some((2, "Action 1".into(), start)); + assert_eq!(app.run(DELETE_SETS, json!({"sets": [1]})).unwrap(), json!({"deleted": 1})); + assert_eq!(set_names(&app), ["Default Actions", "Other"]); + assert_eq!((app.ui.recording.as_ref().map(|r| r.0), app.ui.action_set), (Some(1), Some(1)), "still recording into Other"); + assert_eq!(app.run(DELETE_SETS, json!({"sets": [5]})).unwrap_err(), "no such action set"); + assert_eq!(app.run(DELETE_SETS, json!({})).unwrap(), json!({"deleted": 1}), "the current set by default"); + assert_eq!(set_names(&app), ["Default Actions"]); + assert!(app.ui.recording.is_none(), "the recording into the deleted set stops"); + assert_eq!(app.session.journal.held(), None); + } + /// A recording keeps its steps when a canceled undo group drops journal entries made before the /// recording began. #[test] diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 63a4f03901..0a78ee2b0f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -448,6 +448,10 @@ pub struct UiState { /// with New Set): a recording goes into it and Set Options renames it. Not saved. #[serde(skip)] pub action_set: Option<usize>, + /// The sets selected in the Actions panel, in index order: the current set and the sets a + /// Shift-click on a set's name added. Delete Selection deletes them. Not saved. + #[serde(skip)] + pub action_sets_selected: Vec<usize>, /// Recording in progress: (set index, action name, journal length when recording started). #[serde(skip)] pub recording: Option<(usize, String, usize)>, @@ -876,6 +880,7 @@ impl Default for UiState { about: false, action_sets: crate::panels::actions::default_sets(), action_set: None, + action_sets_selected: vec![], recording: None, shortcut_overrides: Default::default(), shortcut_set: default_shortcut_set(), diff --git a/docs/mcp.md b/docs/mcp.md index 2b4c2ee3c2..f8b00d2b28 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1650,6 +1650,12 @@ already walks Image Trace. Short agent entry points: is one of the format's extensions (`.svg` and `SVG` give `.svg`, `.JPEG` gives `.jpeg`), and otherwise in the format's first extension (`png8` gives `.png`, `template` gives `.vctemplate`). A step without `format` keeps the source file's extension (`.vectorcraft` over data sets). +- Action sets: `ui.actionSet.delete {sets?: [index]}` deletes the Actions panel's sets at these indexes (0 is the top + set) with their actions, by default the current set, and returns `{deleted}`. An index past the last set is an error, + and then no set is deleted. A recording into a deleted set stops and keeps no steps; a recording into another set + goes on in that set. The panel's Delete Selection (the trash button and the panel menu's Delete) asks before it runs + this for the selected sets, and Shift-click on a set's name selects the sets from the current one to it. Undo does + not restore a deleted set. - Image Trace: `imageTrace.presets`, `imageTrace.make {id?, preset?, params?, view?}` (or `imageTrace.makeAndExpand`), `imageTrace.setView`, `imageTrace.expand`, `imageTrace.release`. A key inside `params` that is not one of the trace settings, such as `colours`, is an error that names it and the nearest setting (`colors`), as for a command's own keys. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4a17438055..914b7e2a57 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -547,6 +547,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Variables: Lock Variables (`variable.lock`, in the Variables panel's bottom bar and menu) stops variables from being defined, deleted or renamed until they are unlocked, while objects can still be bound and unbound and data sets still change and apply; the lock is saved with the document. - Batch…: Override Save and Override Export name each file with the extension of the format the step writes, however the step spells the format (`.svg` and `SVG` give `.svg`, `png8` gives `.png`), in `action.batch`. - Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command. + - Actions panel: Delete Selection deletes the selected action set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html): "Removes the selected action, command, or action set from the panel"; `ui.actionSet.delete`). VectorCraft's own rules, which the overview does not cover: deleting a set asks first, Shift-click on a set's name selects a range of sets to delete together, the panel menu's Delete does the same, and Default Actions and the last set can be deleted. Undo does not bring a deleted set back. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output already in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). - Export for Screens: the dialog's Example line shows the path of the file the export writes first, sub-folder included, named as the export names it, for the first chosen artboard, asset, layer or object (`document.exportForScreens`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 7a68606d7f..342c9dd547 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -294,7 +294,8 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Image Trace panel: the Preview checkbox before Trace chooses whether a setting change traces the selected Image Trace object again at once | done | Per the public documentation, Preview shows the result of the current settings and Trace traces with them (<https://web.archive.org/web/20250831090623/https://helpx.adobe.com/illustrator/using/image-trace.html>). Preview is on by default and kept with the UI preferences; Reset to Default leaves it. Off, changes wait in the panel until Trace applies them as one undo step, or until Preview is turned on again. Changes stay with the object they were made for while another object is selected, and come back when it is selected again. `imageTrace.preview {on?}`, `ui.set {imageTracePreview}`; `panels/image_trace.rs` headless tests (`with_preview_off_a_slider_change_waits_for_trace`, `turning_preview_on_traces_the_changes_that_waited`, `preview_turned_on_with_nothing_selected_traces_when_the_object_is_selected_again`, `settings_that_wait_stay_with_their_object`, `settings_that_wait_come_back_when_their_object_is_selected_again`, `settings_that_wait_are_dropped_when_their_object_changed_since`, `preview_is_kept_with_the_preferences_and_reset_to_default_leaves_it`) | | Toolbar without group labels by default, one or two columns; All Tools drawer by flyout group with shortcuts, its menu (Reset, Basic, Advanced) and Show section | done | #1751; a preference brings the labels back; `toolbar.show` sets the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls | | Actions panel: a clicked action stays selected for Play Current Selection and Delete Selection | partial | #1853 (part of #1629); editing actions and action shortcuts remain | -| Actions panel: Create New Set (bottom bar, ≡ › New Set…) names a new set and Set Options… renames the current one; a click on a set's name makes it current and a recording goes into the current set ([helpx: Automation with actions](https://helpx.adobe.com/illustrator/using/automation-actions.html)) | partial | #3712; the New Action dialog (name, set menu, shortcut, colour), dragging actions between sets and deleting a set remain | +| Actions panel: Create New Set (bottom bar, ≡ › New Set…) names a new set and Set Options… renames the current one; a click on a set's name makes it current and a recording goes into the current set ([helpx: Automation with actions](https://helpx.adobe.com/illustrator/using/automation-actions.html)) | partial | #3712; the New Action dialog (name, set menu, shortcut, colour) and dragging actions between sets remain | +| Actions panel: Delete Selection (bottom bar) deletes the selected set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html): "Removes the selected action, command, or action set from the panel") | partial | `ui.actionSet.delete`; `panels/actions.rs` tests. VectorCraft's own rules, which the overview does not cover: deleting a set asks first (a selected action is still deleted at once), Shift-click on a set's name selects a range of sets, ≡ › Delete does the same as the button, and Default Actions and the last set can be deleted. Undo does not restore a deleted set, and recorded commands cannot be selected or deleted | | Properties panel per context (every selection type's Quick Actions) | partial | one clip group: Edit Clipping Path and Edit Contents, at the top of the panel rather than in Quick Actions (G1); the overview's additional controls ([Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html)): Blend Options (one blend selected, with any tool, #4817) and Merge Live Paint (a Live Paint group with more) in Quick Actions, the Width Profile list (Width tool or a variable-width stroke) and an applied effect's Delete icon in Appearance, Corner and Corner Radius for corners selected with Direct Selection; Variable Font was already there | | Select › Start Global Edit / Stop Global Edit; Properties › Quick Actions with the Global Edit Options popover (Match: Appearance, Size; On Artboards: All Artboards or a range, Include Objects On Canvas; Result(s)); Escape stops it; the matched objects are highlighted in their layer colour while it runs | partial | #3521, `select.globalEdit` / `select.globalEditOptions`, `crates/engine/src/tests/globaledit.rs`; paths, compound paths, symbol instances and groups of them (similar groups, #4939: edits inside one group reach the same object in the others; [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)); the Control panel's copy of the options, Shift-click to leave a match out, rotated copies and highlighting matches before the start remain ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)) | | Contextual task bar | done | | From 35860ef68ebc6e7ba43fcbd0f20f45b5de30a3a8 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 11:28:17 -0700 Subject: [PATCH 188/260] Actions: Delete Action Sets checks the asked sets' names before deleting The question Delete Selection asks now passes the names of the sets it names along with their indexes. ui.actionSet.delete deletes nothing and returns an error when the set at an index no longer has that name, so a set deleted or added above them while the question is open does not make OK delete a different set. An index above the platform's usize range is refused as "no such action set" instead of wrapping on 32-bit builds. --- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/actions.rs | 49 ++++++++++++++++++++++--- docs/mcp.md | 7 ++-- 3 files changed, 48 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index c4ef8d753e..4706377a5d 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1123,7 +1123,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ crate::panels::actions::DELETE_SETS, "Delete Action Sets", "", - "{sets?: [index]} delete the Actions panel's sets at these indexes (0 is the top set), with their actions (default: the current set). The panel's Delete Selection on selected sets (Shift-click adds a range) asks first, and OK runs this. A recording into a deleted set stops and keeps nothing. An index past the last set is an error → {deleted: n}", + "{sets?: [index], names?: [name]} delete the Actions panel's sets at these indexes (0 is the top set), with their actions (default: the current set). With names, the set at each index must still have the name at the same position, or nothing is deleted. The panel's Delete Selection on selected sets (Shift-click adds a range) asks first, and OK runs this. A recording into a deleted set stops and keeps nothing. An index past the last set is an error → {deleted: n}", ), ("file.showPackage", "Show Package", "", "{folder} show a package folder (file.package's folder) in the file manager → {folder}"), ( diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index d966b78490..16400cf51a 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -86,13 +86,16 @@ fn delete_selection(app: &mut VectorcraftApp, ctx: &egui::Context) { ), _ => tl!("Delete the selected action sets and their actions?").to_string(), }; - crate::dialogs::confirm::ask(app, &message, "", DELETE_SETS, json!({ "sets": sets })); + let names: Vec<&str> = sets.iter().filter_map(|&s| app.ui.action_sets.get(s)).map(|s| s.name.as_str()).collect(); + let params = json!({ "sets": sets, "names": names }); + crate::dialogs::confirm::ask(app, &message, "", DELETE_SETS, params); } -/// `ui.actionSet.delete {sets?: [index]}`: deletes the action sets at these indexes, with their -/// actions (default: the current set). A recording into a deleted set stops, and its steps are -/// dropped; a recording into another set goes on. When the current set is deleted, no set is -/// current afterwards. +/// `ui.actionSet.delete {sets?: [index], names?: [name]}`: deletes the action sets at these +/// indexes, with their actions (default: the current set). With `names`, the set at each index +/// must still have the name at the same position, or nothing is deleted. A recording into a +/// deleted set stops, and its steps are dropped; a recording into another set goes on. When the +/// current set is deleted, no set is current afterwards. pub fn delete_sets(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { let len = app.ui.action_sets.len(); let mut sets: Vec<usize> = match p.get("sets") { @@ -101,9 +104,18 @@ pub fn delete_sets(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> .as_array() .ok_or("no such action set")? .iter() - .map(|i| i.as_u64().map(|i| i as usize).filter(|&i| i < len).ok_or("no such action set")) + .map(|i| i.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|&i| i < len).ok_or("no such action set")) .collect::<Result<_, _>>()?, }; + match p.get("names") { + None | Some(Value::Null) => {} + Some(v) => { + let names = v.as_array().filter(|n| n.len() == sets.len()).ok_or("the action set names do not match the sets")?; + if sets.iter().zip(names).any(|(&s, n)| n.as_str() != app.ui.action_sets.get(s).map(|s| s.name.as_str())) { + return Err("the action sets changed; nothing was deleted".into()); + } + } + } sets.sort_unstable(); sets.dedup(); if let Some((rec, ..)) = app.ui.recording.as_mut() { @@ -521,6 +533,29 @@ mod tests { assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(2), vec![2])); } + /// The question names the sets it asks about: when a set before them is deleted while it is + /// open, OK deletes nothing instead of the set that moved into the asked index. + #[test] + fn ok_deletes_nothing_after_the_sets_change_under_the_question() { + use super::super::tests_appearance::click; + let mut app = app_with_sets(); + app.ui.action_sets.push(ActionSet { name: "Third".into(), actions: vec![] }); + let ctx = egui::Context::default(); + click_set(&ctx, &mut app, "Other", egui::Modifiers::NONE); + let delete = trash(&ctx, &mut app); + click(&ctx, &mut app, delete, show); + assert_eq!(asked(&app).map(|(_, sets)| sets), Some(json!([2]))); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.fields["__params"]["names"].clone()), Some(json!(["Other"]))); + app.run(DELETE_SETS, json!({"sets": [1]})).unwrap(); + assert_eq!(set_names(&app), ["Default Actions", "Other", "Third"]); + let _ = crate::dialogs::confirm(&mut app); + assert_eq!(set_names(&app), ["Default Actions", "Other", "Third"], "OK deletes no set the question did not name"); + let p = json!({"sets": [0, 1], "names": ["Default Actions"]}); + assert!(app.run(DELETE_SETS, p).is_err(), "names must match the sets one to one"); + assert_eq!(app.run(DELETE_SETS, json!({"sets": [1], "names": ["Other"]})).unwrap(), json!({"deleted": 1})); + assert_eq!(set_names(&app), ["Default Actions", "Third"]); + } + /// The default set can be deleted, and so can the last set: the panel is then empty, no set is /// current, and New Set makes a set again. #[test] @@ -553,6 +588,8 @@ mod tests { assert_eq!(set_names(&app), ["Default Actions", "Other"]); assert_eq!((app.ui.recording.as_ref().map(|r| r.0), app.ui.action_set), (Some(1), Some(1)), "still recording into Other"); assert_eq!(app.run(DELETE_SETS, json!({"sets": [5]})).unwrap_err(), "no such action set"); + assert_eq!(app.run(DELETE_SETS, json!({"sets": [4_294_967_296u64]})).unwrap_err(), "no such action set", "above u32::MAX"); + assert_eq!(set_names(&app), ["Default Actions", "Other"], "a refused index deletes nothing"); assert_eq!(app.run(DELETE_SETS, json!({})).unwrap(), json!({"deleted": 1}), "the current set by default"); assert_eq!(set_names(&app), ["Default Actions"]); assert!(app.ui.recording.is_none(), "the recording into the deleted set stops"); diff --git a/docs/mcp.md b/docs/mcp.md index f8b00d2b28..c3cc11953d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1650,9 +1650,10 @@ already walks Image Trace. Short agent entry points: is one of the format's extensions (`.svg` and `SVG` give `.svg`, `.JPEG` gives `.jpeg`), and otherwise in the format's first extension (`png8` gives `.png`, `template` gives `.vctemplate`). A step without `format` keeps the source file's extension (`.vectorcraft` over data sets). -- Action sets: `ui.actionSet.delete {sets?: [index]}` deletes the Actions panel's sets at these indexes (0 is the top - set) with their actions, by default the current set, and returns `{deleted}`. An index past the last set is an error, - and then no set is deleted. A recording into a deleted set stops and keeps no steps; a recording into another set +- Action sets: `ui.actionSet.delete {sets?: [index], names?: [name]}` deletes the Actions panel's sets at these indexes + (0 is the top set) with their actions, by default the current set, and returns `{deleted}`. An index past the last + set is an error, and then no set is deleted. With `names`, the set at each index must still have the name at the + same position; otherwise the command returns an error and deletes no set. A recording into a deleted set stops and keeps no steps; a recording into another set goes on in that set. The panel's Delete Selection (the trash button and the panel menu's Delete) asks before it runs this for the selected sets, and Shift-click on a set's name selects the sets from the current one to it. Undo does not restore a deleted set. From 979273f930d0f15fb845f45a3ab8ad588b425a9d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 11:50:38 -0700 Subject: [PATCH 189/260] Actions: Delete Action Sets checks every set's name, and Shift-click selects a range with an action selected The Delete Selection question now carries the names of all sets as they were when it asked (`all`). `ui.actionSet.delete` deletes nothing unless the panel's sets still have exactly those names in that order, so a set with a repeated name that moves into the asked index is not deleted. Shift-click on a set's name selects the sets from the current one to it also while an action in the current set is selected. --- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/actions.rs | 67 +++++++++++++++++++------ docs/mcp.md | 6 +-- 3 files changed, 56 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 4706377a5d..ba94d3c1e7 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1123,7 +1123,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ crate::panels::actions::DELETE_SETS, "Delete Action Sets", "", - "{sets?: [index], names?: [name]} delete the Actions panel's sets at these indexes (0 is the top set), with their actions (default: the current set). With names, the set at each index must still have the name at the same position, or nothing is deleted. The panel's Delete Selection on selected sets (Shift-click adds a range) asks first, and OK runs this. A recording into a deleted set stops and keeps nothing. An index past the last set is an error → {deleted: n}", + "{sets?: [index], all?: [name]} delete the Actions panel's sets at these indexes (0 is the top set), with their actions (default: the current set). With all, the names of every set in the panel, in order, must equal it exactly, or nothing is deleted. The panel's Delete Selection on selected sets (Shift-click adds a range) asks first, and OK runs this. A recording into a deleted set stops and keeps nothing. An index past the last set is an error → {deleted: n}", ), ("file.showPackage", "Show Package", "", "{folder} show a package folder (file.package's folder) in the file manager → {folder}"), ( diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 16400cf51a..ec568ce9c1 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -86,14 +86,14 @@ fn delete_selection(app: &mut VectorcraftApp, ctx: &egui::Context) { ), _ => tl!("Delete the selected action sets and their actions?").to_string(), }; - let names: Vec<&str> = sets.iter().filter_map(|&s| app.ui.action_sets.get(s)).map(|s| s.name.as_str()).collect(); - let params = json!({ "sets": sets, "names": names }); + let all: Vec<&str> = app.ui.action_sets.iter().map(|s| s.name.as_str()).collect(); + let params = json!({ "sets": sets, "all": all }); crate::dialogs::confirm::ask(app, &message, "", DELETE_SETS, params); } -/// `ui.actionSet.delete {sets?: [index], names?: [name]}`: deletes the action sets at these -/// indexes, with their actions (default: the current set). With `names`, the set at each index -/// must still have the name at the same position, or nothing is deleted. A recording into a +/// `ui.actionSet.delete {sets?: [index], all?: [name]}`: deletes the action sets at these +/// indexes, with their actions (default: the current set). With `all`, the names of every set in +/// the panel, in order, must equal it exactly, or nothing is deleted. A recording into a /// deleted set stops, and its steps are dropped; a recording into another set goes on. When the /// current set is deleted, no set is current afterwards. pub fn delete_sets(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { @@ -107,11 +107,11 @@ pub fn delete_sets(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> .map(|i| i.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|&i| i < len).ok_or("no such action set")) .collect::<Result<_, _>>()?, }; - match p.get("names") { + match p.get("all") { None | Some(Value::Null) => {} Some(v) => { - let names = v.as_array().filter(|n| n.len() == sets.len()).ok_or("the action set names do not match the sets")?; - if sets.iter().zip(names).any(|(&s, n)| n.as_str() != app.ui.action_sets.get(s).map(|s| s.name.as_str())) { + let all = v.as_array().ok_or("the action set names are not a list")?; + if all.len() != len || app.ui.action_sets.iter().zip(all).any(|(s, n)| n.as_str() != Some(s.name.as_str())) { return Err("the action sets changed; nothing was deleted".into()); } } @@ -194,7 +194,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { // Shift-click selects the sets from the current one to the one clicked; the current // set stays as it was. match current { - Some(c) if shift && selected.is_none() && sets_selected.contains(&c) => sets_selected = (c.min(si)..=c.max(si)).collect(), + Some(c) if shift && sets_selected.contains(&c) => sets_selected = (c.min(si)..=c.max(si)).collect(), _ => { current = Some(si); sets_selected = vec![si]; @@ -533,8 +533,9 @@ mod tests { assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(2), vec![2])); } - /// The question names the sets it asks about: when a set before them is deleted while it is - /// open, OK deletes nothing instead of the set that moved into the asked index. + /// The question carries the names of every set as they were when it asked: when a set before + /// the asked one is deleted while it is open, OK deletes nothing instead of the set that moved + /// into the asked index. #[test] fn ok_deletes_nothing_after_the_sets_change_under_the_question() { use super::super::tests_appearance::click; @@ -545,17 +546,53 @@ mod tests { let delete = trash(&ctx, &mut app); click(&ctx, &mut app, delete, show); assert_eq!(asked(&app).map(|(_, sets)| sets), Some(json!([2]))); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.fields["__params"]["names"].clone()), Some(json!(["Other"]))); + let all = json!(["Default Actions", "Mine", "Other", "Third"]); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.fields["__params"]["all"].clone()), Some(all)); app.run(DELETE_SETS, json!({"sets": [1]})).unwrap(); assert_eq!(set_names(&app), ["Default Actions", "Other", "Third"]); let _ = crate::dialogs::confirm(&mut app); assert_eq!(set_names(&app), ["Default Actions", "Other", "Third"], "OK deletes no set the question did not name"); - let p = json!({"sets": [0, 1], "names": ["Default Actions"]}); - assert!(app.run(DELETE_SETS, p).is_err(), "names must match the sets one to one"); - assert_eq!(app.run(DELETE_SETS, json!({"sets": [1], "names": ["Other"]})).unwrap(), json!({"deleted": 1})); + let p = json!({"sets": [1], "all": ["Default Actions", "Other"]}); + assert!(app.run(DELETE_SETS, p).is_err(), "all must list every set"); + let p = json!({"sets": [1], "all": ["Default Actions", "Other", "Third"]}); + assert_eq!(app.run(DELETE_SETS, p).unwrap(), json!({"deleted": 1})); assert_eq!(set_names(&app), ["Default Actions", "Third"]); } + /// Two sets with the same name: when the asked one is deleted elsewhere while the question is + /// open, OK does not delete the other one, which now has the asked index and name. + #[test] + fn ok_deletes_nothing_when_a_set_of_the_same_name_moves_into_the_asked_index() { + use super::super::tests_appearance::click; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui.action_sets = vec![ActionSet { name: "X".into(), actions: vec![] }, ActionSet { name: "X".into(), actions: vec![] }]; + let ctx = egui::Context::default(); + click_set(&ctx, &mut app, "X", egui::Modifiers::NONE); + assert_eq!(app.ui.action_set, Some(0)); + let delete = trash(&ctx, &mut app); + click(&ctx, &mut app, delete, show); + assert_eq!(asked(&app).map(|(_, sets)| sets), Some(json!([0]))); + app.run(DELETE_SETS, json!({"sets": [0]})).unwrap(); + let _ = crate::dialogs::confirm(&mut app); + assert_eq!(set_names(&app), ["X"], "OK deletes nothing"); + } + + /// Shift-click on another set's name while an action is selected selects the sets from the + /// current one to it and clears the action. + #[test] + fn shift_click_on_a_set_with_an_action_selected_selects_the_range() { + use super::super::tests_appearance::{click, frame_events, text_rect}; + let mut app = app_with_sets(); + let ctx = egui::Context::default(); + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "Nudge").center(), show); + frame_events(&ctx, &mut app, vec![], show); + assert_eq!(pstate::<Option<(usize, usize)>>(&ctx, "actions-selected"), Some((1, 0))); + click_set(&ctx, &mut app, "Other", egui::Modifiers::SHIFT); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(1), vec![1, 2])); + assert_eq!(pstate::<Option<(usize, usize)>>(&ctx, "actions-selected"), None, "the action is no longer selected"); + } + /// The default set can be deleted, and so can the last set: the panel is then empty, no set is /// current, and New Set makes a set again. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index c3cc11953d..f2e9074f1a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1650,10 +1650,10 @@ already walks Image Trace. Short agent entry points: is one of the format's extensions (`.svg` and `SVG` give `.svg`, `.JPEG` gives `.jpeg`), and otherwise in the format's first extension (`png8` gives `.png`, `template` gives `.vctemplate`). A step without `format` keeps the source file's extension (`.vectorcraft` over data sets). -- Action sets: `ui.actionSet.delete {sets?: [index], names?: [name]}` deletes the Actions panel's sets at these indexes +- Action sets: `ui.actionSet.delete {sets?: [index], all?: [name]}` deletes the Actions panel's sets at these indexes (0 is the top set) with their actions, by default the current set, and returns `{deleted}`. An index past the last - set is an error, and then no set is deleted. With `names`, the set at each index must still have the name at the - same position; otherwise the command returns an error and deletes no set. A recording into a deleted set stops and keeps no steps; a recording into another set + set is an error, and then no set is deleted. With `all`, the names of every set in the panel, in order, must equal + it exactly; otherwise the command returns an error and deletes no set. A recording into a deleted set stops and keeps no steps; a recording into another set goes on in that set. The panel's Delete Selection (the trash button and the panel menu's Delete) asks before it runs this for the selected sets, and Shift-click on a set's name selects the sets from the current one to it. Undo does not restore a deleted set. From 1e8c05f675b01672c6e051889041f8e7c000982a Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 12:22:46 -0700 Subject: [PATCH 190/260] Actions: deleting an action set closes its Set Options or Batch dialog ui.actionSet.delete runs while a dialog is open, from the control channel or MCP. An open Set Options or Batch dialog for a deleted set now closes, and one for a later set has its set index lowered so that OK renames or batches the same set. --- crates/ui-egui/src/dialogs/action_batch.rs | 2 +- crates/ui-egui/src/panels/actions.rs | 46 +++++++++++++++++++++- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index 3464fad755..aa640ade1f 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -8,7 +8,7 @@ use crate::state::Dialog; use crate::theme::Tokens; use crate::{VectorcraftApp, widgets}; -pub(super) const KIND: &str = "actionBatch"; +pub const KIND: &str = "actionBatch"; const LABEL: f32 = 130.0; pub(super) const SPEC: DialogSpec = diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index ec568ce9c1..39126d552c 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -94,8 +94,9 @@ fn delete_selection(app: &mut VectorcraftApp, ctx: &egui::Context) { /// `ui.actionSet.delete {sets?: [index], all?: [name]}`: deletes the action sets at these /// indexes, with their actions (default: the current set). With `all`, the names of every set in /// the panel, in order, must equal it exactly, or nothing is deleted. A recording into a -/// deleted set stops, and its steps are dropped; a recording into another set goes on. When the -/// current set is deleted, no set is current afterwards. +/// deleted set stops, and its steps are dropped; a recording into another set goes on. An open +/// Set Options or Batch dialog for a deleted set closes. When the current set is deleted, no set +/// is current afterwards. pub fn delete_sets(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { let len = app.ui.action_sets.len(); let mut sets: Vec<usize> = match p.get("sets") { @@ -126,6 +127,20 @@ pub fn delete_sets(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> *rec -= sets.iter().filter(|&&s| s < *rec).count(); } } + // An open Set Options or Batch dialog holds a set index: it closes when its set is deleted, + // and otherwise follows its set down. + let holds_set = |d: &crate::state::Dialog| { + d.kind == crate::dialogs::action_batch::KIND || (d.kind == crate::dialogs::action_set_options::KIND && d.fields.contains_key("set")) + }; + if let Some(d) = app.ui.dialog.as_mut().filter(|d| holds_set(d)) + && let Some(set) = d.fields.get("set").and_then(Value::as_u64).and_then(|s| usize::try_from(s).ok()) + { + if sets.contains(&set) { + app.ui.dialog = None; + } else { + d.fields.insert("set".into(), json!(set - sets.iter().filter(|&&s| s < set).count())); + } + } for &s in sets.iter().rev() { app.ui.action_sets.remove(s); } @@ -633,6 +648,33 @@ mod tests { assert_eq!(app.session.journal.held(), None); } + /// `ui.actionSet.delete` while Set Options is open on a later set: OK renames that set, not + /// the one that moves into its old index. + #[test] + fn set_options_renames_its_own_set_after_an_earlier_set_is_deleted() { + let mut app = app_with_sets(); + crate::dialogs::action_set_options::open(&mut app, 2); + app.run(DELETE_SETS, json!({"sets": [1]})).unwrap(); + app.ui.dialog.as_mut().expect("Set Options stays open").fields.insert("name".into(), json!("Web")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(set_names(&app), ["Default Actions", "Web"], "the set that was Other is renamed"); + } + + /// `ui.actionSet.delete` closes a Batch dialog open on an action of a deleted set, and keeps + /// one open on a later set pointing at that set. + #[test] + fn deleting_a_set_closes_its_batch_dialog() { + let mut app = app_with_sets(); + crate::dialogs::action_batch::open(&mut app, 1, 0).unwrap(); + app.run(DELETE_SETS, json!({"sets": [1]})).unwrap(); + assert!(app.ui.dialog.is_none(), "the Batch dialog of the deleted set closes"); + let mut app = app_with_sets(); + crate::dialogs::action_batch::open(&mut app, 1, 1).unwrap(); + app.run(DELETE_SETS, json!({"sets": [0]})).unwrap(); + let d = app.ui.dialog.as_ref().expect("the Batch dialog of a kept set stays open"); + assert_eq!((d.fields["set"].clone(), d.fields["action"].clone()), (json!(0), json!(1)), "it follows Mine to index 0"); + } + /// A recording keeps its steps when a canceled undo group drops journal entries made before the /// recording began. #[test] From ef69c82fca364f39628d748fb0b1a342abee97ea Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 13:26:38 -0700 Subject: [PATCH 191/260] Actions: Delete Selection's question deletes the asked sets by id Each action set now has an id of its own, assigned when the set is made (Default Actions, New Set, Begin Recording on an empty panel) and when it is loaded from the saved preferences. The id is not saved. The question Delete Selection asks about sets holds their ids, and ui.actionSet.delete takes ids in place of all: OK deletes the asked sets wherever they are now, and deletes nothing when one of them no longer exists. Before, the question matched sets by the list of names, so with two sets of the same name, or a new set made under the asked one's name while the question was open, OK could delete a set it did not ask about. --- .../ui-egui/src/dialogs/action_set_options.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/actions.rs | 153 ++++++++++++------ docs/mcp.md | 7 +- 4 files changed, 112 insertions(+), 52 deletions(-) diff --git a/crates/ui-egui/src/dialogs/action_set_options.rs b/crates/ui-egui/src/dialogs/action_set_options.rs index 1312f80d5c..9e9cf8b3c7 100644 --- a/crates/ui-egui/src/dialogs/action_set_options.rs +++ b/crates/ui-egui/src/dialogs/action_set_options.rs @@ -54,7 +54,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { } } None => { - app.ui.action_sets.push(crate::panels::actions::ActionSet { name, actions: vec![] }); + app.ui.action_sets.push(crate::panels::actions::ActionSet::new(name, vec![])); app.ui.action_set = Some(app.ui.action_sets.len() - 1); } } diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index ba94d3c1e7..28642f0152 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1123,7 +1123,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ crate::panels::actions::DELETE_SETS, "Delete Action Sets", "", - "{sets?: [index], all?: [name]} delete the Actions panel's sets at these indexes (0 is the top set), with their actions (default: the current set). With all, the names of every set in the panel, in order, must equal it exactly, or nothing is deleted. The panel's Delete Selection on selected sets (Shift-click adds a range) asks first, and OK runs this. A recording into a deleted set stops and keeps nothing. An index past the last set is an error → {deleted: n}", + "{sets?: [index], ids?: [id]} delete the Actions panel's sets at these indexes (0 is the top set), with their actions (default: the current set). ids holds the panel's own set ids, which its question passes: the sets with these ids are deleted wherever they are now, sets is not read, and when one of them no longer exists nothing is deleted. The panel's Delete Selection on selected sets (Shift-click adds a range) asks first, and OK runs this. A recording into a deleted set stops and keeps nothing. An index past the last set is an error → {deleted: n}", ), ("file.showPackage", "Show Package", "", "{folder} show a package folder (file.package's folder) in the file manager → {folder}"), ( diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 39126d552c..1975859e60 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -18,16 +18,33 @@ pub struct Action { #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ActionSet { + /// Tells the set apart from every other set in this run, even one with the same name. It is + /// not saved: each set gets a new id when it is made or loaded. + #[serde(skip, default = "next_set_id")] + pub id: u64, pub name: String, pub actions: Vec<Action>, } +impl ActionSet { + /// A set with a new [`ActionSet::id`]. + pub fn new(name: impl Into<String>, actions: Vec<Action>) -> Self { + Self { id: next_set_id(), name: name.into(), actions } + } +} + +/// A set id no other set in this run has. +fn next_set_id() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + /// Built-in actions (our own, handy defaults). pub fn default_sets() -> Vec<ActionSet> { let step = |c: &str, p: Value| (c.to_string(), p); - vec![ActionSet { - name: "Default Actions".into(), - actions: vec![ + vec![ActionSet::new( + "Default Actions", + vec![ Action { name: "Duplicate and Offset 10 pt".into(), steps: vec![step("object.move", json!({"dx": 10, "dy": 10, "copy": true}))] }, Action { name: "Unite and Simplify".into(), @@ -41,7 +58,7 @@ pub fn default_sets() -> Vec<ActionSet> { Action { name: "Rotate 90° CW".into(), steps: vec![step("object.rotate", json!({"angle": -90}))] }, Action { name: "Reflect Horizontal".into(), steps: vec![step("object.reflect", json!({"axis": "vertical"}))] }, ], - }] + )] } /// Run an action as a single undoable batch. @@ -86,37 +103,37 @@ fn delete_selection(app: &mut VectorcraftApp, ctx: &egui::Context) { ), _ => tl!("Delete the selected action sets and their actions?").to_string(), }; - let all: Vec<&str> = app.ui.action_sets.iter().map(|s| s.name.as_str()).collect(); - let params = json!({ "sets": sets, "all": all }); + let ids: Vec<u64> = sets.iter().filter_map(|&s| app.ui.action_sets.get(s)).map(|s| s.id).collect(); + let params = json!({ "sets": sets, "ids": ids }); crate::dialogs::confirm::ask(app, &message, "", DELETE_SETS, params); } -/// `ui.actionSet.delete {sets?: [index], all?: [name]}`: deletes the action sets at these -/// indexes, with their actions (default: the current set). With `all`, the names of every set in -/// the panel, in order, must equal it exactly, or nothing is deleted. A recording into a -/// deleted set stops, and its steps are dropped; a recording into another set goes on. An open -/// Set Options or Batch dialog for a deleted set closes. When the current set is deleted, no set -/// is current afterwards. +/// `ui.actionSet.delete {sets?: [index], ids?: [id]}`: deletes the action sets at these +/// indexes, with their actions (default: the current set). `ids` holds the panel's own set ids +/// ([`ActionSet::id`]), which Delete Selection's question passes: the sets with these ids are +/// deleted wherever they are now, `sets` is not read, and when one of them no longer exists +/// nothing is deleted. A recording into a deleted set stops, and its steps are dropped; a +/// recording into another set goes on. An open Set Options or Batch dialog for a deleted set +/// closes. When the current set is deleted, no set is current afterwards. pub fn delete_sets(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { let len = app.ui.action_sets.len(); - let mut sets: Vec<usize> = match p.get("sets") { - None | Some(Value::Null) => app.ui.action_set.filter(|&s| s < len).into_iter().collect(), - Some(v) => v + let mut sets: Vec<usize> = match (p.get("ids"), p.get("sets")) { + (Some(v), _) if !v.is_null() => v + .as_array() + .ok_or("the action set ids are not a list")? + .iter() + .map(|id| { + id.as_u64().and_then(|id| app.ui.action_sets.iter().position(|s| s.id == id)).ok_or("the action sets changed; nothing was deleted") + }) + .collect::<Result<_, _>>()?, + (_, None | Some(Value::Null)) => app.ui.action_set.filter(|&s| s < len).into_iter().collect(), + (_, Some(v)) => v .as_array() .ok_or("no such action set")? .iter() .map(|i| i.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|&i| i < len).ok_or("no such action set")) .collect::<Result<_, _>>()?, }; - match p.get("all") { - None | Some(Value::Null) => {} - Some(v) => { - let all = v.as_array().ok_or("the action set names are not a list")?; - if all.len() != len || app.ui.action_sets.iter().zip(all).any(|(s, n)| n.as_str() != Some(s.name.as_str())) { - return Err("the action sets changed; nothing was deleted".into()); - } - } - } sets.sort_unstable(); sets.dedup(); if let Some((rec, ..)) = app.ui.recording.as_mut() { @@ -272,7 +289,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { ui.painter().circle_filled(r.center(), 6.0, if recording { egui::Color32::from_rgb(0xe0, 0x30, 0x30) } else { t.icon }); if resp.on_hover_text(tl!("Begin Recording")).clicked() && !recording { if app.ui.action_sets.is_empty() { - app.ui.action_sets.push(ActionSet { name: "Set 1".into(), actions: vec![] }); + app.ui.action_sets.push(ActionSet::new("Set 1", vec![])); } let set = current.filter(|&s| s < app.ui.action_sets.len()).unwrap_or(0); let n = app.ui.action_sets.get(set).map_or(0, |s| s.actions.len()) + 1; @@ -404,7 +421,7 @@ mod tests { fn set_options_renames_the_current_set() { use super::super::tests_appearance::{click, frame_events, text_rect}; let mut app = VectorcraftApp::new(Session::new(), Default::default()); - app.ui.action_sets.push(ActionSet { name: "Mine".into(), actions: vec![] }); + app.ui.action_sets.push(ActionSet::new("Mine", vec![])); let ctx = egui::Context::default(); let texts = frame_events(&ctx, &mut app, vec![], show); click(&ctx, &mut app, text_rect(&texts, "▾ Mine").center(), show); @@ -423,8 +440,8 @@ mod tests { fn app_with_sets() -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); let action = |name: &str| Action { name: name.into(), steps: vec![("object.move".into(), json!({"dx": 1, "dy": 0}))] }; - app.ui.action_sets.push(ActionSet { name: "Mine".into(), actions: vec![action("Nudge"), action("Nudge Again")] }); - app.ui.action_sets.push(ActionSet { name: "Other".into(), actions: vec![] }); + app.ui.action_sets.push(ActionSet::new("Mine", vec![action("Nudge"), action("Nudge Again")])); + app.ui.action_sets.push(ActionSet::new("Other", vec![])); app } @@ -541,46 +558,46 @@ mod tests { crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(set_names(&app), ["Default Actions"]); // A plain click selects one set again. - app.ui.action_sets.extend([ActionSet { name: "A".into(), actions: vec![] }, ActionSet { name: "B".into(), actions: vec![] }]); + app.ui.action_sets.extend([ActionSet::new("A", vec![]), ActionSet::new("B", vec![])]); click_set(&ctx, &mut app, "A", egui::Modifiers::NONE); click_set(&ctx, &mut app, "Default Actions", egui::Modifiers::SHIFT); click_set(&ctx, &mut app, "B", egui::Modifiers::NONE); assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(2), vec![2])); } - /// The question carries the names of every set as they were when it asked: when a set before - /// the asked one is deleted while it is open, OK deletes nothing instead of the set that moved + /// The question holds the ids of the sets it asks about: when a set before the asked one is + /// deleted while it is open, OK deletes the asked set at its new index, not the set that moved /// into the asked index. #[test] - fn ok_deletes_nothing_after_the_sets_change_under_the_question() { + fn ok_deletes_the_asked_set_after_an_earlier_set_is_deleted_under_the_question() { use super::super::tests_appearance::click; let mut app = app_with_sets(); - app.ui.action_sets.push(ActionSet { name: "Third".into(), actions: vec![] }); + app.ui.action_sets.push(ActionSet::new("Third", vec![])); let ctx = egui::Context::default(); click_set(&ctx, &mut app, "Other", egui::Modifiers::NONE); let delete = trash(&ctx, &mut app); click(&ctx, &mut app, delete, show); assert_eq!(asked(&app).map(|(_, sets)| sets), Some(json!([2]))); - let all = json!(["Default Actions", "Mine", "Other", "Third"]); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.fields["__params"]["all"].clone()), Some(all)); + let id = app.ui.action_sets[2].id; + assert_eq!(app.ui.dialog.as_ref().map(|d| d.fields["__params"]["ids"].clone()), Some(json!([id]))); app.run(DELETE_SETS, json!({"sets": [1]})).unwrap(); assert_eq!(set_names(&app), ["Default Actions", "Other", "Third"]); - let _ = crate::dialogs::confirm(&mut app); - assert_eq!(set_names(&app), ["Default Actions", "Other", "Third"], "OK deletes no set the question did not name"); - let p = json!({"sets": [1], "all": ["Default Actions", "Other"]}); - assert!(app.run(DELETE_SETS, p).is_err(), "all must list every set"); - let p = json!({"sets": [1], "all": ["Default Actions", "Other", "Third"]}); - assert_eq!(app.run(DELETE_SETS, p).unwrap(), json!({"deleted": 1})); - assert_eq!(set_names(&app), ["Default Actions", "Third"]); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(set_names(&app), ["Default Actions", "Third"], "OK deletes Other, the asked set"); + let p = json!({"sets": [0], "ids": [id]}); + assert_eq!(app.run(DELETE_SETS, p).unwrap_err(), "the action sets changed; nothing was deleted"); + assert_eq!(set_names(&app), ["Default Actions", "Third"], "an id that is gone deletes nothing, sets is not read"); } /// Two sets with the same name: when the asked one is deleted elsewhere while the question is - /// open, OK does not delete the other one, which now has the asked index and name. + /// open, OK does not delete the other one, which now has the asked index and name; when the + /// two trade places, OK deletes the asked one at its new index. #[test] - fn ok_deletes_nothing_when_a_set_of_the_same_name_moves_into_the_asked_index() { + fn ok_deletes_only_the_asked_one_of_two_sets_with_the_same_name() { use super::super::tests_appearance::click; let mut app = VectorcraftApp::new(Session::new(), Default::default()); - app.ui.action_sets = vec![ActionSet { name: "X".into(), actions: vec![] }, ActionSet { name: "X".into(), actions: vec![] }]; + let x = |n: &str| ActionSet::new("X", vec![Action { name: n.into(), steps: vec![] }]); + app.ui.action_sets = vec![x("first"), x("second")]; let ctx = egui::Context::default(); click_set(&ctx, &mut app, "X", egui::Modifiers::NONE); assert_eq!(app.ui.action_set, Some(0)); @@ -588,8 +605,50 @@ mod tests { click(&ctx, &mut app, delete, show); assert_eq!(asked(&app).map(|(_, sets)| sets), Some(json!([0]))); app.run(DELETE_SETS, json!({"sets": [0]})).unwrap(); - let _ = crate::dialogs::confirm(&mut app); - assert_eq!(set_names(&app), ["X"], "OK deletes nothing"); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert_eq!(app.ui.action_sets.iter().map(|s| s.actions[0].name.as_str()).collect::<Vec<_>>(), ["second"], "OK deletes nothing"); + app.ui.action_sets = vec![x("first"), x("second")]; + app.ui.action_set = Some(0); + app.ui.action_sets_selected = vec![0]; + let delete = trash(&ctx, &mut app); + click(&ctx, &mut app, delete, show); + assert_eq!(asked(&app).map(|(_, sets)| sets), Some(json!([0]))); + app.ui.action_sets.swap(0, 1); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.ui.action_sets.iter().map(|s| s.actions[0].name.as_str()).collect::<Vec<_>>(), ["second"], "the asked set goes"); + } + + /// When the asked set is deleted while the question is open and a new set with the same name + /// takes its place, OK does not delete the new set. + #[test] + fn ok_does_not_delete_a_new_set_made_in_the_asked_sets_place() { + use super::super::tests_appearance::click; + let mut app = app_with_sets(); + let ctx = egui::Context::default(); + click_set(&ctx, &mut app, "Other", egui::Modifiers::NONE); + let delete = trash(&ctx, &mut app); + click(&ctx, &mut app, delete, show); + assert_eq!(asked(&app).map(|(_, sets)| sets), Some(json!([2]))); + app.run(DELETE_SETS, json!({"sets": [2]})).unwrap(); + app.ui.action_sets.push(ActionSet::new("Other", vec![])); + assert_eq!(set_names(&app), ["Default Actions", "Mine", "Other"]); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert_eq!(set_names(&app), ["Default Actions", "Mine", "Other"], "the new Other stays"); + } + + /// Every set has its own id, and sets read back from the saved preferences get new ids that + /// no other set has. + #[test] + fn action_sets_get_ids_of_their_own_when_made_and_loaded() { + let app = app_with_sets(); + let saved = serde_json::to_value(&app.ui).unwrap(); + assert!(saved["action_sets"][0].get("id").is_none(), "ids are not saved"); + let restored = serde_json::from_value::<crate::state::UiState>(saved).unwrap(); + let mut ids: Vec<u64> = app.ui.action_sets.iter().chain(&restored.action_sets).map(|s| s.id).collect(); + assert_eq!(restored.action_sets.len(), 3); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), 6, "six sets, six ids"); } /// Shift-click on another set's name while an action is selected selects the sets from the diff --git a/docs/mcp.md b/docs/mcp.md index f2e9074f1a..16cadd2be5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1650,10 +1650,11 @@ already walks Image Trace. Short agent entry points: is one of the format's extensions (`.svg` and `SVG` give `.svg`, `.JPEG` gives `.jpeg`), and otherwise in the format's first extension (`png8` gives `.png`, `template` gives `.vctemplate`). A step without `format` keeps the source file's extension (`.vectorcraft` over data sets). -- Action sets: `ui.actionSet.delete {sets?: [index], all?: [name]}` deletes the Actions panel's sets at these indexes +- Action sets: `ui.actionSet.delete {sets?: [index], ids?: [id]}` deletes the Actions panel's sets at these indexes (0 is the top set) with their actions, by default the current set, and returns `{deleted}`. An index past the last - set is an error, and then no set is deleted. With `all`, the names of every set in the panel, in order, must equal - it exactly; otherwise the command returns an error and deletes no set. A recording into a deleted set stops and keeps no steps; a recording into another set + set is an error, and then no set is deleted. `ids` holds the panel's own set ids, which its question passes: the + sets with these ids are deleted wherever they are now and `sets` is not read; when one of them no longer exists, the + command returns an error and deletes no set. A recording into a deleted set stops and keeps no steps; a recording into another set goes on in that set. The panel's Delete Selection (the trash button and the panel menu's Delete) asks before it runs this for the selected sets, and Shift-click on a set's name selects the sets from the current one to it. Undo does not restore a deleted set. From 18510b77afae83ec1ec614218d9d9ddd7006cb50 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 12:06:47 -0700 Subject: [PATCH 192/260] Appearance: effect.apply reports the new effect's index in the object whose row it names The reply's index came from the last object the effect was added to, while its item came from the first selected object (or the first target for an explicit item). When those objects held different numbers of effects on the row, the reply named no effect of that object. The index is now read from that object's effect list. --- crates/engine/src/cmd/effectcmd.rs | 5 ++--- crates/engine/src/tests/appearance.rs | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 8010931a70..feee6913fb 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -213,16 +213,15 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> { } } } - let mut index = 0; let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", 0, |fx, _| { fx.push(effect.clone()); - index = fx.len() - 1; true })?; // The item the effect landed on in the object whose row the item is (the first selected object - // for the active item, which applies where it fits). + // for the active item, which applies where it fits), and the effect's index in that object. let first = ids.get(item.anchor(s, &ids)).and_then(|id| s.doc().ok()?.doc.node(*id)); let landed = first.and_then(|n| item.effects_item(&n.appearance, C).ok().flatten()); + let index = first.and_then(|n| n.appearance.effects_at(landed)).map_or(0, |fx| fx.len().saturating_sub(1)); Ok(json!({ "ids": ids_json(&ids), "index": index, "item": landed })) } diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index e368711889..e1728c1adb 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -513,6 +513,27 @@ fn edits_change_the_active_row_of_the_first_selected_object() { assert!(!e.contains("internal error"), "{e}"); } +/// `effect.apply`'s reply names the new effect by its index in the object whose row `item` is, +/// also when the objects painted after it already have effects there. +#[test] +fn apply_reports_the_index_in_the_object_whose_row_it_names() { + let mut s = session(); + let (a, b) = reversed_pair(&mut s); + let c = rect(&mut s, 350.0); + run(&mut s, "effect.apply", json!({"effect": "distort.twist", "item": 0})); + // b's red fill row is not shared, so each object's row 0 takes the effect: c's second one. + run(&mut s, "select.set", json!({"ids": [b.0, a.0, c.0]})); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + let r = run(&mut s, "effect.apply", json!({"effect": "distort.twist"})); + assert_eq!(node(&s, c).appearance.items[0].effects().len(), 2); + assert_eq!((r["item"].clone(), r["index"].clone()), (json!(0), json!(0)), "b's row 0 holds one effect"); + // An explicit item is a row of the first target, a, which paints below c. + run(&mut s, "select.set", json!({"ids": [c.0, a.0]})); + let r = run(&mut s, "effect.apply", json!({"effect": "distort.twist", "item": 0})); + assert_eq!(node(&s, c).appearance.items[0].effects().len(), 3); + assert_eq!((r["item"].clone(), r["index"].clone()), (json!(0), json!(1)), "a's row 0 holds two effects"); +} + /// How many steps there are to undo and to redo, and whether the document has unsaved changes. fn history(s: &Session) -> (usize, usize, bool) { let st = s.doc().unwrap(); From ba16468710a17bf4d87a491beb7827694c8a9d9e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 11:40:10 -0700 Subject: [PATCH 193/260] PDF export: a gradient that mixes a spot color with process colors keeps the spot ink A linear or radial gradient whose stops mix a spot color with process colors, or two spot colors, was written in process colors with a warning. It is now written as a DeviceN shading of the process inks its stops use and its spot inks, so each spot ink separates onto its own plate. An off-center midpoint becomes a stop with the inks halfway between its two stops. A gradient that mixes a spot color with RGB or Lab colors is still written without the spot ink, with a warning that says so. --- crates/engine/src/tests/linked_stops.rs | 32 ++++++++++- crates/pdf/src/export/paint.rs | 75 +++++++++++++++++++++++-- docs/target-app-parity.md | 3 +- 3 files changed, 102 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index 2f25cf83c9..ce9478464f 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -1,5 +1,5 @@ //! Gradient swatches and gradient stops linked to global and spot swatches: the recorded links, -//! stops following swatch edits, spot stops on their plate and as Separation shadings in PDF. +//! stops following swatch edits, spot stops on their plate and as Separation and DeviceN shadings in PDF. use serde_json::{Value, json}; use vectorcraft_color::{Color, GradientPaint, GradientStop, Paint}; @@ -133,13 +133,39 @@ fn spot_gradients_export_as_separation_shadings() { assert!(pdf.contains("/ShadingType 2") && pdf.contains("/Separation/Ink/DeviceCMYK"), "an Ink → paper gradient is a Separation shading"); // Its function runs over the tints: 80 % (204 / 255) to 0 %. assert!(pdf.contains("/C0[0.8]/C1[0]"), "the shading's tints"); - // Mixing the spot ink with another colour falls back to process colours, with a warning. + // Mixing the spot ink with an RGB color writes the gradient without the spot ink, with a warning. run(&mut s, "paint.editGradient", json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#00ff00"}]})); let (pdf, warnings) = pdf_of(&s); - assert!(!pdf.contains("/Separation"), "no Separation for a mixed gradient"); + assert!(!pdf.contains("/Separation") && !pdf.contains("/DeviceN"), "no spot ink for a gradient with an RGB stop"); assert!(warnings.iter().any(|w| w.contains("spot")), "{warnings:?}"); } +#[test] +fn spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() { + let (mut s, _) = setup(); + // Ink → process yellow: a DeviceN shading of Yellow and Ink, with no warning. + run(&mut s, "paint.editGradient", json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": {"c": 0, "m": 0, "y": 0.6, "k": 0}}]})); + let (pdf, warnings) = pdf_of(&s); + assert!(pdf.contains("/ShadingType 2") && pdf.contains("/DeviceN[/Yellow/Ink]/DeviceCMYK"), "a DeviceN shading of Yellow and Ink"); + assert!(pdf.contains("/C0[0 1]/C1[0.6 0]"), "the shading's tints: Yellow and Ink"); + assert!(!warnings.iter().any(|w| w.contains("spot")), "{warnings:?}"); + // Two spot inks, with an off-center midpoint: a stop halfway between the two inks. + run(&mut s, "swatch.new", json!({"name": "Leaf", "color": {"c": 1, "m": 0, "y": 1, "k": 0}, "spot": true})); + run( + &mut s, + "paint.editGradient", + json!({"stops": [{"offset": 0, "swatch": "Ink", "midpoint": 30}, {"offset": 1, "swatch": "Leaf", "tint": 50}]}), + ); + let (pdf, warnings) = pdf_of(&s); + assert!(pdf.contains("/DeviceN[/Ink/Leaf]/DeviceCMYK"), "a DeviceN shading of both spot inks"); + let functions: Vec<_> = pdf.match_indices("/C0[").filter_map(|(i, _)| pdf.get(i..i + 32)).collect(); + assert!( + pdf.contains("/C0[1 0]/C1[0.5019608 0.2509804]") && pdf.contains("/C0[0.5019608 0.2509804]/C1[0 0.5019608]"), + "the tints through the midpoint: {functions:?}" + ); + assert!(!warnings.iter().any(|w| w.contains("spot")), "{warnings:?}"); +} + #[test] fn linked_stops_round_trip() { let (mut s, id) = setup(); diff --git a/crates/pdf/src/export/paint.rs b/crates/pdf/src/export/paint.rs index 24a8577974..b7c3034879 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -65,8 +65,8 @@ impl Exporter<'_> { /// The stops of a gradient whose every stop is a tint of one spot ink (or paper white, 0% of /// it) as tints of that ink — a Separation shading — with midpoints as explicit stops (the - /// tint and opacity there are halfway). `None` for other gradients; one that mixes a spot ink - /// with other colours is written in process colours (the PDF writer has no DeviceN). + /// tint and opacity there are halfway). A gradient that mixes a spot ink with other colors + /// gets [`Self::device_n_stops`]. `None` for gradients without a spot ink. fn spot_stops(&mut self, g: &vectorcraft_color::Gradient) -> Option<Vec<(f32, krilla::color::Color, f32)>> { let ink = g.stops.iter().find_map(|s| s.swatch.as_deref().filter(|n| self.doc.swatch(n).is_some_and(|w| w.spot)))?; let paper = |c: &Color| c.to_rgba8(1.0)[..3] == [255; 3]; @@ -80,8 +80,7 @@ impl Exporter<'_> { }) .collect(); let Some(tints) = tints else { - self.warn("gradients mixing a spot color with other colors are exported in process colors"); - return None; + return self.device_n_stops(g); }; let space = self.separation(ink)?; let tint = |t: f32| -> krilla::color::Color { SepColor::new(q(t), space.clone()).into() }; @@ -98,6 +97,74 @@ impl Exporter<'_> { Some(out) } + /// The stops of a gradient that mixes spot inks with process colors or with each other, in + /// a DeviceN space of the process inks the stops use (in CMYK order) and the spot inks (in + /// the order the stops name them), with midpoints as explicit stops (the tints and opacity + /// there are halfway). Paper white adds no ink. `None`, with a warning, when a stop is + /// written in RGB or Lab or the spot inks can't share a DeviceN space; the gradient is then + /// written in the colors of its stops. + fn device_n_stops(&mut self, g: &vectorcraft_color::Gradient) -> Option<Vec<(f32, krilla::color::Color, f32)>> { + use krilla::color::device_n::{Color as DnColor, Colorant, DeviceNSpace, Process}; + let paper = |c: &Color| c.to_rgba8(1.0)[..3] == [255; 3]; + let doc = self.doc; + fn spot_of<'s>(doc: &vectorcraft_doc::Document, s: &'s vectorcraft_color::GradientStop) -> Option<&'s str> { + s.swatch.as_deref().filter(|n| doc.swatch(n).is_some_and(|w| w.spot)) + } + let mut spots: Vec<(String, [f32; 4])> = Vec::new(); + for s in &g.stops { + if let Some(n) = spot_of(doc, s) + && !spots.iter().any(|(m, _)| m == n) + { + spots.push(self.spot_ink(n)?); + } + } + // Each stop's ink coverage: the four process inks, then one tint per spot ink. + let mut inks: Vec<Vec<f32>> = Vec::with_capacity(g.stops.len()); + for s in &g.stops { + let mut v = vec![0.0; 4 + spots.len()]; + match spot_of(doc, s) { + Some(n) => { + let i = spots.iter().position(|(m, _)| m == n)?; + v[4 + i] = s.tint; + } + None if s.swatch.is_none() && paper(&s.color) => {} + None => match self.page_color(&s.color) { + Color::Cmyk { c, m, y, k } => v[..4].copy_from_slice(&[c, m, y, k]), + Color::Gray { k } => v[3] = k, + Color::Rgb { .. } | Color::Lab { .. } => { + self.warn("gradients mixing a spot color with RGB or Lab colors are exported without the spot ink"); + return None; + } + }, + } + inks.push(v); + } + let process: Vec<usize> = (0..4).filter(|&i| inks.iter().any(|v| q(v[i]) > 0)).collect(); + let colorants = process.iter().map(|&i| Colorant::Process(Process::ALL[i])).chain( + spots.iter().map(|(name, f)| Colorant::Spot { name: name.clone(), alternate: cmyk::Color::new(q(f[0]), q(f[1]), q(f[2]), q(f[3])) }), + ); + let Some(space) = DeviceNSpace::new(colorants) else { + self.warn("gradients whose spot inks can't share a DeviceN color space are exported without the spot inks"); + return None; + }; + let color = |v: &[f32]| -> Option<krilla::color::Color> { + let tints = process.iter().map(|&i| q(v[i])).chain(v[4..].iter().map(|&t| q(t))).collect(); + Some(DnColor::new(tints, space.clone())?.into()) + }; + let mut out = vec![]; + for (i, s) in g.stops.iter().enumerate() { + out.push((s.offset, color(&inks[i])?, s.opacity)); + if let Some(n) = g.stops.get(i + 1) + && (s.midpoint - 0.5).abs() > 1e-3 + { + let at = s.offset + (n.offset - s.offset) * s.midpoint; + let half: Vec<f32> = inks[i].iter().zip(&inks[i + 1]).map(|(a, b)| (a + b) / 2.0).collect(); + out.push((at, color(&half)?, (s.opacity + n.opacity) / 2.0)); + } + } + Some(out) + } + /// Warn when `effects` (an object's, a fill's or a stroke's) has a visible raster effect: the /// app renders them to images before export (`vectorcraft_engine::export_pdf`), so the ones /// still here (on `what`) can't be written. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 95c0395a76..6fde1dfbb1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -393,7 +393,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of similar groups, transform nuances (the rotated persistent bounding box is done) | 4–6 | | Drawing tools | 7 | 86% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | -| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | freeform and mixed spot/process gradients in SVG/PDF (exported as stops or process colours), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | +| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | | Strokes, brushes, width profiles | 5 | 90% | the Art brush's Overlap, auto-generated Pattern brush corners and new tile art in Pattern Brush Options (Brush Options for every brush type done), more built-in brush libraries (four generated in code are done), pen pressure on macOS (the windowing layer reports none there), brushes driven by pen tilt, bearing and barrel rotation (6D art pens) | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | @@ -1027,6 +1027,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - PDF export and print composition use the optional shared guarded writer ([pdf-backend.md](pdf-backend.md)); app drawing and output policy and desktop printer submission remain in their existing layers. The shared reader keeps the app-owned import adapter; synthetic tests cover layer and overprint state across windows, long operands, inline images, failed decoding, document limits and incomplete tails. Empty and populated metadata key presence is regression-tested, and CI checks the immutable backend source. Invisible text in a PDF (rendering mode 3, which carries a scanned page's recognized text over the scan) opens as type with no fill or stroke, a run of its own beside visible text on the same line; text that can't come in as type (opened as outlines, Type 3 fonts) is left out with a warning. PDF export, and printing, write characters with no fill or stroke as real text in rendering mode 3, so they draw nothing but stay selectable and searchable, also in PDF/X-1a and PDF/A-2b (#2675, `pdf/src/tests/import_fidelity.rs`, `pdf/src/tests/realtext.rs`). A PDF, or a `.ai` read through its PDF part, whose spot inks have the same values but different names opens with a spot swatch for each ink. The solid fills and strokes of paths and type, and the stops of gradients on paths, link to the swatch of the ink they are painted in, the points of a gradient mesh in one of these inks keep the ink's color, and PDF export writes each of these inks as its own separation (`pdf/src/tests/import_color.rs`). Paint in these inks inside pattern cells, soft masks and type 3 glyphs, and gradients on type in these inks, still import as RGB. Type in one of these inks can also import as RGB when type in another Separation or DeviceN ink is shown with no path drawn between them. + PDF export writes a linear or radial gradient that mixes a spot color with process colors, or two spot colors, as a DeviceN shading of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. A gradient that mixes a spot color with RGB or Lab colors is still written without the spot ink, with a warning (`engine/src/tests/linked_stops.rs`). - `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465). Native documents with a lot of path data (traced or generated art, in layers, symbols or patterns) are saved as compact JSON, about a fifth of the size; small documents stay pretty-printed (#1492). Saving to a network drive on macOS falls back to a plain fsync when the share refuses a full flush (#1625, part of #1620; not confirmed on a real share), and a save still succeeds when a folder refuses the temporary file, the rename over the document or copying permissions: the content is written elsewhere first and copied in, and a failed copy keeps the temporary file and names it (#1649, part of #1620). A document opened by a relative path finds its relatively linked images, and `vectorcraft-cli convert` lists what reading the input left out as `importWarnings` (#1606, fixes #1604). A name typed in the desktop save panel without the file type's extension gets it, and when a file of that name exists, which the panel did not ask about, Save, Save As, Save a Copy, Save as Template, the exports and every other write through a save panel ask before replacing it (dialog `replaceFile`; Cancel writes nothing). A name returned by the desktop save panel with the extension of a format the save does not write has it replaced with the saved format's: Save As of a new document saves `card.ait` and `card.png` as `card.vectorcraft`, and Save as Template saves `card.pdf` as `card.vctemplate`. An extension that names no format stays part of the name (`notes.v2` is saved as `notes.v2.vectorcraft`). From d098d3318852a6fe478b6598fa5fcf8008d434cf Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 10:50:29 -0700 Subject: [PATCH 194/260] Perspective: a stored projection whose determinant overflows is judged on a scaled copy Homography::from_array accepted nine finite numbers only when det().abs() was above 1e-15. With large entries the determinant can be inf - inf, so a valid stored projection was rejected on reading and its type drew flat, or it can overflow to inf, so a projection that cannot be inverted was accepted. When the determinant is not finite, inverse() now inverts a copy divided by a power of two (largest entry between 0.5 and 1), and treats that copy as not invertible when its determinant is at most 1e-15 times the largest of the six products it sums. from_array and the overflow path of conjugated accept such a map only when that inverse exists. Maps with a finite determinant are judged as before. Follows #4912. --- crates/geom/src/projective.rs | 96 ++++++++++++++++++++++++++++++++--- docs/target-app-parity.md | 1 + 2 files changed, 90 insertions(+), 7 deletions(-) diff --git a/crates/geom/src/projective.rs b/crates/geom/src/projective.rs index 77bb513b45..53405233af 100644 --- a/crates/geom/src/projective.rs +++ b/crates/geom/src/projective.rs @@ -31,7 +31,7 @@ impl Homography { return None; } let h = Self([[v[0], v[1], v[2]], [v[3], v[4], v[5]], [v[6], v[7], v[8]]]); - (h.det().abs() > 1e-15).then_some(h) + h.is_invertible().then_some(h) } /// The nine row-major numbers. @@ -60,14 +60,58 @@ impl Homography { + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]) } - /// Inverse; `None` when the map is not invertible or its inverse has an entry that is not - /// finite. - pub fn inverse(&self) -> Option<Self> { - let m = &self.0; + /// Whether the map is invertible: the magnitude of its determinant is above 1e-15, or, when the + /// determinant is not finite, [`Self::inverse`] gives one. + fn is_invertible(&self) -> bool { let d = self.det(); - if d.abs() < 1e-15 || !d.is_finite() { + if d.is_finite() { + return d.abs() > 1e-15; + } + self.inverse().is_some() + } + + /// The same map with every entry divided by one power of two, the smallest above every entry's + /// magnitude (so its largest entry is at least 0.5 and below 1). `None` when every entry is 0 + /// or one is not finite. + fn scaled(&self) -> Option<Self> { + if !self.is_finite() { return None; } + let e = self.0.iter().flatten().filter(|v| **v != 0.0).map(|v| frexp(*v).1).max()?; + Some(Self(self.0.map(|row| row.map(|v| ldexp(v, -e))))) + } + + /// Inverse; `None` when the map is not invertible or its inverse has an entry that is not + /// finite. When the determinant is not finite, this is the inverse of [`Self::scaled`] (the + /// exact inverse multiplied by one power of two, which is the same map), and that copy counts + /// as not invertible when the magnitude of its determinant is at most 1e-15 times that of the largest + /// of the six products the determinant sums. + pub fn inverse(&self) -> Option<Self> { + let d = self.det(); + let (h, d) = if d.is_finite() { + if d.abs() < 1e-15 { + return None; + } + (*self, d) + } else { + let s = self.scaled()?; + let m = &s.0; + let terms = [ + m[0][0] * m[1][1] * m[2][2], + m[0][0] * m[1][2] * m[2][1], + m[0][1] * m[1][0] * m[2][2], + m[0][1] * m[1][2] * m[2][0], + m[0][2] * m[1][0] * m[2][1], + m[0][2] * m[1][1] * m[2][0], + ]; + let largest = terms.iter().fold(0.0_f64, |k, v| k.max(v.abs())); + let d = s.det(); + if d.abs() <= 1e-15 * largest { + return None; + } + (s, d) + }; + let m = &h.0; let c = |r0: usize, c0: usize, r1: usize, c1: usize| m[r0][c0] * m[r1][c1] - m[r0][c1] * m[r1][c0]; let adj = [ [c(1, 1, 2, 2), -c(0, 1, 2, 2), c(0, 1, 1, 2)], @@ -143,7 +187,7 @@ impl Homography { return None; } let c = Self(c.map(|row| row.map(|v| v / k))); - (c.is_finite() && c.det().abs() > 1e-15).then_some(c) + (c.is_finite() && c.is_invertible()).then_some(c) } fn is_finite(&self) -> bool { @@ -274,6 +318,44 @@ mod tests { assert!(h().inverse().is_some()); } + #[test] + fn a_determinant_that_overflows_is_taken_at_a_smaller_scale() { + // (x, y) ↦ (x + 1, y) / (x + 2) with every entry multiplied by 1e200: the determinant is + // inf − inf, though the map is invertible. + let big = Homography([[1e200, 0.0, 1e200], [0.0, 1e200, 0.0], [1e200, 0.0, 2e200]]); + assert!(big.det().is_nan()); + assert_eq!(Homography::from_array(big.to_array()), Some(big)); + let inv = big.inverse().unwrap(); + for p in [Point::new(3.0, -2.0), Point::new(-1.5, 4.0)] { + assert!(inv.apply(big.apply(p).unwrap()).unwrap().distance(p) < 1e-9); + } + // A scale by 1e500: the determinant is inf, but scaled to a largest entry below 1 the + // w row is 0, and no point maps to a finite page point except the origin. + let flat = Homography([[1e300, 0.0, 0.0], [0.0, 1e300, 0.0], [0.0, 0.0, 1e-200]]); + assert!(flat.det().is_infinite()); + assert_eq!(Homography::from_array(flat.to_array()), None); + assert_eq!(flat.inverse(), None); + // Two equal rows with large entries. + let twice = Homography([[1e200, 1e200, 0.0], [1e200, 1e200, 0.0], [0.0, 0.0, 1e200]]); + assert_eq!(Homography::from_array(twice.to_array()), None); + assert_eq!(twice.inverse(), None); + // (x, y) ↦ 1e200·(x + 1, y) / (x + 2) seen through a scale by 1e10: the product + // overflows, and the determinant of the result at a w row of 1 is inf − inf. + let far = Homography([[1e300, 0.0, 1e300], [0.0, 1e300, 0.0], [1e100, 0.0, 2e100]]); + let t = Affine::scale(1e10); + let c = far.conjugated(t).unwrap(); + assert!(c.det().is_nan()); + assert_eq!(Homography::from_array(c.to_array()), Some(c)); + for p in [Point::new(3.0, -2.0), Point::new(0.5, 7.0)] { + let want = t * far.apply(p).unwrap(); + assert!(c.apply(t * p).unwrap().distance(want) <= 1e-9 * want.to_vec2().hypot(), "{c:?}"); + } + // A determinant that does not overflow is judged as it is. + assert!(Homography::from_array([1e-6, 0.0, 0.0, 0.0, 1e-6, 0.0, 0.0, 0.0, 1e-6]).is_none()); + assert!(Homography::from_array([f64::NAN; 9]).is_none()); + assert!(Homography::from_array([0.0; 9]).is_none()); + } + #[test] fn a_product_that_overflows_is_none() { // Each factor is finite and invertible, but the product's first entry is 1e400. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 914b7e2a57..356929cdf8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1006,6 +1006,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur All Artwork Above and Other Layers (Object › Lock and Object › Hide), Transform Each, Rearrange All Artboards, the width point and width profile commands, Liquify, Puppet Warp, Define Perspective Grid, Attach to Active Plane, Release with Perspective, moves and transforms in perspective, Move Plane and Move Plane to Match Object record no undo step when they change nothing. Move in Perspective (its copy, perpendicular and Snap to Grid choices), Transform in Perspective (its copy), Nudge in Perspective (its ×10 and copy), Draw in Perspective (Snap to Grid), Define Perspective Grid (its reproject choice), Show Perspective Grid, Width Point (Adjust Adjoining Width Points), Liquify (its pen pressure, Simplify and Affect choices) and Puppet Warp (its pins' rest shape) refuse a value other than true, false or null, such as "true", and leave the document and its undo history as they were. Moves and transforms in perspective and Define Perspective Grid with reproject return an error, and leave the document and its undo history as they were, when the projection they would give type or a symbol instance in perspective has a number too large to store. Object › Perspective › Edit Text returns an error, and does not enter isolation mode, when the type cannot be shown flat where it is drawn: when part of it crosses the horizon, or when that view's projection has a number too large to store. Regressions: `a_product_that_overflows_is_none` in `crates/geom/src/projective.rs`, and `moving_type_whose_projection_would_overflow_is_refused` and `edit_text_whose_flat_view_would_overflow_is_refused` in `crates/engine/src/tests/persp_text.rs`. + A stored projection with numbers so large that its determinant overflows is judged on a copy divided by a power of two: an invertible one is read back when the document opens, and one that cannot be inverted, such as one whose bottom row is 0 at that scale, is not. Regression: `a_determinant_that_overflows_is_taken_at_a_smaller_scale` in `crates/geom/src/projective.rs`. Create Object Mosaic (its columns and rows), Transform Each (its reference point and Random seed) and Rearrange All Artboards (its columns) refuse a fraction, a negative number or a string, such as 2.5, -1 or "4"; 4.0 counts as 4. Move, Rotate, Scale, Reflect, Shear, Transform Again, Nudge and the Transform panel's values (their copy, Scale Strokes & Effects, Scale Corners, Transform Patterns, Transform Objects and area type options), Align, Distribute and Distribute Spacing (Transform Patterns), Object Properties (visible, locked, Isolate Blending and Opacity & Mask Define Knockout Shape) and Live Shape Properties (Invert Pie, Make Sides Equal and relative rounding) refuse a value other than true, false or null, such as "false", and leave the document as it was. Object Properties (its opacity), Live Shape Properties (corner radius and polygon sides), the Transform panel's reference point and Align, Distribute and Distribute Spacing to an artboard (the artboard's number) refuse a value other than a number or null, such as "50", and leave the document as it was. From 3c95ce529ec48bd8b2822955f2712e4b8966fd2d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 11:50:46 -0700 Subject: [PATCH 195/260] Docs: list the PDF gradients that still drop the spot ink The Feature areas row still listed mixed spot/process gradients as missing in PDF. It and the detailed row now name SVG, plus PDF gradients that mix a spot color with RGB or Lab stops, which are still written without the spot ink. --- docs/target-app-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6fde1dfbb1..9b987e7899 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -123,7 +123,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939); the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies and excluding a match with Shift-click, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522) | -| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | 30.0's gradient additions are done (dither, perceptual blending, presets); freeform and mixed spot/process gradients in SVG/PDF | 4–7 | estimated; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged | +| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, and PDF gradients mixing a spot color with RGB or Lab stops | 4–7 | estimated; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (four generated libraries, User Defined, Other Library…, Save Brushes); remaining: Art brush Overlap, Pattern brush auto corners, pen pressure on macOS, tilt/bearing/rotation | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | @@ -393,7 +393,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of similar groups, transform nuances (the rotated persistent bounding box is done) | 4–6 | | Drawing tools | 7 | 86% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | -| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | +| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | | Strokes, brushes, width profiles | 5 | 90% | the Art brush's Overlap, auto-generated Pattern brush corners and new tile art in Pattern Brush Options (Brush Options for every brush type done), more built-in brush libraries (four generated in code are done), pen pressure on macOS (the windowing layer reports none there), brushes driven by pen tilt, bearing and barrel rotation (6D art pens) | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | From 49cded55da071cdcce79a5398ed5b835aa4c0bb2 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 11:51:33 -0700 Subject: [PATCH 196/260] Accessibility: Tab no longer stops on a dialog's backdrop; tests check a reachable control The backdrop behind a modal dialog took clicks with Sense::click(), which egui makes focusable, so Tab stopped on it. It now senses clicks without taking the keyboard focus. The Tab tests now check that Tab reaches a known control in each region instead of only that some widget took the focus: the title bar's three caption buttons, a control inside each dialog, a Tools panel button and a floating strip's Put back in the toolbar button, and the isolation bar's back button. The dialog test also checks that Tab skips the backdrop. --- crates/ui-egui/src/chrome/tests.rs | 8 +++++--- crates/ui-egui/src/dialogs/modal.rs | 3 ++- crates/ui-egui/src/dialogs/tests_modal.rs | 9 ++++++++- crates/ui-egui/src/titlebar.rs | 4 +++- crates/ui-egui/src/toolbar/tests.rs | 9 ++++++++- 5 files changed, 26 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index e021354af6..f32d3a9445 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -995,10 +995,12 @@ fn tab_skips_the_isolation_bars_background() { }; frame(vec![]); let bar = egui::Rect::from_min_size(screen.min, egui::vec2(screen.width(), 24.0)); - let bar = ctx.viewport(|vp| vp.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).find(|w| w.rect == bar).map(|w| w.id)); - let bar = bar.expect("the isolation bar"); + let back = egui::Rect::from_min_size(bar.min + egui::vec2(6.0, 3.0), egui::vec2(18.0, 18.0)); + let widget = + |rect: egui::Rect| ctx.viewport(|vp| vp.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).find(|w| w.rect == rect).map(|w| w.id)); + let (bar, back) = (widget(bar).expect("the isolation bar"), widget(back).expect("the back button")); let stops = crate::widgets::accessibility_tests::tab_stops(&ctx, 10, frame); - assert!(!stops.is_empty(), "Tab reaches the back button and the breadcrumbs"); + assert!(stops.contains(&back), "Tab reaches the back button: {stops:?}"); assert!(!stops.contains(&bar), "{stops:?}"); } diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index 0303db8c6f..6d9f91df33 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -21,7 +21,8 @@ pub(crate) fn show_at<R>(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 let dim = backdrop(); egui::Area::new(dim.id).order(dim.order).fixed_pos(egui::Pos2::ZERO).show(ctx, |ui| { // Modal, but the canvas isn't dimmed so previews stay readable (as in the reference app). - ui.allocate_rect(ctx.content_rect(), egui::Sense::click()); + // Not focusable (`Sense::click()` is): Tab goes through the dialog's controls, not the backdrop. + ui.allocate_rect(ctx.content_rect(), egui::Sense::CLICK); }); let shown = egui::Window::new(title) .id(id) diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index 80e403d83a..c2b1daf06c 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -133,10 +133,17 @@ fn tab_skips_the_band_that_moves_a_dialog() { settle(&ctx, &mut app); let band = modal::handle(id); assert!(ctx.read_response(band).is_some(), "{name}: the band is drawn"); + let window = ctx.memory(|m| m.area_rect(id)).unwrap_or_else(|| panic!("{name}: the window is drawn")); let stops = crate::widgets::accessibility_tests::tab_stops(&ctx, 30, |events| { frame(&ctx, &mut app, events); }); - assert!(!stops.is_empty(), "{name}: Tab reaches the dialog's controls"); + let inside = |s: &egui::Id| ctx.read_response(*s).is_some_and(|r| r.rect.is_positive() && window.contains_rect(r.rect)); + assert!(stops.iter().any(inside), "{name}: Tab reaches a control in the dialog: {stops:?}"); + let backdrop: Vec<egui::Id> = ctx.viewport(|vp| { + vp.prev_pass.widgets.layers().filter(|(l, _)| **l == modal::backdrop()).flat_map(|(_, w)| w.iter()).map(|w| w.id).collect() + }); + assert!(!backdrop.is_empty(), "{name}: the backdrop is drawn"); + assert!(!stops.iter().any(|id| backdrop.contains(id)), "{name}: Tab stops on the backdrop: {stops:?}"); assert!(!stops.contains(&band), "{name}: {stops:?}"); } } diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/titlebar.rs index 5f2a128760..5e151e0c55 100644 --- a/crates/ui-egui/src/titlebar.rs +++ b/crates/ui-egui/src/titlebar.rs @@ -403,7 +403,9 @@ mod tests { let stops = crate::widgets::accessibility_tests::tab_stops(&ctx, 40, |events| { w.frame(events); }); - assert!(!stops.is_empty(), "Tab reaches the bar's controls"); + for c in CAPTIONS { + assert!(stops.contains(&caption_id(c)), "Tab reaches the {c:?} button: {stops:?}"); + } let regions: Vec<Id> = std::iter::once(Id::unique("titlebar-drag")).chain((0..8usize).map(|i| Id::unique(("titlebar-resize", i)))).collect(); assert!(!stops.iter().any(|id| regions.contains(id)), "{stops:?}"); } diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 0feb1cabdb..b0f8ad29ea 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -1030,8 +1030,15 @@ fn tab_skips_the_grip_and_the_tear_off_bars() { .map(|w| w.id) }); let grip = grip.expect("the Tools panel's grip"); + // The Tools panel's tool buttons: 36 by 29 pt. + let buttons: Vec<egui::Id> = ctx.viewport(|vp| { + vp.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).filter(|w| w.rect.size() == vec2(36.0, PITCH - 1.0)).map(|w| w.id).collect() + }); + assert!(!buttons.is_empty(), "the Tools panel's buttons are drawn"); let stops = crate::widgets::accessibility_tests::tab_stops(&ctx, 120, frame); - assert!(!stops.is_empty(), "Tab reaches the tool buttons"); + assert!(stops.iter().any(|id| buttons.contains(id)), "Tab reaches the Tools panel's buttons: {stops:?}"); + let close = egui::Id::unique(("tool-flyout-close", "polygon")); + assert!(stops.contains(&close), "Tab reaches the strip's Put back in the toolbar button: {stops:?}"); for (name, id) in [("the grip", grip), ("the flyout's bar", bar_id("rectangle")), ("the strip's bar", bar_id("polygon"))] { assert!(!stops.contains(&id), "Tab stops on {name}: {stops:?}"); } From bbcb886a40f7d448b2dda9bb741b7c272adeee03 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 11:49:30 -0700 Subject: [PATCH 197/260] Perspective: a stored projection whose determinant overflows reads back at a w row of 1 A stored projection whose determinant is not finite is read back as the same map divided by the largest magnitude in its w row, the scale the overflow branch of conjugated already uses, so points that overflowed at the stored scale draw: the identity with every entry 1e308 maps (2, 2) to (2, 2). The overflow branch of inverse scales the map so that the largest of the products its determinant sums is near 1, so a map with large entries and a small w row, such as a scale by 1e305 with a move by -3.9e307, is still inverted and read back. The two overflow tests in persp_text.rs build their stored projections with a w row of 1, so they still overflow after the read-back. --- crates/engine/src/tests/persp_text.rs | 16 ++++--- crates/geom/src/projective.rs | 65 +++++++++++++++++++++++---- docs/target-app-parity.md | 2 +- 3 files changed, 66 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/tests/persp_text.rs b/crates/engine/src/tests/persp_text.rs index ae447915f6..b5dc5e7a53 100644 --- a/crates/engine/src/tests/persp_text.rs +++ b/crates/engine/src/tests/persp_text.rs @@ -119,13 +119,15 @@ fn moving_type_whose_projection_would_overflow_is_refused() { let id = persp_text(&mut s); let NodeKind::Text(t) = &node(&s, id).kind else { panic!("type") }; let flat = t.bounds().unwrap(); - // A stored projection that draws the type flat where it is, with every entry scaled by `k`: a - // document can hold it (its entries are finite) and the type draws, but its product with a - // scale by 2 in perspective overflows. + // A stored projection that maps each point p of the type to k·(p − 0.9·q), with q its top-left + // corner: a document can hold it (its entries are finite, and its w row is already 1) and the + // type draws, but its product with a scale by 2 in perspective overflows, since its move, + // 0.9·k·q, is larger than any point it draws. let step = grid(&s).transform_map(Plane::Right, 0.0, vectorcraft_geom::Affine::scale(2.0), 0.0).unwrap(); + let q = flat.origin(); let scaled = |e: i32| { let k = 2f64.powf(f64::from(e) / 16.0); - vectorcraft_geom::Homography([[k, 0.0, 0.0], [0.0, k, 0.0], [0.0, 0.0, k]]) + vectorcraft_geom::Homography([[k, 0.0, -0.9 * k * q.x], [0.0, k, -0.9 * k * q.y], [0.0, 0.0, 1.0]]) }; let finite = |m: &vectorcraft_geom::Homography| m.to_array().iter().all(|v| v.is_finite()); let draws = |m: &vectorcraft_geom::Homography| { @@ -180,12 +182,12 @@ fn edit_text_whose_flat_view_would_overflow_is_refused() { let id = persp_text(&mut s); let NodeKind::Text(t) = &node(&s, id).kind else { panic!("type") }; let flat = t.bounds().unwrap(); - // A stored projection that draws the type 4 times its size, with every entry scaled by `k`: a - // document can hold it and the type draws, but the projection that shows it flat where it is + // A stored projection that draws the type `4k` times its size: a document can hold it (its w + // row is already 1) and the type draws, but the projection that shows it flat where it is // drawn overflows. let scaled = |e: i32| { let k = 2f64.powf(f64::from(e) / 16.0); - vectorcraft_geom::Homography([[4.0 * k, 0.0, 0.0], [0.0, 4.0 * k, 0.0], [0.0, 0.0, k]]) + vectorcraft_geom::Homography([[4.0 * k, 0.0, 0.0], [0.0, 4.0 * k, 0.0], [0.0, 0.0, 1.0]]) }; let overflows = |m: &vectorcraft_geom::Homography| { let Some(drawn) = m.map_rect_bbox(flat) else { return false }; diff --git a/crates/geom/src/projective.rs b/crates/geom/src/projective.rs index 53405233af..80758d3bab 100644 --- a/crates/geom/src/projective.rs +++ b/crates/geom/src/projective.rs @@ -25,13 +25,23 @@ impl Homography { } /// From nine row-major numbers (as stored in documents); `None` unless all are finite and the - /// map is invertible. + /// map is invertible. When the determinant is not finite, this is the same map divided by the + /// largest magnitude in its `w` row (so that row's largest entry is 1), and `None` when that + /// copy has an entry that is not finite or is not invertible. pub fn from_array(v: [f64; 9]) -> Option<Self> { if v.iter().any(|x| !x.is_finite()) { return None; } let h = Self([[v[0], v[1], v[2]], [v[3], v[4], v[5]], [v[6], v[7], v[8]]]); - h.is_invertible().then_some(h) + if h.det().is_finite() { + return h.is_invertible().then_some(h); + } + let k = h.0[2].iter().fold(0.0_f64, |k, v| k.max(v.abs())); + if k <= 0.0 || !h.is_invertible() { + return None; + } + let c = Self(h.0.map(|row| row.map(|v| v / k))); + (c.is_finite() && c.is_invertible()).then_some(c) } /// The nine row-major numbers. @@ -70,14 +80,23 @@ impl Homography { self.inverse().is_some() } - /// The same map with every entry divided by one power of two, the smallest above every entry's - /// magnitude (so its largest entry is at least 0.5 and below 1). `None` when every entry is 0 - /// or one is not finite. + /// The same map with every entry divided by one power of two, chosen so that the largest of the + /// six products its determinant sums is at least 1/8 and below 4. `None` when every one of + /// those products is 0 or an entry is not finite. fn scaled(&self) -> Option<Self> { if !self.is_finite() { return None; } - let e = self.0.iter().flatten().filter(|v| **v != 0.0).map(|v| frexp(*v).1).max()?; + let f = self.0.map(|row| row.map(frexp)); + // The columns each of the six products takes from rows 0, 1 and 2. + let cols = [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]; + let e = cols + .iter() + .map(|&(a, b, c)| (f[0][a], f[1][b], f[2][c])) + .filter(|(a, b, c)| a.0 * b.0 * c.0 != 0.0) + .map(|(a, b, c)| a.1 + b.1 + c.1) + .max()?; + let e = e.div_euclid(3); Some(Self(self.0.map(|row| row.map(|v| ldexp(v, -e))))) } @@ -324,13 +343,41 @@ mod tests { // inf − inf, though the map is invertible. let big = Homography([[1e200, 0.0, 1e200], [0.0, 1e200, 0.0], [1e200, 0.0, 2e200]]); assert!(big.det().is_nan()); - assert_eq!(Homography::from_array(big.to_array()), Some(big)); + // Read back as the same map with a w row whose largest entry is 1. + let read = Homography::from_array(big.to_array()).unwrap(); + assert_eq!(read, Homography([[0.5, 0.0, 0.5], [0.0, 0.5, 0.0], [0.5, 0.0, 1.0]])); + assert_eq!(Homography::from_array(read.to_array()), Some(read)); let inv = big.inverse().unwrap(); for p in [Point::new(3.0, -2.0), Point::new(-1.5, 4.0)] { + assert!(read.apply(p).unwrap().distance(big.apply(p).unwrap()) < 1e-12); assert!(inv.apply(big.apply(p).unwrap()).unwrap().distance(p) < 1e-9); } - // A scale by 1e500: the determinant is inf, but scaled to a largest entry below 1 the - // w row is 0, and no point maps to a finite page point except the origin. + // The identity with every entry 1e308: stored as it is, (2, 2) overflows to 2e308, but the + // map read back draws it at (2, 2). + let wide = Homography([[1e308, 0.0, 0.0], [0.0, 1e308, 0.0], [0.0, 0.0, 1e308]]); + assert_eq!(wide.apply(Point::new(2.0, 2.0)), None); + let read = Homography::from_array(wide.to_array()).unwrap(); + assert_eq!(read.apply(Point::new(2.0, 2.0)), Some(Point::new(2.0, 2.0))); + // A large map whose w row is 1e-205 times its largest entry: read back at a w row of 1, + // its points are in front of the horizon and draw. + let low = Homography([[1e300, 0.0, 1e305], [0.0, 1e300, 0.0], [1e90, 0.0, 1e100]]); + assert!(low.det().is_nan()); + let read = Homography::from_array(low.to_array()).unwrap(); + assert_eq!(Homography::from_array(read.to_array()), Some(read)); + let p = Point::new(1.0, 1.0); + let want = Point::new((1e200 + 1e205) / (1.0 + 1e-10), 1e200 / (1.0 + 1e-10)); + assert!(read.apply(p).unwrap().distance(want) <= 1e-9 * want.to_vec2().hypot()); + // A scale by 1e305 and a move by -3.9e307 with a w row of 1: the determinant is inf, and + // the inverse is a scale by 1e-305 and a move by 390. + let moved = Homography([[1e305, 0.0, -3.9e307], [0.0, 1e305, -3.2e307], [0.0, 0.0, 1.0]]); + assert!(moved.det().is_infinite()); + assert_eq!(Homography::from_array(moved.to_array()), Some(moved)); + let inv = moved.inverse().unwrap(); + for p in [Point::new(400.0, 330.0), Point::new(500.0, 400.0)] { + assert!(inv.apply(moved.apply(p).unwrap()).unwrap().distance(p) < 1e-9); + } + // A scale by 1e500: the determinant is inf, but scaled so that its products are near 1 + // the w row is 0, and no point maps to a finite page point except the origin. let flat = Homography([[1e300, 0.0, 0.0], [0.0, 1e300, 0.0], [0.0, 0.0, 1e-200]]); assert!(flat.det().is_infinite()); assert_eq!(Homography::from_array(flat.to_array()), None); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 356929cdf8..95c0395a76 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1006,7 +1006,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur All Artwork Above and Other Layers (Object › Lock and Object › Hide), Transform Each, Rearrange All Artboards, the width point and width profile commands, Liquify, Puppet Warp, Define Perspective Grid, Attach to Active Plane, Release with Perspective, moves and transforms in perspective, Move Plane and Move Plane to Match Object record no undo step when they change nothing. Move in Perspective (its copy, perpendicular and Snap to Grid choices), Transform in Perspective (its copy), Nudge in Perspective (its ×10 and copy), Draw in Perspective (Snap to Grid), Define Perspective Grid (its reproject choice), Show Perspective Grid, Width Point (Adjust Adjoining Width Points), Liquify (its pen pressure, Simplify and Affect choices) and Puppet Warp (its pins' rest shape) refuse a value other than true, false or null, such as "true", and leave the document and its undo history as they were. Moves and transforms in perspective and Define Perspective Grid with reproject return an error, and leave the document and its undo history as they were, when the projection they would give type or a symbol instance in perspective has a number too large to store. Object › Perspective › Edit Text returns an error, and does not enter isolation mode, when the type cannot be shown flat where it is drawn: when part of it crosses the horizon, or when that view's projection has a number too large to store. Regressions: `a_product_that_overflows_is_none` in `crates/geom/src/projective.rs`, and `moving_type_whose_projection_would_overflow_is_refused` and `edit_text_whose_flat_view_would_overflow_is_refused` in `crates/engine/src/tests/persp_text.rs`. - A stored projection with numbers so large that its determinant overflows is judged on a copy divided by a power of two: an invertible one is read back when the document opens, and one that cannot be inverted, such as one whose bottom row is 0 at that scale, is not. Regression: `a_determinant_that_overflows_is_taken_at_a_smaller_scale` in `crates/geom/src/projective.rs`. + A stored projection with numbers so large that its determinant overflows is judged on a copy divided by a power of two: an invertible one is read back when the document opens as the same map at a smaller scale (divided by the largest number in its bottom row), so points that overflowed at the stored scale draw, and one that cannot be inverted, such as one whose bottom row is 0 at that scale, is not. Regression: `a_determinant_that_overflows_is_taken_at_a_smaller_scale` in `crates/geom/src/projective.rs`. Create Object Mosaic (its columns and rows), Transform Each (its reference point and Random seed) and Rearrange All Artboards (its columns) refuse a fraction, a negative number or a string, such as 2.5, -1 or "4"; 4.0 counts as 4. Move, Rotate, Scale, Reflect, Shear, Transform Again, Nudge and the Transform panel's values (their copy, Scale Strokes & Effects, Scale Corners, Transform Patterns, Transform Objects and area type options), Align, Distribute and Distribute Spacing (Transform Patterns), Object Properties (visible, locked, Isolate Blending and Opacity & Mask Define Knockout Shape) and Live Shape Properties (Invert Pie, Make Sides Equal and relative rounding) refuse a value other than true, false or null, such as "false", and leave the document as it was. Object Properties (its opacity), Live Shape Properties (corner radius and polygon sides), the Transform panel's reference point and Align, Distribute and Distribute Spacing to an artboard (the artboard's number) refuse a value other than a number or null, such as "50", and leave the document as it was. From 3f5c6f3b5b6f3bc57e0a7c72efb9da9769108cba Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 11:59:51 -0700 Subject: [PATCH 198/260] Fix #3826: the toolbar's Gradient chip lines up with Color and None Filled rectangles are drawn on whole pixels, but the gradient chip is a mesh, which was drawn at its exact position. At a fractional position or display scale the Gradient button under the Fill/Stroke proxy sat up to half a pixel off the Color and None buttons beside it. gradient_chip now rounds its rect to pixels first, which also lines it up wherever else a gradient chip sits next to a color chip. --- crates/ui-egui/src/widgets.rs | 37 +++++++++++++++++++++++++++++ crates/ui-egui/src/widgets/chips.rs | 5 +++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 5b2773259d..e1e83995a3 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -509,6 +509,43 @@ mod gradient_chip_tests { assert_eq!(colors[2 * 5 + 2], Color32::WHITE); assert_eq!(colors[0], Color32::BLACK); } + + /// At a position and display scale that fall between pixels, the gradient chip covers the same + /// pixel rows as a colour or None chip beside it (#3826). Filled rectangles are drawn on whole + /// pixels, so the toolbar's Gradient button sat up to half a pixel off its neighbors. + #[test] + fn gradient_chip_lines_up_with_a_solid_chip() { + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(1.5); + // Without anti-aliasing, a filled rectangle's mesh is exactly the rectangle it fills. + ctx.tessellation_options_mut(|o| o.feathering = false); + let chip = |x: f32| Rect::from_min_size(pos2(x, 40.3), vec2(11.0, 11.0)); + let mut shapes = Vec::new(); + for _ in 0..2 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + paint_chip(ui, chip(10.2), &Paint::solid(Color::BLACK)); + gradient_chip(ui, chip(23.2), &paint(GradientKind::Linear, 0.0)); + }); + out.textures_delta.clear(); + assert_eq!(out.pixels_per_point, 1.5); + shapes = out.shapes; + } + let bounds = |shape: egui::epaint::ClippedShape| { + let mut r = Rect::NOTHING; + for p in ctx.tessellate(vec![shape], 1.5) { + if let egui::epaint::Primitive::Mesh(m) = p.primitive { + m.vertices.iter().for_each(|v| r.extend_with(v.pos)); + } + } + r + }; + let n = shapes.len(); + assert!(n >= 2, "{n} shapes"); + let gradient = bounds(shapes.remove(n - 1)); + let solid = bounds(shapes.remove(n - 2)); + assert_eq!((gradient.top(), gradient.bottom()), (solid.top(), solid.bottom()), "gradient {gradient:?}, solid {solid:?}"); + assert_eq!(gradient, egui::emath::GuiRounding::round_to_pixels(chip(23.2), 1.5)); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/widgets/chips.rs b/crates/ui-egui/src/widgets/chips.rs index a215b3ee8b..520b8d2437 100644 --- a/crates/ui-egui/src/widgets/chips.rs +++ b/crates/ui-egui/src/widgets/chips.rs @@ -25,8 +25,11 @@ pub fn paint_chip(ui: &Ui, rect: Rect, paint: &Paint) { } /// Draw a gradient preview into `rect`, laid out as the gradient would be on an object of that -/// shape: linear along its angle, radial from the centre, freeform from its colour points. +/// shape: linear along its angle, radial from the centre, freeform from its colour points. The +/// rect is rounded to whole pixels, as filled rectangles are when drawn, so the chip lines up with +/// a colour chip beside it (#3826). pub fn gradient_chip(ui: &Ui, rect: Rect, gradient: &vectorcraft_color::GradientPaint) { + let rect = egui::emath::GuiRounding::round_to_pixels(rect, ui.pixels_per_point()); if !(rect.width() > 0.0 && rect.height() > 0.0) { return; } From f66b583b5b0a7ceb559df7c3e00a3013117b28f1 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 12:51:05 -0700 Subject: [PATCH 199/260] Tests: mixed spot gradients export as DeviceN shadings when radial or in a Lab ink - A radial gradient from a spot swatch to a CMYK color is written as a DeviceN shading (ShadingType 3) of Yellow and the spot ink. - A Lab spot color used as a flat fill and in a mixed gradient is written as one Separation space with the Lab alternate, which the DeviceN space names under /Colorants. - docs/roadmap.md lists the gradients that still export without the spot ink: mixed spot/process gradients in SVG and PDF gradients with RGB or Lab stops. docs/target-app-parity.md also notes that a Perceptual gradient is written to PDF as an image. --- crates/engine/src/tests/labspots.rs | 24 ++++++++++++++++++++++++ crates/engine/src/tests/linked_stops.rs | 14 ++++++++++++++ docs/roadmap.md | 4 ++-- docs/target-app-parity.md | 2 +- 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/labspots.rs b/crates/engine/src/tests/labspots.rs index 2064118888..358a1e606f 100644 --- a/crates/engine/src/tests/labspots.rs +++ b/crates/engine/src/tests/labspots.rs @@ -202,3 +202,27 @@ fn lab_spots_export_with_a_lab_alternate() { assert!(text.contains("/Separation/Lab#20Ink/DeviceCMYK") && !text.contains("/Lab<<")); assert_xref_valid(&pdf); } + +#[test] +fn lab_spots_in_device_n_gradients_keep_one_alternate() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let (mut s, _) = lab_ink(); + let g = NodeId(run(&mut s, "shape.rectangle", json!({"x": 50, "y": 10, "width": 30, "height": 30}))["id"].as_u64().unwrap()); + run( + &mut s, + "paint.setFill", + json!({"ids": [g.0], "gradient": {"stops": [{"offset": 0, "swatch": "Lab Ink"}, {"offset": 1, "color": {"c": 0, "m": 0, "y": 0.6, "k": 0}}]}}), + ); + let pdf = pdf_bytes(&s); + let text = String::from_utf8_lossy(&pdf); + // One Separation space for the ink, with the Lab alternate: the flat fill paints in it, and the + // gradient's DeviceN space names it as the ink's colorant. + assert_eq!(text.matches("[/Separation/Lab#20Ink").count(), 1, "one Separation space for the ink"); + assert!(!text.contains("/Separation/Lab#20Ink/DeviceCMYK"), "no CMYK Separation space for the ink"); + let at = text.find("[/Separation/Lab#20Ink[/Lab<<").expect("the ink's Lab Separation space"); + let obj = text[..at].trim_end().strip_suffix("obj").and_then(|h| h.trim_end().rsplit('\n').next()).expect("the space's object header"); + let id = obj.split_whitespace().next().expect("the space's object number"); + assert!(text.contains("/DeviceN[/Yellow/Lab#20Ink]"), "a DeviceN shading of Yellow and the ink"); + assert!(text.contains(&format!("/Colorants<</Lab#20Ink {id} 0 R>>")), "the DeviceN space's colorant is the ink's Lab Separation space"); + assert_xref_valid(&pdf); +} diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index ce9478464f..33c622ec7e 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -166,6 +166,20 @@ fn spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() { assert!(!warnings.iter().any(|w| w.contains("spot")), "{warnings:?}"); } +#[test] +fn radial_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() { + let (mut s, _) = setup(); + run( + &mut s, + "paint.editGradient", + json!({"kind": "radial", "stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": {"c": 0, "m": 0, "y": 0.6, "k": 0}}]}), + ); + let (pdf, warnings) = pdf_of(&s); + assert!(pdf.contains("/ShadingType 3") && pdf.contains("/DeviceN[/Yellow/Ink]/DeviceCMYK"), "a radial DeviceN shading of Yellow and Ink"); + assert!(pdf.contains("/C0[0 1]/C1[0.6 0]"), "the shading's tints: Yellow and Ink"); + assert!(!warnings.iter().any(|w| w.contains("spot")), "{warnings:?}"); +} + #[test] fn linked_stops_round_trip() { let (mut s, id) = setup(); diff --git a/docs/roadmap.md b/docs/roadmap.md index 5f6245138e..979eb11214 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -86,10 +86,10 @@ Checked 2026-10-10 from the code, tests and open issues; no workflow fails, so V | M0 | Skeleton + vertical slice | ✅ done | — | | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537); no View submenu | 12–18 | -| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform and mixed spot/process gradients export as stops or process colours to SVG/PDF; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls | 4–8 | +| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls | 4–8 | | M2 | Drawing tools + smart guides | ✅ mostly done (Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending) | 12–18 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish | 3–6 (existing scope; Affinity export unestimated) | -| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform and mixed spot/process gradients export as stops or process colours to SVG/PDF; confirm the Scale Strokes & Effects default | 4–8 | +| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; confirm the Scale Strokes & Effects default | 4–8 | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9b987e7899..d6fb2d9a0f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1027,7 +1027,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - PDF export and print composition use the optional shared guarded writer ([pdf-backend.md](pdf-backend.md)); app drawing and output policy and desktop printer submission remain in their existing layers. The shared reader keeps the app-owned import adapter; synthetic tests cover layer and overprint state across windows, long operands, inline images, failed decoding, document limits and incomplete tails. Empty and populated metadata key presence is regression-tested, and CI checks the immutable backend source. Invisible text in a PDF (rendering mode 3, which carries a scanned page's recognized text over the scan) opens as type with no fill or stroke, a run of its own beside visible text on the same line; text that can't come in as type (opened as outlines, Type 3 fonts) is left out with a warning. PDF export, and printing, write characters with no fill or stroke as real text in rendering mode 3, so they draw nothing but stay selectable and searchable, also in PDF/X-1a and PDF/A-2b (#2675, `pdf/src/tests/import_fidelity.rs`, `pdf/src/tests/realtext.rs`). A PDF, or a `.ai` read through its PDF part, whose spot inks have the same values but different names opens with a spot swatch for each ink. The solid fills and strokes of paths and type, and the stops of gradients on paths, link to the swatch of the ink they are painted in, the points of a gradient mesh in one of these inks keep the ink's color, and PDF export writes each of these inks as its own separation (`pdf/src/tests/import_color.rs`). Paint in these inks inside pattern cells, soft masks and type 3 glyphs, and gradients on type in these inks, still import as RGB. Type in one of these inks can also import as RGB when type in another Separation or DeviceN ink is shown with no path drawn between them. - PDF export writes a linear or radial gradient that mixes a spot color with process colors, or two spot colors, as a DeviceN shading of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. A gradient that mixes a spot color with RGB or Lab colors is still written without the spot ink, with a warning (`engine/src/tests/linked_stops.rs`). + PDF export writes a linear or radial gradient that mixes a spot color with process colors, or two spot colors, as a DeviceN shading of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. A gradient that mixes a spot color with RGB or Lab colors is still written without the spot ink, with a warning, and a gradient with the Perceptual method is written as an image, without the spot ink. A Lab spot color in such a shading is named by the same Separation space, with the Lab alternate, as its flat fills (`engine/src/tests/linked_stops.rs`, `engine/src/tests/labspots.rs`). - `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465). Native documents with a lot of path data (traced or generated art, in layers, symbols or patterns) are saved as compact JSON, about a fifth of the size; small documents stay pretty-printed (#1492). Saving to a network drive on macOS falls back to a plain fsync when the share refuses a full flush (#1625, part of #1620; not confirmed on a real share), and a save still succeeds when a folder refuses the temporary file, the rename over the document or copying permissions: the content is written elsewhere first and copied in, and a failed copy keeps the temporary file and names it (#1649, part of #1620). A document opened by a relative path finds its relatively linked images, and `vectorcraft-cli convert` lists what reading the input left out as `importWarnings` (#1606, fixes #1604). A name typed in the desktop save panel without the file type's extension gets it, and when a file of that name exists, which the panel did not ask about, Save, Save As, Save a Copy, Save as Template, the exports and every other write through a save panel ask before replacing it (dialog `replaceFile`; Cancel writes nothing). A name returned by the desktop save panel with the extension of a format the save does not write has it replaced with the saved format's: Save As of a new document saves `card.ait` and `card.png` as `card.vectorcraft`, and Save as Template saves `card.pdf` as `card.vctemplate`. An extension that names no format stays part of the name (`notes.v2` is saved as `notes.v2.vectorcraft`). From 51dcb9466134c7c114393c2b3a59ffeeb87e5653 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 04:51:43 +0700 Subject: [PATCH 200/260] Fix #4967: a drawing tablet's pen draws on a Wayland session by default On a Wayland session Linux Display Server's default, Automatic, opened the window on native Wayland. winit 0.30 doesn't bind the Wayland tablet protocol, and KWin (since Plasma 6.3) and Mutter turn no tablet input into pointer input, so the pen moved only the compositor's cursor and the app got no motion or presses. Only X11 (XWayland) When a Pen Is Attached, which users had to find and choose, sent the window through XWayland, where the pen works as a mouse with its pressure. Automatic now opens the window through XWayland when a pen is attached as the app starts, as PhotoCraft does by default. VECTORCRAFT_NATIVE_WAYLAND=1 keeps the window on Wayland, like PhotoCraft's PHOTOCRAFT_NATIVE_WAYLAND. The X11 choice is unchanged. --- README.md | 8 ++--- apps/vectorcraft/src/main.rs | 6 ++-- apps/vectorcraft/src/xwayland.rs | 53 ++++++++++++++++++------------ crates/engine/src/cmd/prefscmds.rs | 5 +-- crates/engine/src/prefs.rs | 7 ++-- docs/development.md | 3 +- docs/hardware-parity.md | 5 +-- 7 files changed, 51 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index fd45eb9cdd..0b7b9932bb 100644 --- a/README.md +++ b/README.md @@ -205,10 +205,10 @@ drag-and-drop, set **Preferences › Performance › Linux Display Server** to * the app with `WAYLAND_DISPLAY= vectorcraft`: the window then opens through XWayland, where drops work (see [`docs/development.md`](docs/development.md#linux-wayland-and-x11)). -On Linux with Wayland, under KDE Plasma 6.3 or later and under GNOME, VectorCraft doesn't respond to a drawing tablet's -pen yet (#491, #2028). Open the window through XWayland instead, where the pen works as a mouse and the app reads its -pressure: set the same preference to **X11 (XWayland)**, or to **X11 (XWayland) When a Pen Is Attached** to use -XWayland only when a pen is attached as VectorCraft starts, and restart; or start the app with +On Linux with Wayland, under KDE Plasma 6.3 or later and under GNOME, VectorCraft can't get a drawing tablet's pen +input on native Wayland yet (#491, #2028). When a pen is attached as VectorCraft starts, the window opens through +XWayland, where the pen works as a mouse and the app reads its pressure (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps +Wayland). For a pen attached later, set the same preference to **X11 (XWayland)** and restart, or start the app with `WAYLAND_DISPLAY= vectorcraft` (see [`docs/development.md`](docs/development.md#linux-wayland-and-x11)). ### Use it from Claude Code and other agents diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 8bb9600af4..980d3826bb 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -290,15 +290,15 @@ fn main() -> std::process::ExitCode { let options = native_options(custom_titlebar); // winit picks Wayland whenever `WAYLAND_DISPLAY` is set; Preferences › Performance › Linux // Display Server › X11 opens the window through XWayland instead, where file drops work (#1151), - // and X11 (XWayland) When a Pen Is Attached does so when a pen is attached, where the pen draws (#2028). + // and the other choices do so when a pen is attached, where the pen draws (#2028, #4967). #[cfg(target_os = "linux")] let options = { let mut options = options; let pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("linuxDisplayServer")).and_then(serde_json::Value::as_str); if xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) { if xwayland::x11_libraries_found() { - if pref == Some("x11WithPen") { - log::info!("pen found: opening the window through XWayland (Preferences › Performance › Linux Display Server)"); + if pref != Some("x11") { + log::info!("pen found: opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)"); } else { log::info!("opening the window through XWayland (Preferences › Performance › Linux Display Server)"); } diff --git a/apps/vectorcraft/src/xwayland.rs b/apps/vectorcraft/src/xwayland.rs index 509a700569..38b210c05e 100644 --- a/apps/vectorcraft/src/xwayland.rs +++ b/apps/vectorcraft/src/xwayland.rs @@ -1,8 +1,10 @@ //! Linux: Preferences › Performance › Linux Display Server › X11 opens the window through XWayland //! on a Wayland session, where dropped files arrive (winit 0.30 has no Wayland drag and drop, -//! #1151). X11 (XWayland) When a Pen Is Attached does so only when a pen is attached as the app -//! starts: winit 0.30 doesn't bind the Wayland tablet protocol, and XWayland hands the pen to X11 -//! windows as a pointer (#2028). Only when XWayland can run the window: an X display is set and +//! #1151). Automatic and X11 (XWayland) When a Pen Is Attached do so only when a pen is attached +//! as the app starts, as PhotoCraft does: winit 0.30 doesn't bind the Wayland tablet protocol, so +//! on native Wayland the pen moves only the compositor's cursor, and XWayland hands the pen to X11 +//! windows as a pointer (#2028, #4967). `VECTORCRAFT_NATIVE_WAYLAND=1` keeps a pen's window on +//! Wayland. Only when XWayland can run the window: an X display is set and //! the X11 libraries winit loads at runtime are installed. Otherwise the window opens on Wayland, //! so a missing library never keeps the app from starting. //! @@ -21,16 +23,17 @@ const X11_LIBS: &[&str] = &["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"]; /// Whether the saved `linuxDisplayServer` and the environment ask for XWayland: `x11` chosen, or -/// `x11WithPen` chosen and `pen` finding a pen; a Wayland session (winit picks Wayland whenever -/// `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set); and an X display to open. `pen` runs only for -/// `x11WithPen`, after the session checks. +/// any other choice (`automatic`, `x11WithPen`, none saved) with `pen` finding a pen and +/// `VECTORCRAFT_NATIVE_WAYLAND` unset (or `0`); a Wayland session (winit picks Wayland whenever +/// `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set); and an X display to open. `pen` runs only after +/// the other checks. pub fn wanted(pref: Option<&str>, var: impl Fn(&str) -> Option<OsString>, pen: impl FnOnce() -> bool) -> bool { let set = |name: &str| var(name).is_some_and(|v| !v.is_empty()); let session = (set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET")) && set("DISPLAY"); + let native_wayland = var("VECTORCRAFT_NATIVE_WAYLAND").is_some_and(|v| !v.is_empty() && v != "0"); match pref { Some("x11") => session, - Some("x11WithPen") => session && pen(), - _ => false, + _ => session && !native_wayland && pen(), } } @@ -149,27 +152,35 @@ mod tests { let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]); assert!(wanted(Some("x11"), &wayland, no_probe)); assert!(wanted(Some("x11"), env(&[("WAYLAND_SOCKET", "3"), ("DISPLAY", ":0")]), no_probe)); - assert!(!wanted(Some("automatic"), &wayland, no_probe)); - assert!(!wanted(None, &wayland, no_probe)); - assert!(!wanted(Some("wayland"), &wayland, no_probe)); + assert!(!wanted(Some("automatic"), &wayland, || false)); + assert!(!wanted(None, &wayland, || false)); // An X11 session already opens on X11; without an X display there is no XWayland to use. assert!(!wanted(Some("x11"), env(&[("DISPLAY", ":0")]), no_probe)); assert!(!wanted(Some("x11"), env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", "")]), no_probe)); assert!(!wanted(Some("x11"), env(&[("WAYLAND_DISPLAY", "wayland-0")]), no_probe)); } - /// X11 (XWayland) When a Pen Is Attached (#2028): XWayland on a Wayland session with an X - /// display when a pen is found, the session's own display server otherwise. The pen check - /// runs only on such a session. + /// Automatic and X11 (XWayland) When a Pen Is Attached (#2028, #4967): XWayland on a Wayland + /// session with an X display when a pen is found, where the pen reaches the window, the + /// session's own display server otherwise. The pen check runs only on such a session, and + /// `VECTORCRAFT_NATIVE_WAYLAND` keeps Wayland. #[test] - fn the_pen_choice_opens_xwayland_only_with_a_pen() { + fn a_pen_opens_xwayland_unless_native_wayland_is_asked_for() { let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]); - assert!(wanted(Some("x11WithPen"), &wayland, || true)); - assert!(wanted(Some("x11WithPen"), env(&[("WAYLAND_SOCKET", "3"), ("DISPLAY", ":0")]), || true)); - assert!(!wanted(Some("x11WithPen"), &wayland, || false)); - assert!(!wanted(Some("x11WithPen"), env(&[("DISPLAY", ":0")]), no_probe)); - assert!(!wanted(Some("x11WithPen"), env(&[("WAYLAND_DISPLAY", "wayland-0")]), no_probe)); - assert!(!wanted(Some("x11WithPen"), env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", "")]), no_probe)); + let native = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), ("VECTORCRAFT_NATIVE_WAYLAND", "1")]); + let not_native = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), ("VECTORCRAFT_NATIVE_WAYLAND", "0")]); + for pref in [Some("automatic"), None, Some("x11WithPen")] { + assert!(wanted(pref, &wayland, || true), "{pref:?}"); + assert!(wanted(pref, env(&[("WAYLAND_SOCKET", "3"), ("DISPLAY", ":0")]), || true), "{pref:?}"); + assert!(!wanted(pref, &wayland, || false), "{pref:?}"); + assert!(!wanted(pref, env(&[("DISPLAY", ":0")]), no_probe), "{pref:?}"); + assert!(!wanted(pref, env(&[("WAYLAND_DISPLAY", "wayland-0")]), no_probe), "{pref:?}"); + assert!(!wanted(pref, env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", "")]), no_probe), "{pref:?}"); + assert!(!wanted(pref, &native, no_probe), "{pref:?}"); + assert!(wanted(pref, ¬_native, || true), "{pref:?}"); + } + // The X11 choice opens XWayland with or without a pen; the opt-out is for the pen only. + assert!(wanted(Some("x11"), &native, no_probe)); } /// `/proc/bus/input/devices` of a laptop with a Wacom Intuos Pro attached (64-bit longs: the diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index d3bf73b952..257b6f0f1f 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -89,8 +89,9 @@ pub const GPU_PREFERENCES: &[(&str, &str)] = &[("automatic", "Automatic"), ("lowPower", "Power Saving (integrated)"), ("highPerformance", "High Performance (discrete)")]; /// Performance › Linux Display Server (`linuxDisplayServer`), read by the desktop app at startup: /// `x11` opens the window through XWayland on a Wayland session, where dropped files arrive -/// (winit 0.30 has no Wayland drag and drop, #1151); `x11WithPen` does the same only when a pen is -/// attached as the app starts: under XWayland a drawing tablet's pen draws as a mouse (#2028). +/// (winit 0.30 has no Wayland drag and drop, #1151); `automatic` and `x11WithPen` do the same only +/// when a pen is attached as the app starts: under XWayland a drawing tablet's pen draws as a mouse +/// (#2028, #4967). const LINUX_DISPLAY_SERVERS: &[(&str, &str)] = &[("automatic", "Automatic"), ("x11", "X11 (XWayland)"), ("x11WithPen", "X11 (XWayland) When a Pen Is Attached")]; const BLACK: &[(&str, &str)] = &[("accurate", "Display All Blacks Accurately"), ("rich", "Display All Blacks as Rich Black")]; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 05f7880ba1..db3ee7e752 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -162,9 +162,10 @@ pub struct Prefs { pub real_time_drawing: bool, /// Rasterizer worker threads; -1 = automatic. pub render_threads: i32, - /// Linux: `automatic` opens the window on the session's display server; `x11` opens it through - /// XWayland on a Wayland session, where dropped files arrive (#1151); `x11WithPen` opens it - /// through XWayland only when a pen is attached (#2028). Read when the app starts. + /// Linux: `automatic` opens the window on the session's display server, or through XWayland on + /// a Wayland session when a pen is attached (#4967); `x11` opens it through XWayland on a + /// Wayland session, where dropped files arrive (#1151); `x11WithPen` opens it through XWayland + /// only when a pen is attached (#2028). Read when the app starts. pub linux_display_server: String, // File Handling pub background_save: bool, diff --git a/docs/development.md b/docs/development.md index 2dfa4fea63..db22dcf72b 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,5 +1,6 @@ # Development +> **Last updated:** 2026-11-01 · **Change:** Linux: Automatic Linux Display Server opens the window through XWayland when a pen is attached on a Wayland session, so the pen draws (#4967); `VECTORCRAFT_NATIVE_WAYLAND=1` keeps Wayland. > **Last updated:** 2026-10-31 · **Change:** files opened while the app runs open in its window on Windows and Linux (#4892); `--new-instance`. > **Last updated:** 2026-10-29 · **Change:** Linux clipboard: the Flatpak on GNOME copies and pastes text through the core Wayland protocol. > **Last updated:** 2026-10-29 · **Change:** Linux clipboard: a clipboard that can't be opened is retried with a growing wait and logged once. @@ -124,7 +125,7 @@ The window runs natively on Wayland (eframe's `wayland` feature) and on X11. On - **Clipboard owners that never answer (#510):** reading the clipboard waits on the app that owns it: arboard gives up on an X11 owner after 4 s, and a Wayland read waits for the owner to send its data. So on Linux the check that enables the Paste menu items runs on a background thread with a second clipboard handle (`crates/ui-egui/src/clipboard_probe.rs`, installed as `Services::clipboard_probe`), only while nothing is copied in the app and a document is open, and the window keeps drawing. A paste itself still reads on the UI thread, so pasting from such an owner waits for it once. Windows and macOS keep the check on the UI thread: Windows only asks which formats the clipboard holds, macOS asks the pasteboard server. - **Copied files:** files copied in a file manager (`text/uri-list`; `CF_HDROP` on Windows, file URLs on macOS) paste as the first one that is art (SVG, PDF, EPS, EMF/WMF or a bitmap; a `.ai` or `.ait` file from the editing data it holds, else as the PDF or PostScript it holds), before the clipboard's other formats (which include the files' paths as text). - **Dropping files on the window does not work under Wayland:** winit 0.30, which eframe 0.37 runs on, has no Wayland drag and drop ([winit#1881](https://github.com/rust-windowing/winit/issues/1881), added in winit 0.31; [egui#1563](https://github.com/emilk/egui/issues/1563)), so no `dropped_files` arrive. Until eframe moves to winit 0.31: copy the files in the file manager and paste them, use File › Place or Open, or open the window through XWayland, where drops work: set **Preferences › Performance › Linux Display Server** to **X11 (XWayland)** and restart (#1151), or start the app with `WAYLAND_DISPLAY= vectorcraft`. The preference (`linuxDisplayServer`, read at startup in `apps/vectorcraft/src/main.rs`, shown on Linux only) has winit open the window on X11 (`EventLoopBuilderExtX11::with_x11`) when the session is Wayland, `DISPLAY` is set and the X11 libraries winit loads are installed (`apps/vectorcraft/src/xwayland.rs` reads `ldconfig -p` and the usual library directories); otherwise the window opens on Wayland and the log says why. Unlike clearing `WAYLAND_DISPLAY`, it leaves the clipboard on the compositor's own. -- **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, either run the app under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer (Preferences › Performance › Linux Display Server › X11 (XWayland); X11 (XWayland) When a Pen Is Attached (`x11WithPen`), which opens the window through XWayland only when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and logs `pen found: opening the window through XWayland`; `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way. +- **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, the app runs under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer: Preferences › Performance › Linux Display Server's Automatic (the default) and X11 (XWayland) When a Pen Is Attached (`x11WithPen`) open the window through XWayland when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and log `pen found: opening the window through XWayland`, as PhotoCraft does (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps the window on Wayland). For a pen attached after the app started, either run the app under XWayland (Preferences › Performance › Linux Display Server › X11 (XWayland); `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way. - **Pen pressure under X11 and XWayland (#764):** winit 0.30 hands a pen to an X11 window as a mouse, without its pressure. When the window is on X11, XWayland included, the desktop app opens a second X connection (x11rb's `RustConnection`) and reads XInput2 raw events for every device (`apps/vectorcraft/src/tablet.rs`, from PhotoCraft's `crates/tablet`). A device with an `Abs Pressure` valuator is a pen, unless its XInput type is `TOUCHPAD` or `TOUCHSCREEN`. While a pen is the pointer that moved last, its pressure, scaled from the valuator's range to 0..1, reaches the tools that use pressure: the Paintbrush's pressure-sensitive brushes and the Liquify tools' Use Pressure Pen. A pen device whose name or XInput type contains `eraser` (in any case) is the pen's eraser end: while the pointer is over the window, the canvas selects the Eraser tool when the eraser end moves, and it selects the tool used before when the tip moves again (`crates/ui-egui/src/stylus.rs`). The X server needs XInput 2.1 or later; otherwise the log has a `tablet pressure:` warning with the reason, and the pen draws at full pressure. ## Fonts: craft-fonts (optional build input) diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 336fe696bf..3baf8d30df 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,6 +1,6 @@ # Hardware parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** patch (a second finger cancels the tool press the first finger began, and a finger landing while another is down presses nothing; the pinch only navigates, #4198) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** patch (Linux: on a Wayland session with a pen attached, Automatic opens the window through XWayland, where the pen draws, #4967) · **Target:** Adobe Illustrator 2026 (30.x) What hardware Illustrator uses, per platform, against VectorCraft. Illustrator's side is from its public documentation (GPU Performance, touch workspace, pen pressure pages); ours from the code @@ -21,7 +21,7 @@ reads the pen's eraser end on Windows, on macOS and on Linux under X11 and XWayl | Multithreaded rendering off the UI thread | partial | yes | yes | yes | single-threaded | beyond Illustrator | | Hybrid-graphics GPU choice | automatic | power-saving GPU by default, Preferences › Graphics Processor | same; DX12 then OpenGL; no Vulkan unless asked (#545, #806) | the desktop's GPU | browser | done | | Restart on another GPU when the first fails to present | — | yes (#502, #964) | yes | yes | restart on lost device (#369) | done | -| Pen pressure | yes (Wacom, Windows Ink, macOS tablet events) | yes, read from AppKit's tablet events before the window gets them (winit reports none), each move of a stroke with its own pressure, mouse event coalescing off (#852; not yet tried on a Mac) | yes (pointer force via `WM_POINTER`) | under X11 and XWayland (Preferences › Performance › Linux Display Server, #1151, #2028), read from XInput2 raw events (#764); **no** on native Wayland, where winit reports none and the pen may not reach the window (#491) | browser pointer events, with coalesced events; Apple Pencil on iPad (hover, palm rejection: fingers navigate after a pen contact until reload) | partial: 2–4 h for Wayland (winit 0.31), plus a check on a Mac | +| Pen pressure | yes (Wacom, Windows Ink, macOS tablet events) | yes, read from AppKit's tablet events before the window gets them (winit reports none), each move of a stroke with its own pressure, mouse event coalescing off (#852; not yet tried on a Mac) | yes (pointer force via `WM_POINTER`) | under X11 and XWayland (Preferences › Performance › Linux Display Server, #1151, #2028; Automatic uses XWayland when a pen is attached on a Wayland session, #4967), read from XInput2 raw events (#764); **no** on native Wayland, where winit reports none and the pen may not reach the window (#491) | browser pointer events, with coalesced events; Apple Pencil on iPad (hover, palm rejection: fingers navigate after a pen contact until reload) | partial: 2–4 h for Wayland (winit 0.31), plus a check on a Mac | | Pen tilt, bearing, barrel rotation (6D Art Pen) | yes, drives brushes | no | no | no | no | missing: 4–8 h after the input layer (#372) | | Pen eraser end | yes | the eraser end (AppKit's tablet proximity events) selects the Eraser tool and the tip brings back the tool used before, as on Linux (#852; not yet tried on a Mac) | no | under X11 and XWayland, the eraser end selects the Eraser tool and the tip brings back the tool used before (#764); **no** on native Wayland | a press of the eraser end (Pointer Events eraser button, `button` 5) selects the Eraser tool, and that press erases; a press of the tip brings back the tool used before; Pointer Events report no end while the pen hovers | partial | | Pen eraser end | yes | the eraser end (AppKit's tablet proximity events) selects the Eraser tool and the tip brings back the tool used before, as on Linux (#852; not yet tried on a Mac) | with Windows Ink, an inverted pen or its eraser button (`PEN_FLAG_INVERTED`, `PEN_FLAG_ERASER` in the pen's pointer messages) selects the Eraser tool and the tip brings back the tool used before, as on Linux (not yet tried with a pen) | under X11 and XWayland, the eraser end selects the Eraser tool and the tip brings back the tool used before (#764); **no** on native Wayland | no | partial | @@ -36,6 +36,7 @@ reads the pen's eraser end on Windows, on macOS and on Linux under X11 and XWayl | Date | Change | Summary | |---|---|---| +| 2026-11-01 | patch | Linux (#4967): on a Wayland session, Linux Display Server › Automatic opens the window through XWayland when a pen is attached as the app starts, as X11 (XWayland) When a Pen Is Attached does and as PhotoCraft does; on native Wayland winit 0.30 gets no tablet input and KWin 6.3+ and Mutter emulate no pointer, so the pen moved only the compositor's cursor. `VECTORCRAFT_NATIVE_WAYLAND=1` keeps Wayland. Unit-tested (`xwayland::tests`); not tried with a tablet; score unchanged (estimated) | | 2026-10-30 | patch | Touch (#4198): a second finger landing cancels the tool press the first finger began, also in the same frame (the Pencil's stroke and a Selection move are rolled back, nothing enters the undo history), and a finger landing while another is down presses nothing, so a pinch or two-finger pan only navigates. Headless canvas test `a_second_finger_cancels_the_tool_gesture_the_first_began`; not tried on a touch screen; score unchanged (estimated) | | 2026-10-24 | minor | macOS: an AppKit local event monitor reads each mouse and tablet event's pen pressure and the pen's end before the window gets it and writes them into the canvas's pen feed (#852): each pointer move of a stroke keeps its own pressure, mouse event coalescing is off, and the eraser end selects the Eraser tool. The mapping is unit-tested on every platform and the macOS code type-checks for `aarch64-apple-darwin`; not yet tried on a Mac with a tablet, so the score is unchanged (estimated) | | 2026-10-15 | patch | Web review: preserve pen buttons and modifiers; leave fingers to eframe before the first pen contact; remove persistent pen policy. Canvas regression tests cover intermediate moves and long-touch cancellation on native and web input. Physical-device QA pending. | From d26dd933a76253d37d2785773605dfc44a94deab Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Sat, 31 Oct 2026 18:53:15 -0400 Subject: [PATCH 201/260] packaging(flatpak): add OCI image build and GHCR publishing helper (#4987) --- packaging/linux/flatpak-bundle.sh | 8 ++++ packaging/linux/flatpak-oci.sh | 64 +++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100755 packaging/linux/flatpak-oci.sh diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh index d5fddb473e..1c4025dbe6 100755 --- a/packaging/linux/flatpak-bundle.sh +++ b/packaging/linux/flatpak-bundle.sh @@ -20,10 +20,12 @@ APP_ID=ai.storyteller.vectorcraft FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo TEST=1 +OCI=0 TARBALL="" while [[ $# -gt 0 ]]; do case "$1" in --no-test) TEST=0; shift ;; + --oci) OCI=1; shift ;; -h | --help) sed -n '2,14p' "$0"; exit 0 ;; -*) echo "unknown argument: $1" >&2; exit 2 ;; *) TARBALL="$1"; shift ;; @@ -61,6 +63,12 @@ OUT="$DIST/$BASENAME.flatpak" # --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing. flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable echo "wrote $OUT" +if [[ "$OCI" = 1 ]]; then + OUT_OCI="$DIST/$BASENAME-oci" + rm -rf "$OUT_OCI" + flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable + echo "wrote OCI layout to $OUT_OCI" +fi if [[ "$TEST" = 1 ]]; then flatpak install --user -y --noninteractive --reinstall "$OUT" diff --git a/packaging/linux/flatpak-oci.sh b/packaging/linux/flatpak-oci.sh new file mode 100755 index 0000000000..0f73a62004 --- /dev/null +++ b/packaging/linux/flatpak-oci.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# Build vectorcraft as an OCI container layout and push it to GitHub Container Registry (GHCR) +# for consumption by Flatpak OCI clients (flatpak-oci-specs). +# +# Usage: +# packaging/linux/flatpak-oci.sh [--push] [TARBALL] +# +# Environment variables: +# REGISTRY Target registry image (default: ghcr.io/storytold/vectorcraft) +# TAG Target image tag (default: $VERSION-$ARCH, also tags stable-$ARCH) +# GITHUB_TOKEN Token for GHCR authentication when --push is used +set -euo pipefail +# shellcheck source=../env.sh +. "$(dirname "${BASH_SOURCE[0]}")/../env.sh" +HERE="$ROOT/packaging/linux" + +PUSH=0 +TARBALL="" +while [[ $# -gt 0 ]]; do + case "$1" in + --push) PUSH=1; shift ;; + -h | --help) sed -n '2,12p' "$0"; exit 0 ;; + -*) echo "unknown argument: $1" >&2; exit 2 ;; + *) TARBALL="$1"; shift ;; + esac +done + +ARCH="$(uname -m)" +case "$ARCH" in + x86_64) ;; + aarch64 | arm64) ARCH=aarch64 ;; + *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; +esac + +BASENAME="vectorcraft-$VERSION-linux-$ARCH" +OUT_OCI="$DIST/$BASENAME-oci" + +echo "==> Building Flatpak OCI layout for $BASENAME" +"$HERE/flatpak-bundle.sh" --oci --no-test "${TARBALL:-}" + +[[ -d "$OUT_OCI" ]] || { echo "error: $OUT_OCI layout not generated" >&2; exit 1; } + +REGISTRY="${REGISTRY:-ghcr.io/storytold/vectorcraft}" +TAG="${TAG:-$VERSION-$ARCH}" + +echo "==> OCI layout ready at $OUT_OCI (Target: $REGISTRY:$TAG)" + +if [[ "$PUSH" = 1 ]]; then + command -v skopeo >/dev/null || { echo "error: skopeo is required to push OCI images (apt install skopeo)" >&2; exit 1; } + + AUTH_ARGS=() + if [[ -n "${GITHUB_TOKEN:-}" ]]; then + AUTH_ARGS=(--dest-creds "${GITHUB_ACTOR:-storytold}:$GITHUB_TOKEN") + fi + + echo "==> Pushing to $REGISTRY:$TAG" + skopeo copy --format oci "${AUTH_ARGS[@]}" "oci:$OUT_OCI" "docker://$REGISTRY:$TAG" + + # Also update architecture-specific stable tag + echo "==> Pushing to $REGISTRY:stable-$ARCH" + skopeo copy --format oci "${AUTH_ARGS[@]}" "oci:$OUT_OCI" "docker://$REGISTRY:stable-$ARCH" + + echo "==> Push complete" +fi From ffc9b71a2b8b0e666574406fe6c445754a8b0623 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 06:02:13 +0700 Subject: [PATCH 202/260] Tests: artboard fill in EPS and PostScript print matches the red by hue, not one platform's CMYK values --- .../engine/src/cmd/fileio/tests_artboard_fill.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_artboard_fill.rs b/crates/engine/src/cmd/fileio/tests_artboard_fill.rs index 6ca7d486fd..28e170e063 100644 --- a/crates/engine/src/cmd/fileio/tests_artboard_fill.rs +++ b/crates/engine/src/cmd/fileio/tests_artboard_fill.rs @@ -100,8 +100,20 @@ fn pdf_and_svg_show_the_color_and_their_editing_data_keeps_it_as_the_artboards() #[test] fn eps_and_postscript_print_draw_the_color() { let mut s = session(); - // The only red the document has, the first artboard's color: RGB, or CMYK PostScript's. - let red = |t: &str| t.contains("1 0 0 rg\n") || t.contains("0 0.9725 1 0 k\n"); + // The only red the document has, the first artboard's color: RGB, or CMYK PostScript's (its + // values depend on the color conversion the platform offers, so only its hue is checked). + let red = |t: &str| { + t.lines().any(|l| { + let mut w: Vec<&str> = l.split_whitespace().collect(); + let Some(op) = w.pop() else { return false }; + let v: Vec<f64> = w.iter().filter_map(|n| n.parse().ok()).collect(); + match (op, v.as_slice()) { + ("rg" | "setrgbcolor", [r, g, b]) => *r > 0.9 && *g < 0.1 && *b < 0.1, + ("k" | "setcmykcolor", [c, m, y, k]) => *c < 0.1 && *m > 0.8 && *y > 0.8 && *k < 0.1, + _ => false, + } + }) + }; let eps = |s: &mut Session, more: Value| { String::from_utf8_lossy(&file(s, with(json!({"format": "eps", "useArtboards": true, "artboard": 0}), &more))).into_owned() }; From 8704c15c6dbc4cadd2c0a252be54cfce36aeb41c Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 05:52:23 +0700 Subject: [PATCH 203/260] Fix #4980: Pen with Cmd/Ctrl drags the path, not hidden bounding-box handles Cmd/Ctrl held with the Pen lends the last-used selection tool (Direct Selection until one is chosen), which already moved anchors, straight segments and curves of the path being drawn, one undo step each, and handed the path back to the Pen. With the Selection tool used last, the lent tool hit-tested the bounding box even though the canvas hides it while anchors are selected on their own, as the end anchor of a path being drawn is. Over the path it showed a resize pointer, and the drag scaled the path by a handle nobody could see: a flat path did nothing at all. The Selection tool's handles now take the pointer only while the box is shown (View > Show Bounding Box, no anchors selected on their own), so the lent Selection tool moves the path being drawn. Tests: select::tests::hidden_box_handles_take_no_press_while_anchors_are_selected, tests::draw2::pen_cmd_drag_edits_anchors_and_segments_and_goes_on_drawing. --- crates/engine/src/tests/draw2.rs | 54 ++++++++++++++++++++++++++++++++ crates/tools/src/select.rs | 17 +++++----- crates/tools/src/select/tests.rs | 22 +++++++++++++ docs/ui-parity.md | 5 +-- 4 files changed, 89 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 47adaf47cd..e5d9ac3cc6 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -2579,6 +2579,60 @@ fn pen_with_cmd_borrows_direct_selection_and_goes_on_drawing() { assert_eq!(s.tool_id(), "rectangle"); } +/// #4980: Cmd/Ctrl held with the Pen drags as Direct Selection: an anchor of the path being drawn +/// moves on its own and the Pen goes on drawing that path from it; another path's straight segment +/// moves both its ends and a curved one bends; each drag is one undo step and the pointer is the +/// Pen's again once Cmd is let go. With the Selection tool used last, a Cmd drag on the path being +/// drawn moves it: the bounding box isn't shown, so its handles don't scale it to nothing. +#[test] +fn pen_cmd_drag_edits_anchors_and_segments_and_goes_on_drawing() { + let (none, cmd) = (Mods::default(), Mods { cmd: true, ..Mods::default() }); + let v = view(); + let mut s = session(); + let straight = line(&mut s, 100.0, 500.0, 300.0, 500.0); + let anchors = json!([{"x": 400, "y": 500, "out": [450, 400]}, {"x": 600, "y": 500, "in": [550, 400]}]); + let curve = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("pen", v).unwrap(); + for x in [100.0, 200.0, 300.0] { + gesture(&mut s, &[(x, 100.0)], none); + } + let id = s.doc().unwrap().selection.objects[0]; + let points = |s: &Session, id| path(s, id).subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect::<Vec<_>>(); + assert_eq!(gesture(&mut s, &[(200.0, 100.0), (205.0, 120.0), (210.0, 140.0)], cmd), 1); + assert_eq!(points(&s, id), [(100.0, 100.0), (210.0, 140.0), (300.0, 100.0)]); + assert_eq!(s.tool_id(), "pen"); + let pen = s.cursor(Point::new(700.0, 300.0), none, v); + assert!(matches!(pen, vectorcraft_tools::Cursor::Pen | vectorcraft_tools::Cursor::PenDrawing), "{pen:?}"); + // The next click goes on drawing the same path from its end. + gesture(&mut s, &[(400.0, 200.0)], none); + assert_eq!(paths(&s).len(), 3, "no new path"); + assert_eq!(path(&s, id).subpaths[0].anchors.len(), 4); + assert_eq!(gesture(&mut s, &[(200.0, 500.0), (200.0, 510.0), (200.0, 530.0)], cmd), 1); + assert_eq!(points(&s, straight), [(100.0, 530.0), (300.0, 530.0)]); + let before = path(&s, curve).subpaths[0].anchors.clone(); + assert_eq!(gesture(&mut s, &[(500.0, 425.0), (500.0, 410.0), (500.0, 380.0)], cmd), 1); + let after = &path(&s, curve).subpaths[0].anchors; + assert_eq!((after[0].p, after[1].p), (before[0].p, before[1].p), "the ends stay"); + assert!(after[0].h_out.y < before[0].h_out.y && after[1].h_in.y < before[1].h_in.y, "{after:?}"); + // A Cmd-click away from the art deselects: the path is done, the next click starts another. + gesture(&mut s, &[(700.0, 300.0)], cmd); + assert!(s.doc().unwrap().selection.is_empty()); + gesture(&mut s, &[(700.0, 50.0)], none); + assert_eq!(paths(&s).len(), 4); + // Selection used last, a flat path being drawn: a Cmd drag where its box's top handle would be moves it. + s.select_tool("selection", v).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("pen", v).unwrap(); + gesture(&mut s, &[(100.0, 300.0)], none); + gesture(&mut s, &[(300.0, 300.0)], none); + let flat = s.doc().unwrap().selection.objects[0]; + assert_ne!(s.cursor(Point::new(200.0, 300.0), cmd, v), vectorcraft_tools::Cursor::ResizeV); + assert_eq!(gesture(&mut s, &[(200.0, 300.0), (200.0, 320.0), (200.0, 340.0)], cmd), 1); + assert_eq!(points(&s, flat), [(100.0, 340.0), (300.0, 340.0)]); + assert_eq!(s.tool_id(), "pen"); +} + #[test] fn cmd_alt_lends_group_selection_while_direct_selection_is_active() { let (cmd, cmd_alt) = (Mods { cmd: true, ..Mods::default() }, Mods { cmd: true, alt: true, ..Mods::default() }); diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index b9ae12f747..bcbce02eeb 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -427,6 +427,13 @@ pub fn selection_box(cx: &ToolContext) -> Option<OrientedBox> { remembered(cx, |m| &mut m.oriented, || vectorcraft_effects::preview::oriented_bounds(cx.doc, &cx.selection.objects, cx.preview_bounds)) } +/// [`selection_box`] while the canvas shows it (View › Show Bounding Box, and no anchors selected +/// on their own): its handles take a press only then. A path the Pen is drawing keeps its end +/// anchor selected, so Cmd/Ctrl lending the Selection tool doesn't scale it by hidden handles (#4980). +fn shown_box(cx: &ToolContext) -> Option<OrientedBox> { + (cx.show_bbox && cx.selection.anchors.is_empty()).then(|| selection_box(cx)).flatten() +} + /// The bounds of object `id`, measured as [`selection_bounds`] measures the selection. fn object_bounds(cx: &ToolContext, id: NodeId) -> Option<Rect> { remembered(cx, |m| m.by_object.entry(id).or_insert(None), || vectorcraft_effects::preview::bounds_of(cx.doc, &[id], cx.preview_bounds)) @@ -460,7 +467,7 @@ fn box_hit(cx: &ToolContext, b: &OrientedBox, p: Point) -> Option<BoxHit> { /// Whether the current selection's bounding-box handle is under `p`, using the same geometry as /// the Selection tool's press handling. pub(crate) fn bbox_handle_at(cx: &ToolContext, p: Point) -> bool { - cx.show_bbox && selection_box(cx).is_some_and(|b| matches!(box_hit(cx, &b, p), Some(BoxHit::Handle(_)))) + shown_box(cx).is_some_and(|b| matches!(box_hit(cx, &b, p), Some(BoxHit::Handle(_)))) } /// How near (screen points) the pointer must come to an object's centre or anchor for Smart Guides @@ -933,9 +940,7 @@ impl Tool for SelectionTool { if typewidget::over_widget(cx, p) { return Cursor::TypeWidget; } - if cx.show_bbox - && let Some(bx) = selection_box(cx) - { + if let Some(bx) = shown_box(cx) { match box_hit(cx, &bx, p) { Some(BoxHit::Handle(h)) => return handle_cursor(h, bx.angle - cx.view_angle()), Some(BoxHit::Rotate) => return Cursor::rotate_about_in_view(bx.center(), p, cx.view_angle()), @@ -1205,9 +1210,7 @@ impl SelectionTool { self.state = State::Idle; return Some(vec![]); } - if cx.show_bbox - && let Some(bx) = selection_box(cx) - { + if let Some(bx) = shown_box(cx) { match box_hit(cx, &bx, p) { Some(BoxHit::Handle(handle)) => { let is_area = |id: &NodeId| cx.doc.node(*id).is_some_and(is_area_type); diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 6ad4a6bf61..8e949e4d15 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -571,6 +571,28 @@ fn turned_cursors_step_with_the_view() { assert_eq!(Cursor::rotate_about_in_view(Point::ORIGIN, Point::ORIGIN, 90.0), Cursor::Rotate, "on the center"); } +/// #4980: with anchors selected on their own (the end anchor of a path the Pen is drawing, when +/// Cmd/Ctrl lends the Selection tool) the canvas shows no bounding box, so its handles neither +/// offer a resize pointer nor scale on a press: the press takes the path, as away from the box. +#[test] +fn hidden_box_handles_take_no_press_while_anchors_are_selected() { + let (d, id) = doc_with_rect(); + let p = paint(); + let top_middle = Point::new(150.0, 100.0); + let mut s = Selection::default(); + s.add(id); + let mut t = SelectionTool::default(); + assert_eq!(t.cursor(&cx(&d, &s, &p), top_middle, Mods::default()), Cursor::ResizeV, "the shown box's handle"); + assert_eq!(t.pointer(&cx(&d, &s, &p), &ev(PointerKind::Down, 150.0, 100.0)), vec![Action::Begin("Scale".into())]); + s.anchors.entry(id).or_default().insert((0, 1)); + let c = cx(&d, &s, &p); + let mut t = SelectionTool::default(); + assert_eq!(t.cursor(&c, top_middle, Mods::default()), Cursor::Move); + let down = t.pointer(&c, &ev(PointerKind::Down, 150.0, 100.0)); + assert!(!down.contains(&Action::Begin("Scale".into())), "{down:?}"); + assert!(!crate::select::bbox_handle_at(&c, top_middle)); +} + /// In a rotated view the resize and rotate cursors turn with the view. #[test] fn box_cursors_turn_with_the_view() { diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 342c9dd547..9c01459894 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (dynamic symbols, #4938) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Pen: Cmd/Ctrl drags with the lent selection tool, not hidden box handles, #4980) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -78,7 +78,7 @@ tools, never checked side by side) isn't captured row by row. | Click the first anchor to close; the drag shapes the closing curve | done | | | Click the last anchor to retract its outgoing handle; drag from it to pull a new one | done | | | Alt over a handle, anchor or segment acts as the Anchor Point tool | done | | -| Cmd/Ctrl lends the last-used selection tool | done | the path being drawn continues afterwards | +| Cmd/Ctrl lends the last-used selection tool | done | the path being drawn continues afterwards; with Direct Selection (the default until a selection tool is chosen) a Cmd drag moves an anchor of the path being drawn, moves a straight segment or bends a curved one, one undo step each, and a Cmd-click away from art ends the path; with Selection the hidden bounding box of the path being drawn takes no press, so the drag moves the path (#4980) | | Click an open path's end to continue it; click another path's end to join | done | #776 | | Rubber Band preview | done | Preferences option | | Auto Add/Delete on a selected path; Shift or the preference disables it | done | | @@ -387,6 +387,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Pen with Cmd/Ctrl held: the lent Selection tool no longer scales the path being drawn by bounding-box handles the canvas hides while its end anchor is selected (a flat path did nothing under a resize pointer); a Cmd drag moves the path instead, and with Direct Selection moves anchors and segments, one undo step each (#4980); scores and estimates unchanged | | 2026-11-01 | minor | Dynamic symbols (#4938): Symbol Options › Symbol Type; per-instance appearance for objects of a dynamic symbol's art; Reset in the Properties panel and the Symbols panel menu; on-canvas Direct Selection of the parts remains | | 2026-11-01 | minor | Export for Screens has Include Artboard Fill beside Include Bleed (on by default, remembered; `includeArtboardFill`): the files draw each artboard's background color behind its art, as exports and print now do, and the Print dialog's preview shows it (#4937); scores and estimates unchanged | | 2026-11-01 | minor | Select › Start Global Edit on a group takes the groups like it (the same objects at the same places, moved or scaled; Appearance, Size and the artboard options apply) and gives an edit made to an object inside one to the object at its place in each of the others, in proportion, as one undo step (#4939). Scores and estimates unchanged | From 7d8f1d4e0669952ebcd84ea5ee0682b20d70ee4b Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 05:41:26 +0700 Subject: [PATCH 204/260] =?UTF-8?q?Fix=20#4978:=20Area=20Type=20Options=20?= =?UTF-8?q?=E2=80=BA=20Text=20Flow=20by=20rows=20or=20by=20columns?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/doc/src/lib.rs | 3 +- crates/doc/src/text.rs | 2 +- crates/doc/src/text/area.rs | 17 ++++++++++ crates/doc/src/text/tests.rs | 13 ++++++++ crates/engine/src/cmd/typecmd.rs | 5 +-- crates/engine/src/tests/typearea.rs | 32 ++++++++++++++++++ crates/engine/tests/command_sweep.rs | 7 +++- crates/text/src/layout/driver.rs | 1 + crates/text/src/layout/region.rs | 10 ++++-- crates/text/src/lib.rs | 7 ++-- crates/text/src/tests/typo.rs | 20 +++++++++++ crates/ui-egui/src/dialogs/command.rs | 48 +++++++++++++++++++++++++-- crates/ui-egui/src/i18n/bg.tsv | 3 ++ crates/ui-egui/src/i18n/bs.tsv | 3 ++ crates/ui-egui/src/i18n/ca.tsv | 3 ++ crates/ui-egui/src/i18n/cs.tsv | 3 ++ crates/ui-egui/src/i18n/da.tsv | 3 ++ crates/ui-egui/src/i18n/de.tsv | 3 ++ crates/ui-egui/src/i18n/el.tsv | 3 ++ crates/ui-egui/src/i18n/es.tsv | 3 ++ crates/ui-egui/src/i18n/fi.tsv | 3 ++ crates/ui-egui/src/i18n/fr.tsv | 3 ++ crates/ui-egui/src/i18n/hu.tsv | 3 ++ crates/ui-egui/src/i18n/id.tsv | 3 ++ crates/ui-egui/src/i18n/it.tsv | 3 ++ crates/ui-egui/src/i18n/ja.tsv | 3 ++ crates/ui-egui/src/i18n/ka.tsv | 3 ++ crates/ui-egui/src/i18n/ko.tsv | 3 ++ crates/ui-egui/src/i18n/nl.tsv | 3 ++ crates/ui-egui/src/i18n/pl.tsv | 3 ++ crates/ui-egui/src/i18n/pt-br.tsv | 3 ++ crates/ui-egui/src/i18n/ru.tsv | 3 ++ crates/ui-egui/src/i18n/sv.tsv | 3 ++ crates/ui-egui/src/i18n/tr.tsv | 3 ++ crates/ui-egui/src/i18n/uk.tsv | 3 ++ crates/ui-egui/src/i18n/vi.tsv | 3 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 3 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 3 ++ docs/mcp.md | 11 ++++++ docs/target-app-parity.md | 5 +-- docs/type-parity.md | 5 +-- 41 files changed, 248 insertions(+), 16 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 333890c53b..26e2bfebf1 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -109,7 +109,8 @@ pub use style_libs::StyleLibrary; pub use text::{ AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt, JustificationOptions, Justify, Kinsoku, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign, RubyPosition, - RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape, + RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, + WrapShape, }; pub use trace::TraceView; pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables}; diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index a3ab2ccc56..c1a36e0583 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -13,7 +13,7 @@ mod para_style; mod runs; mod tabs_lists; -pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextWrap, VerticalAlign, WrapShape}; +pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape}; use char_style::yes; pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, ScriptMetrics}; pub use para_style::{ diff --git a/crates/doc/src/text/area.rs b/crates/doc/src/text/area.rs index b30afd4128..f53a488571 100644 --- a/crates/doc/src/text/area.rs +++ b/crates/doc/src/text/area.rs @@ -29,6 +29,19 @@ impl VerticalAlign { } } +/// Area Type Options › Text Flow: the order text fills the cells of area type with several rows +/// and columns. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum TextFlow { + /// Down each column's rows, then on to the next column (the default, and what a document + /// from before the option reads as). + #[default] + Columns, + /// Across each row's columns, then on to the next row. + Rows, +} + /// Text Wrap Options of a wrap object (Object → Text Wrap). #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] @@ -135,6 +148,9 @@ pub struct AreaOptions { pub first_baseline_min: f64, /// Vertical alignment of the lines in each row/column. pub vertical_align: VerticalAlign, + /// Text Flow: by columns (the default, left out when saved) or by rows. + #[serde(skip_serializing_if = "crate::skip::is_default")] + pub flow: TextFlow, /// How the frame and its text fit each other (Auto Size, Shrink Text to Fit). #[serde(skip_serializing_if = "crate::skip::is_default")] pub fit: AreaFit, @@ -150,6 +166,7 @@ impl Default for AreaOptions { first_baseline: FirstBaseline::Ascent, first_baseline_min: 0.0, vertical_align: VerticalAlign::Top, + flow: TextFlow::Columns, fit: AreaFit::None, } } diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 89a2591a93..bd53024b1c 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -293,6 +293,19 @@ fn paragraph_styles_split_merge_and_normalize() { assert_eq!(back.para_at(3).space_before, 4.0); } +/// Text Flow is saved only when by rows: area type by columns (the default) saves as it did before +/// the option, and files from before it read by columns; other values don't read. +#[test] +fn text_flow_is_saved_only_when_by_rows() { + let by_columns = serde_json::to_value(AreaOptions::default()).unwrap(); + assert!(by_columns.get("flow").is_none()); + assert_eq!(serde_json::from_value::<AreaOptions>(by_columns).unwrap().flow, TextFlow::Columns); + let by_rows = serde_json::to_value(AreaOptions { flow: TextFlow::Rows, ..AreaOptions::default() }).unwrap(); + assert_eq!(by_rows["flow"], "rows"); + assert_eq!(serde_json::from_value::<AreaOptions>(by_rows).unwrap().flow, TextFlow::Rows); + assert!(serde_json::from_value::<AreaOptions>(serde_json::json!({"flow": "diagonal"})).is_err()); +} + /// 120 × 40 area type at (40, 40), its text drawn at twice its size. fn area_type() -> TextObject { let mut t = TextObject::point(Point::ZERO, "Some text", CharStyle::default()); diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 97ffea3561..002851b70a 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -87,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> { "Area Type Options…", ["Type"], None, - "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt, inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options; width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", + "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt, inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options; width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", has_selection, area_options ), @@ -1006,6 +1006,7 @@ pub(crate) fn area_options_json(t: &TextObject) -> Result<Value> { let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); if let Some(o) = v.as_object_mut() { o.insert("fit".into(), json!(t.area.fit.id())); + o.insert("flow".into(), json!(t.area.flow)); let min = match t.area.fit { AreaFit::ShrinkText { min_percent } => min_percent, _ => AreaFit::DEFAULT_MIN_PERCENT, @@ -1022,7 +1023,7 @@ pub(crate) fn area_options_json(t: &TextObject) -> Result<Value> { } /// The [`vectorcraft_doc::AreaOptions`] keys `text.areaOptions` merges as they are. -const AREA_KEYS: [&str; 7] = ["rows", "columns", "gutter", "inset", "firstBaseline", "firstBaselineMin", "verticalAlign"]; +const AREA_KEYS: [&str; 8] = ["rows", "columns", "gutter", "inset", "firstBaseline", "firstBaselineMin", "verticalAlign", "flow"]; fn area_options(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.areaOptions"; diff --git a/crates/engine/src/tests/typearea.rs b/crates/engine/src/tests/typearea.rs index 430074433c..623eaa5a42 100644 --- a/crates/engine/src/tests/typearea.rs +++ b/crates/engine/src/tests/typearea.rs @@ -476,3 +476,35 @@ fn area_type_options_align_the_lines_vertically() { assert_eq!(text(&s, id).cached_bounds, before); assert!(cmd::find_command("text.areaOptions").unwrap().params.contains("verticalAlign?: top|center|bottom|justify")); } + +/// Area Type Options › Text Flow (#4978): `flow` fills the cells by columns (the default) or by +/// rows, is reported back, refuses other values and undoes. +#[test] +fn area_type_options_set_the_text_flow() { + use vectorcraft_doc::TextFlow; + let mut s = session(); + let id = area(&mut s, 0.0, 0.0, 420.0, 300.0, &"Words flow from cell to cell in order. ".repeat(40)); + sel(&mut s, &[id]); + let r = s.execute("text.areaOptions", &json!({"rows": 2, "columns": 2, "gutter": 20})).unwrap(); + assert_eq!(r["flow"], "columns"); + // Where the second cell sits from the first. + let second = |s: &Session| { + let f = layout(s, id).frames; + (f[1].x0 - f[0].x0, f[1].y0 - f[0].y0) + }; + assert_eq!(second(&s), (0.0, 160.0), "by columns the second cell is below the first"); + let n = undo_len(&s); + assert_eq!(s.execute("text.areaOptions", &json!({"flow": "rows"})).unwrap()["flow"], "rows"); + assert_eq!(text(&s, id).area.flow, TextFlow::Rows); + assert_eq!(second(&s), (220.0, 0.0), "by rows the second cell is beside the first"); + let l = layout(&s, id); + assert!(l.lines.iter().any(|li| li.region == 1 && li.x0 >= l.frames[1].x0 - 1e-6), "text reaches it"); + assert_eq!((undo_len(&s), last_step(&s).as_str()), (n + 1, "Area Type Options")); + for bad in [json!({"flow": "diagonal"}), json!({"flow": "Rows"}), json!({"flow": 1}), json!({"flow": null})] { + assert!(s.execute("text.areaOptions", &bad).is_err(), "{bad}"); + } + assert_eq!((undo_len(&s), text(&s, id).area.flow), (n + 1, TextFlow::Rows)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((text(&s, id).area.flow, second(&s)), (TextFlow::Columns, (0.0, 160.0))); + assert!(cmd::find_command("text.areaOptions").unwrap().params.contains("flow?: columns|rows")); +} diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index ae69993f7a..fd879a301e 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -720,7 +720,7 @@ fn shape_builder_options_junk() { assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); } -/// Area Type Options with junk fit values, on selected area type (the fixtures have none), with +/// Area Type Options with junk fit and flow values, on selected area type (the fixtures have none), with /// text that overflows: never a panic, the document stays sound, and editing still works. #[test] fn area_options_fit_junk() { @@ -741,6 +741,11 @@ fn area_options_fit_junk() { json!({"fit": "shrinkText", "columns": 100, "gutter": 0, "inset": 10000}), json!({"fitMinPercent": 50}), json!({"fit": "none", "fitMinPercent": 1e-308}), + json!({"flow": "rows", "rows": u64::MAX, "columns": u64::MAX, "gutter": 1e308}), + json!({"flow": "rows", "fit": "shrinkText", "rows": 3, "columns": 3}), + json!({"flow": "rows", "fit": "autoHeight", "columns": 4}), + json!({"flow": {"rows": 1}}), + json!({"flow": [1]}), ]; let story = "Words that overflow a small frame. ".repeat(40); let mut failures = vec![]; diff --git a/crates/text/src/layout/driver.rs b/crates/text/src/layout/driver.rs index 33d25f34fa..03a5d66179 100644 --- a/crates/text/src/layout/driver.rs +++ b/crates/text/src/layout/driver.rs @@ -18,6 +18,7 @@ pub fn layout(db: &FontDb, t: &TextObject) -> TextLayout { first_baseline: a.first_baseline, first_baseline_min: a.first_baseline_min, vertical_align: a.vertical_align, + flow: a.flow, fit: a.fit, ..LayoutOptions::default() }; diff --git a/crates/text/src/layout/region.rs b/crates/text/src/layout/region.rs index e0423e1dda..e702c6eb60 100644 --- a/crates/text/src/layout/region.rs +++ b/crates/text/src/layout/region.rs @@ -142,9 +142,13 @@ impl Region { let cw = ((bbox.width() - gutter * (cols - 1) as f64) / cols as f64).max(0.0); let rh = ((bbox.height() - gutter * (rows - 1) as f64) / rows as f64).max(0.0); let mut out = Vec::with_capacity(rows * cols); - // Text flows down each column, then across (Illustrator's default "by columns"). - for c in 0..cols { - for r in 0..rows { + // Text Flow: down each column, then across (by columns, the default), or across each row, + // then down (by rows). + let by_rows = opts.flow == vectorcraft_doc::TextFlow::Rows; + let (outer, inner) = if by_rows { (rows, cols) } else { (cols, rows) }; + for o in 0..outer { + for i in 0..inner { + let (r, c) = if by_rows { (o, i) } else { (i, o) }; let x0 = bbox.x0 + c as f64 * (cw + gutter); let y0 = bbox.y0 + r as f64 * (rh + gutter); let cell = if rows * cols == 1 { bbox } else { Rect::new(x0, y0, x0 + cw, y0 + rh) }; diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 8524a5962f..a382eabce2 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -47,7 +47,7 @@ use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2}; pub use layout::{decorations, fit_first_line, layout, layout_with, scaled}; pub use vectorcraft_doc::TextObject; -pub use vectorcraft_doc::{AreaFit, FirstBaseline, VerticalAlign}; +pub use vectorcraft_doc::{AreaFit, FirstBaseline, TextFlow, VerticalAlign}; /// Paragraph composer; stored per text object in [`vectorcraft_doc::ParaStyle::composer`]. pub use vectorcraft_doc::Composer; @@ -56,7 +56,7 @@ pub use vectorcraft_doc::Composer; /// composer, OpenType features). [`layout`] takes rows/columns/inset/first baseline from the object. #[derive(Clone, Debug, PartialEq)] pub struct LayoutOptions { - /// Area type rows and columns (text flows down each column, then across). Layout clamps each + /// Area type rows and columns (text fills them in [`LayoutOptions::flow`] order). Layout clamps each /// count to 1..=[`vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS`]. pub rows: usize, pub columns: usize, @@ -69,6 +69,8 @@ pub struct LayoutOptions { pub first_baseline_min: f64, /// Vertical alignment of the lines in each row/column (Area Type Options "Align"). pub vertical_align: VerticalAlign, + /// Area Type Options "Text Flow": by columns (down each column, then across) or by rows. + pub flow: TextFlow, /// Area type only: Shrink Text to Fit scales overflowing text down at layout time (see /// [`TextLayout::fit_scale`]); the other fits are the engine's business and lay out as `None`. pub fit: AreaFit, @@ -87,6 +89,7 @@ impl Default for LayoutOptions { first_baseline: FirstBaseline::Ascent, first_baseline_min: 0.0, vertical_align: VerticalAlign::Top, + flow: TextFlow::Columns, fit: AreaFit::None, composer: None, features: OtFeatures::default(), diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 105c1b424e..389fb985d1 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -457,6 +457,26 @@ fn hit_testing_picks_the_right_column() { } } +/// Area Type Options › Text Flow (#4978): by columns (the default) the second cell is the one +/// below the first; by rows it is the one beside it. +#[test] +fn text_flow_fills_the_cells_by_columns_or_by_rows() { + let t = area(©.repeat(8), style(12.0), Rect::new(0.0, 0.0, 420.0, 300.0), Justify::Left); + let grid = LayoutOptions { rows: 2, columns: 2, gutter: 20.0, ..Default::default() }; + for (flow, second) in [(TextFlow::Columns, (0.0, 160.0)), (TextFlow::Rows, (220.0, 0.0))] { + let l = layout_with(db(), &t, &LayoutOptions { flow, ..grid.clone() }); + let frame = l.frames.get(1).copied().unwrap(); + assert_eq!((frame.x0, frame.y0), second, "{flow:?}"); + let line = l.lines.iter().find(|li| li.region == 1).expect("text reaches the second cell"); + assert!(line.x0 >= second.0 - 1e-6 && line.baseline >= second.1, "{flow:?}: {line:?}"); + assert!(l.lines.iter().all(|li| l.lines.iter().all(|m| m.region >= li.region || m.start <= li.start)), "{flow:?}: text runs in cell order"); + } + // The object's own option lays out the same way. + let mut by_rows = t.clone(); + (by_rows.area.rows, by_rows.area.columns, by_rows.area.gutter, by_rows.area.flow) = (2, 2, 20.0, TextFlow::Rows); + assert_eq!(layout(db(), &by_rows).frames.get(1).map(|f| (f.x0, f.y0)), Some((220.0, 0.0))); +} + // ---------- area flow ---------- #[test] diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 89ef90c883..772833f4ba 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -3,11 +3,12 @@ use std::sync::LazyLock; -use serde_json::Value; +use serde_json::{Value, json}; use super::{DialogSpec, form}; -use crate::VectorcraftApp; use crate::state::Dialog; +use crate::theme::Tokens; +use crate::{VectorcraftApp, widgets}; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |d| tl!(&d.str("__label")).to_string(), @@ -15,7 +16,28 @@ pub(super) const SPEC: DialogSpec = DialogSpec { let command = d.str("__command"); let (lengths, order) = (lengths(&command), order(&command)); let rank = |k: &str| order.iter().position(|o| *o == k).unwrap_or(order.len()); + // Area Type Options › Text Flow is a pair of radio buttons after the other options. + let flow = if command == "text.areaOptions" { d.fields.remove("flow") } else { None }; form::param_fields(ui, d, &|k| lengths.contains(&k), &|k| choices(&command, k), &rank, app.session.general_unit()); + if let Some(v) = flow { + let mut rows = v.as_str() == Some("rows"); + ui.add_space(4.0); + egui::Grid::new("text-flow").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| { + let row = ui.label(egui::RichText::new(format!("{}:", tl!("Text Flow"))).color(Tokens::get(ui.ctx()).text)); + ui.label_inputs_by(row.id, |ui| { + ui.horizontal(|ui| { + if widgets::radio(ui, tl!("By Rows"), rows, true) { + rows = true; + } + if widgets::radio(ui, tl!("By Columns"), !rows, true) { + rows = false; + } + }); + }); + ui.end_row(); + }); + d.fields.insert("flow".into(), json!(if rows { "rows" } else { "columns" })); + } if previews(d) { let (cmd, params) = call(d); form::preview(app, ui, d, &d.str("__label"), &cmd, params); @@ -177,6 +199,28 @@ mod tests { assert_eq!(t.area.vertical_align, VerticalAlign::Center); } + /// Area Type Options › Text Flow (#4978): two radio buttons, By Columns as new area type has + /// it, and OK fills the cells by rows when By Rows is picked. + #[test] + fn area_type_options_dialog_sets_the_text_flow() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 20, "text": "Hello", "area": {"width": 200, "height": 200}})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + crate::menus::invoke(&mut app, "text.areaOptions", json!({})); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("flow"), "columns", "drawing the radio buttons keeps the value"); + app.ui.dialog.as_mut().unwrap().fields.insert("flow".into(), json!("rows")); + crate::dialogs::confirm(&mut app).unwrap(); + let NodeKind::Text(t) = &app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { panic!("text") }; + assert_eq!(t.area.flow, vectorcraft_doc::TextFlow::Rows); + } + /// Graph Type › Value Axis is a dropdown of the values `graph.setType` takes, and OK puts the /// value axis on the side picked. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index e2b237f2a8..cb018daf7f 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5988,3 +5988,6 @@ breakText Glyphs Глифи @msg no object at path {shown} in the symbol's art в графиката на символа няма обект на пътя {shown} @msg give fill, stroke, opacity and/or blend задайте fill, stroke, opacity и/или blend @msg pass newName, registration, exportType, nineSlice and/or type задайте newName, registration, exportType, nineSlice и/или type + Text Flow Поток на текста + By Rows По редове + By Columns По колони diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 879566d12a..aad1ce608a 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6021,3 +6021,6 @@ shape Open Otvoren @msg no object at path {shown} in the symbol's art nema objekta na putanji {shown} u grafici simbola @msg give fill, stroke, opacity and/or blend navedite fill, stroke, opacity i/ili blend @msg pass newName, registration, exportType, nineSlice and/or type navedite newName, registration, exportType, nineSlice i/ili type + Text Flow Tok teksta + By Rows Po redovima + By Columns Po kolonama diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index d0316d8024..c874a4e36e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6094,3 +6094,6 @@ breakText Glyphs Glifs @msg no object at path {shown} in the symbol's art no hi ha cap objecte al camí {shown} de l’art del símbol @msg give fill, stroke, opacity and/or blend indiqueu fill, stroke, opacity i/o blend @msg pass newName, registration, exportType, nineSlice and/or type indiqueu newName, registration, exportType, nineSlice i/o type + Text Flow Flux del text + By Rows Per files + By Columns Per columnes diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 3e441728aa..1d18695532 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6104,3 +6104,6 @@ breakText Glyphs Glyfy @msg no object at path {shown} in the symbol's art v kresbě symbolu není na cestě {shown} žádný objekt @msg give fill, stroke, opacity and/or blend zadejte fill, stroke, opacity a/nebo blend @msg pass newName, registration, exportType, nineSlice and/or type zadejte newName, registration, exportType, nineSlice a/nebo type + Text Flow Tok textu + By Rows Po řádcích + By Columns Po sloupcích diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 36f923e49e..399c067ad0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6002,3 +6002,6 @@ breakText Glyphs Glyffer @msg no object at path {shown} in the symbol's art intet objekt ved stien {shown} i symbolets grafik @msg give fill, stroke, opacity and/or blend angiv fill, stroke, opacity og/eller blend @msg pass newName, registration, exportType, nineSlice and/or type angiv newName, registration, exportType, nineSlice og/eller type + Text Flow Tekstflow + By Rows Efter rækker + By Columns Efter kolonner diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 6e6dc23930..80adbe1171 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5689,3 +5689,6 @@ breakText Glyphs Glyphen @msg no object at path {shown} in the symbol's art kein Objekt am Pfad {shown} in der Grafik des Symbols @msg give fill, stroke, opacity and/or blend geben Sie fill, stroke, opacity und/oder blend an @msg pass newName, registration, exportType, nineSlice and/or type geben Sie newName, registration, exportType, nineSlice und/oder type an + Text Flow Textfluss + By Rows Nach Zeilen + By Columns Nach Spalten diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 160be58422..535bc98be6 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6056,3 +6056,6 @@ breakText Glyphs Γλύφοι @msg no object at path {shown} in the symbol's art δεν υπάρχει αντικείμενο στη διαδρομή {shown} στο γραφικό του συμβόλου @msg give fill, stroke, opacity and/or blend δώστε fill, stroke, opacity ή/και blend @msg pass newName, registration, exportType, nineSlice and/or type δώστε newName, registration, exportType, nineSlice ή/και type + Text Flow Ροή κειμένου + By Rows Κατά γραμμές + By Columns Κατά στήλες diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 8a682cdc95..5a56e70b01 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6046,3 +6046,6 @@ breakText Glyphs Glifos @msg no object at path {shown} in the symbol's art no hay ningún objeto en la ruta {shown} del arte del símbolo @msg give fill, stroke, opacity and/or blend indique fill, stroke, opacity y/o blend @msg pass newName, registration, exportType, nineSlice and/or type indique newName, registration, exportType, nineSlice y/o type + Text Flow Flujo de texto + By Rows Por filas + By Columns Por columnas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 6bd598a4b5..2a4564b938 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6134,3 +6134,6 @@ breakText Glyphs Merkit @msg no object at path {shown} in the symbol's art symbolin kuvituksessa ei ole objektia polussa {shown} @msg give fill, stroke, opacity and/or blend anna fill, stroke, opacity ja/tai blend @msg pass newName, registration, exportType, nineSlice and/or type anna newName, registration, exportType, nineSlice ja/tai type + Text Flow Tekstin kulku + By Rows Riveittäin + By Columns Sarakkeittain diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 9e232d2184..a7a46033a8 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6101,3 +6101,6 @@ breakText Glyphs Glyphes @msg no object at path {shown} in the symbol's art aucun objet au chemin {shown} dans l'illustration du symbole @msg give fill, stroke, opacity and/or blend indiquez fill, stroke, opacity et/ou blend @msg pass newName, registration, exportType, nineSlice and/or type indiquez newName, registration, exportType, nineSlice et/ou type + Text Flow Flux du texte + By Rows Par lignes + By Columns Par colonnes diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index ffe3360fc8..eec2461130 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6090,3 +6090,6 @@ breakText Glyphs Glifák @msg no object at path {shown} in the symbol's art a szimbólum grafikájában nincs objektum a(z) {shown} útvonalon @msg give fill, stroke, opacity and/or blend adja meg a fill, stroke, opacity és/vagy blend értékét @msg pass newName, registration, exportType, nineSlice and/or type adja meg a newName, registration, exportType, nineSlice és/vagy type értékét + Text Flow Szövegfolyás + By Rows Soronként + By Columns Oszloponként diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index d38b743a6d..e5904b11c6 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6002,3 +6002,6 @@ breakText Glyphs Glif @msg no object at path {shown} in the symbol's art tidak ada objek di jalur {shown} dalam karya seni simbol @msg give fill, stroke, opacity and/or blend berikan fill, stroke, opacity dan/atau blend @msg pass newName, registration, exportType, nineSlice and/or type berikan newName, registration, exportType, nineSlice dan/atau type + Text Flow Alur teks + By Rows Per baris + By Columns Per kolom diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index e1f375654a..bf53ef52dc 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5723,3 +5723,6 @@ breakText Glyphs Glifi @msg no object at path {shown} in the symbol's art nessun oggetto al percorso {shown} nella grafica del simbolo @msg give fill, stroke, opacity and/or blend specifica fill, stroke, opacity e/o blend @msg pass newName, registration, exportType, nineSlice and/or type specifica newName, registration, exportType, nineSlice e/o type + Text Flow Flusso del testo + By Rows Per righe + By Columns Per colonne diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 8fdcd35c3f..718561e266 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5790,3 +5790,6 @@ breakText Glyphs 字形 @msg no object at path {shown} in the symbol's art シンボルのアートのパス {shown} にオブジェクトがありません @msg give fill, stroke, opacity and/or blend fill、stroke、opacity、blend のいずれかを指定してください @msg pass newName, registration, exportType, nineSlice and/or type newName、registration、exportType、nineSlice、type のいずれかを指定してください + Text Flow テキストの流れ + By Rows 行方向 + By Columns 列方向 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b091969fdd..9091ca5099 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6093,3 +6093,6 @@ breakText Glyphs გლიფები @msg no object at path {shown} in the symbol's art სიმბოლოს გრაფიკაში გზაზე {shown} ობიექტი არ არის @msg give fill, stroke, opacity and/or blend მიუთითეთ fill, stroke, opacity და/ან blend @msg pass newName, registration, exportType, nineSlice and/or type მიუთითეთ newName, registration, exportType, nineSlice და/ან type + Text Flow ტექსტის დინება + By Rows სტრიქონების მიხედვით + By Columns სვეტების მიხედვით diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index eac09b1b85..cdf3b79378 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5686,3 +5686,6 @@ breakText Glyphs 글리프 @msg no object at path {shown} in the symbol's art 심볼 아트의 경로 {shown}에 개체가 없습니다 @msg give fill, stroke, opacity and/or blend fill, stroke, opacity 및/또는 blend를 지정하세요 @msg pass newName, registration, exportType, nineSlice and/or type newName, registration, exportType, nineSlice 및/또는 type을 지정하세요 + Text Flow 텍스트 흐름 + By Rows 행 방향 + By Columns 열 방향 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 88652875a1..1bd09afd91 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6046,3 +6046,6 @@ breakText Glyphs Glyphs @msg no object at path {shown} in the symbol's art geen object op pad {shown} in de illustratie van het symbool @msg give fill, stroke, opacity and/or blend geef fill, stroke, opacity en/of blend op @msg pass newName, registration, exportType, nineSlice and/or type geef newName, registration, exportType, nineSlice en/of type op + Text Flow Tekstdoorloop + By Rows Per rij + By Columns Per kolom diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2761b1fb31..9e68943421 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5959,3 +5959,6 @@ breakText Glyphs Glify @msg no object at path {shown} in the symbol's art brak obiektu w ścieżce {shown} w grafice symbolu @msg give fill, stroke, opacity and/or blend podaj fill, stroke, opacity i/lub blend @msg pass newName, registration, exportType, nineSlice and/or type podaj newName, registration, exportType, nineSlice i/lub type + Text Flow Przepływ tekstu + By Rows Wierszami + By Columns Kolumnami diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 33e8b45d57..54d1a792eb 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6023,3 +6023,6 @@ breakText Glyphs Glifos @msg no object at path {shown} in the symbol's art nenhum objeto no caminho {shown} na arte do símbolo @msg give fill, stroke, opacity and/or blend informe fill, stroke, opacity e/ou blend @msg pass newName, registration, exportType, nineSlice and/or type informe newName, registration, exportType, nineSlice e/ou type + Text Flow Fluxo do texto + By Rows Por linhas + By Columns Por colunas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 8bab68b835..93b2543dee 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6081,3 +6081,6 @@ breakText Glyphs Глифы @msg no object at path {shown} in the symbol's art в графике символа нет объекта по пути {shown} @msg give fill, stroke, opacity and/or blend укажите fill, stroke, opacity и/или blend @msg pass newName, registration, exportType, nineSlice and/or type укажите newName, registration, exportType, nineSlice и/или type + Text Flow Поток текста + By Rows По строкам + By Columns По столбцам diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 572afa011d..ef3a7b65cd 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6156,3 +6156,6 @@ breakText Glyphs Glyfer @msg no object at path {shown} in the symbol's art inget objekt vid sökvägen {shown} i symbolens bild @msg give fill, stroke, opacity and/or blend ange fill, stroke, opacity och/eller blend @msg pass newName, registration, exportType, nineSlice and/or type ange newName, registration, exportType, nineSlice och/eller type + Text Flow Textflöde + By Rows Radvis + By Columns Kolumnvis diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ffb90dbb95..85abd24cca 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6061,3 +6061,6 @@ breakText Glyphs Glifler @msg no object at path {shown} in the symbol's art sembolün çiziminde {shown} yolunda nesne yok @msg give fill, stroke, opacity and/or blend fill, stroke, opacity ve/veya blend verin @msg pass newName, registration, exportType, nineSlice and/or type newName, registration, exportType, nineSlice ve/veya type verin + Text Flow Metin Akışı + By Rows Satırlara Göre + By Columns Sütunlara Göre diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 543e4834cf..686d8c4a15 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5703,3 +5703,6 @@ breakText Glyphs Гліфи @msg no object at path {shown} in the symbol's art у графіці символу немає об’єкта за шляхом {shown} @msg give fill, stroke, opacity and/or blend вкажіть fill, stroke, opacity та/або blend @msg pass newName, registration, exportType, nineSlice and/or type вкажіть newName, registration, exportType, nineSlice та/або type + Text Flow Потік тексту + By Rows За рядками + By Columns За стовпцями diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 78f16ce995..5b5ad327d4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5706,3 +5706,6 @@ breakText Glyphs Glyph @msg no object at path {shown} in the symbol's art không có đối tượng tại đường dẫn {shown} trong hình của ký hiệu @msg give fill, stroke, opacity and/or blend hãy cung cấp fill, stroke, opacity và/hoặc blend @msg pass newName, registration, exportType, nineSlice and/or type hãy cung cấp newName, registration, exportType, nineSlice và/hoặc type + Text Flow Luồng văn bản + By Rows Theo hàng + By Columns Theo cột diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 3249ed52f7..f3246d7a47 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5946,3 +5946,6 @@ breakText Glyphs 字形 @msg no object at path {shown} in the symbol's art 符号图稿中路径 {shown} 处没有对象 @msg give fill, stroke, opacity and/or blend 请提供 fill、stroke、opacity 和/或 blend @msg pass newName, registration, exportType, nineSlice and/or type 请提供 newName、registration、exportType、nineSlice 和/或 type + Text Flow 文本流向 + By Rows 按行 + By Columns 按列 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 70c266d79d..831924ac25 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5743,3 +5743,6 @@ breakText Glyphs 字符 @msg no object at path {shown} in the symbol's art 符號圖稿中路徑 {shown} 處沒有物件 @msg give fill, stroke, opacity and/or blend 請提供 fill、stroke、opacity 和/或 blend @msg pass newName, registration, exportType, nineSlice and/or type 請提供 newName、registration、exportType、nineSlice 和/或 type + Text Flow 文字流向 + By Rows 依列 + By Columns 依欄 diff --git a/docs/mcp.md b/docs/mcp.md index 16cadd2be5..f40709cb37 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4593,6 +4593,17 @@ again, so SVG, PDF and EPS show the aligned text. {"name":"run_command","arguments":{"command":"text.areaOptions","params":{"verticalAlign":"center"}}} ``` +### Text flow + +`text.areaOptions {flow: columns|rows}` (Area Type Options › Text Flow) sets the order area type with several rows +and columns fills its cells: `columns` (the default) runs down each column's rows, then on to the next column; +`rows` runs across each row's columns, then on to the next row. The reply reports `flow`; other values are refused. +Native files save it only when it is `rows`, so files from before it open by columns. + +```json +{"name":"run_command","arguments":{"command":"text.areaOptions","params":{"rows":2,"columns":3,"flow":"rows"}}} +``` + ## Fitting area type: Auto Size, Shrink Text to Fit, overflow `text.areaOptions` (and `text.create`'s `area`, `text.createInPath` in area mode) take a `fit`: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d6fb2d9a0f..e90c39ef7a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (dynamic symbols, #4938; score unchanged, hours 5–9 → 4–8) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Area Type Options › Text Flow, #4978; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -849,7 +849,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Optical kerning:** Character and Properties offer Optical beside Auto for automatic pair spacing. The side-profile spacing method is VectorCraft's own. Optical keeps its mode across cosmetic style runs, and leaves manual pair values and additive tracking intact. Native documents retain the mode and pair overrides; old documents use Auto. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/engine/src/tests/textedit.rs`. - **Kerning across style runs:** characters that differ only in fill, stroke, underline, strikethrough, overprint, character style name, leading, baseline shift, rotation, Character Alignment, kerning, or tracking that keeps or drops ligatures alike are shaped together, so restyling one character keeps the font's kerning pairs with its neighbors. A character with manual kerning that follows one with automatic kerning keeps the font's kerning with it (unless All Caps or Small Caps sets it as two letters, as ß becomes SS), and its value replaces the font's kerning after it. A ligature does not form across a change of style, and a change of font, size or OpenType features still shapes the characters apart. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/text/src/tests/bidi.rs`. - **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515). -- **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `<use>` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). +- **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `<use>` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in rectangular area type, rows and columns included. In area type of another shape, or with text wrap, such a paragraph is broken with the Single-line Composer. The Character panel's Small Caps, Superscript and Subscript buttons and the panel menu's items of the same names turn small caps and the superscript or subscript position on and off for the selected type, or for the text the Type tool has selected (`text.setFormat` or `text.setRangeStyle` `{smallCaps, position}`), in Document Setup's proportions. Turning Superscript on turns Subscript off, and turning Subscript on turns Superscript off. A button or item shows as on when the first selected character (at a caret, the character before it) has its attribute. - **Paragraph alignment:** the shared Paragraph/Properties alignment row leaves every button unselected when the paragraphs it acts on differ. Auto resolves per paragraph; choosing an alignment uses the existing command. Headless paragraph_mixed_alignment_* regressions exercise mixed → Center → Undo, caret/uniform states, Unicode range boundaries, Auto/direction, split runs and grouped text. These regressions and full integration CI pass. Original captures confirm mixed → Center → Undo in the existing alignment-button layout. The [public Paragraph panel guide](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/paragraph-panel-overview.html) lists the seven controls, but does not specify mixed-state rendering. Other paragraph fields remain outside this change; scores and hours unchanged. @@ -1427,6 +1427,7 @@ Symbols area (#4938), from the public symbol documentation ([create and place sy | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Type core: Area Type Options › Text Flow (#4978): area type with several rows and columns fills them by columns (the default) or by rows, from the dialog's radio buttons or `text.areaOptions {flow}`; evidence updated; scores unchanged. | | 2026-11-01 | minor | Symbols: dynamic symbols (#4938): Symbol Options › Symbol Type, per-instance appearance for objects of a dynamic symbol's art that stays linked through redefinition, Break Link baking, Reset and Static dropping it; evidence added. Score unchanged at 87% (estimated), hours 5–9 → 4–8. | | 2026-11-01 | minor | Artboard background colors in output (#4937): raster exports (a transparent background too), PDF, SVG and EPS pages, `.ai` files' PDF pages, Export for Screens and print (and its preview) draw each artboard's color behind its art, inside the artboard and in the color's own model; Export for Screens has Include Artboard Fill beside Include Bleed (on by default, remembered; `includeArtboardFill`, also on `document.export` and `file.print`); editing data keeps the color as the artboard's, and Export for Screens' document rows keep it too; evidence updated; scores unchanged. | | 2026-11-01 | minor | Selection: Select › Start Global Edit on a group takes the groups like it (the same objects at the same places, moved or scaled; Appearance, Size and the artboard options apply) and gives an edit made to an object inside one to the object at its place in each of the others, in proportion, as one undo step (#4939); Global Edit of rotated copies and Shift-click exclusion remain. Score unchanged at 85% (estimated), hours unchanged. | diff --git a/docs/type-parity.md b/docs/type-parity.md index f6c4a2c7b3..521d216855 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Digits: the native digits of the Indic scripts, #4942; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Area Type Options › Text Flow by rows or by columns, #4978; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -21,7 +21,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Soft return (forced line break, Shift+Enter) | done | Shift+Enter inserts a soft return (U+2028), breaking the line without starting a new paragraph; paragraph spacing (space before/after) and first-line indents apply only at paragraph ends; continuation lines in lists do not repeat the marker; soft return lines in justified text do not spread (#2754) | | Native font-family labels | partial | With Show Font Names in English off, localized legacy names are used when typographic names contain no native label (#2208); loaded-font and catalog-only regressions. Choosing among multiple native languages is unchanged. | | Point, area and type-on-a-path type; vertical variants | done / partial | vertical point, area and path type have initial support; fullwidth `!` / `?` keep the nominal glyph upright when no vertical alternate exists (Unicode Tu); in a non-rectangular area a word too wide for the top lines moves down to the first line that holds it (#1615); Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802); `text.create` and `text.createInPath` take `justify` (#1752); MCP `add_text` forwards `vertical` to both commands | -| Area Type Options (rows, columns, inset, first baseline, Auto Size, Shrink Text to Fit) | done | the commands that make or restyle type say when it does not fit its frame; MCP `add_text` takes Auto Size and Shrink Text to Fit (#1471) | +| Area Type Options (rows, columns, inset, first baseline, Text Flow by rows or by columns, Auto Size, Shrink Text to Fit) | done | Text Flow fills the cells down each column first (By Columns, the default, as files from before it open) or across each row first (By Rows), in the dialog and `text.areaOptions {flow}` (#4978); the commands that make or restyle type say when it does not fit its frame; MCP `add_text` takes Auto Size and Shrink Text to Fit (#1471) | | Threaded text, Fit Headline, Text Wrap | done | Fit Headline sees wrapping in a frame one line tall (#1444); a thread holds area type and type on a path in any mix, as Illustrator links type in an area or along a path ([help](https://helpx.adobe.com/illustrator/using/manage-text-area.html)) | | Threading from the ports: selected area type and type on a path show an in port and an out port, empty, with an arrow on a side where the frame is threaded, or with a red "+" in the out port when the text doesn't fit; a click on either port loads the text; a click on a closed path, area type or type on a path threads into it, a click on empty canvas makes a frame of the same kind, shape and size there, a drag draws a rectangular frame; the frame placed comes after the clicked one from its out port and before it from its in port (the story then starts there); Escape or another tool cancels; a double-click on a threaded port breaks the thread there | partial | #2572: the Selection tool, `text.thread.add {from, to?, rect?, at?, before?}`, as the reference app's help describes ports and threading ([archived help, Threading text between objects](https://web.archive.org/web/20210119051048/https://helpx.adobe.com/illustrator/using/creating-text.html), [create text threads](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html)); area type's in port sits on the left side below the top-left corner, type on a path's just before its start bracket; Show Text Threads draws its lines between the same ports; with more than 1,000 such objects selected no ports are drawn. a double-click on a port where the frame is threaded breaks the thread there, the story flowing into the frames before the break and the frames after it left empty, still threaded with each other when two or more (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)). Remaining: the ports only take clicks with the Selection tool, and the loaded cursor borrows the I-beam until it's drawn | | Type on a Path effects and options; brackets | done | #429 | @@ -72,6 +72,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Area Type Options › Text Flow (#4978): By Rows / By Columns radio buttons and `text.areaOptions {flow}`; area type with several rows and columns fills them across each row first or down each column first (the default, so existing documents are unchanged; saved only when by rows); scores unchanged | | 2026-11-01 | minor | Digits (#4942): the native digits of Devanagari, Bengali, Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada and Malayalam in the Character panel menu › Digits and `{digits}`; scores unchanged | | 2026-11-01 | minor | Language per character (#4946): Character panel › Language, `text.setFormat` / `text.setRangeStyle {language}`, character styles; text is shaped in its language (`locl`, #4940); new type takes the document's; Indian languages in the list (#4943); scores unchanged | | 2026-10-31 | minor | PDF import finds an installed font whose PDF name holds hyphens (`Noto-Sans-Bold` is Noto Sans, Bold: the longest part before a hyphen that names an installed family) and a composite font by its CIDFont's name rather than its base name, which ends in the CMap's (`Name-Identity-H`, [ISO 32000-1 §9.7.6.1](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)); a missing font is split only before a style part (`Helvetica-BoldOblique`), so it is reported as `MS PGothic`, not `MS`; scores unchanged | From 1840b9a58266ef986e4d8f356675501ab57395de Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 14:45:38 -0700 Subject: [PATCH 205/260] EPS export: gradients of spot colors keep their spot inks EPS export wrote every gradient with a spot color stop in process colors. A gradient of tints of one spot color and paper white is now written in that ink's Separation space, at Level 2 and 3. At Level 3, a gradient that mixes a spot color with CMYK or gray colors, or two spot colors, is written in a DeviceN space of the process inks its stops use and the spot inks, each spot ink with the CMYK equivalent its Separation space has. An off-center midpoint is a stop with the inks halfway between its two stops. Paper white is an exact white, whether or not the stop is linked to a process swatch. These gradients are still written in process colors, each with its own warning: a mix with other inks at Level 2; a mix with RGB or Lab colors in an RGB export (a CMYK export converts those stops to CMYK first); a DeviceN space that would need more than 32 colorants or a spot ink named Cyan, Magenta, Yellow, Black, All or None; and a Perceptual gradient. The old warning for every spot gradient has been removed. The header lists two or more spot colors with each %%+ line right after the comment it continues: %%DocumentCustomColors and %%CMYKCustomColor were interleaved, so a DSC reader took the second ink's name as part of the first ink's %%CMYKCustomColor. --- crates/eps/src/lib.rs | 7 +- crates/eps/src/scene.rs | 296 ++++++++++++++++++++++++++++++++------ crates/eps/src/tests.rs | 241 ++++++++++++++++++++++++++++++- docs/target-app-parity.md | 1 + 4 files changed, 498 insertions(+), 47 deletions(-) diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 59926fe188..2b828e0932 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -263,10 +263,13 @@ pub(crate) fn comments(s: &mut String, title: &str, created: Option<i64>, level: } let _ = writeln!(s, "%%LanguageLevel: {}", level.id()); s.push_str("%%DocumentData: Clean7Bit\n"); - for (i, (name, cmyk)) in custom.iter().enumerate() { + // Each `%%+` line continues the comment right above it. + for (i, (name, _)) in custom.iter().enumerate() { let _ = writeln!(s, "{}{}", if i == 0 { "%%DocumentCustomColors: " } else { "%%+ " }, ps::string(name)); + } + for (i, (name, cmyk)) in custom.iter().enumerate() { let [c, m, y, k] = cmyk.map(|v| ps::num(f64::from(v))); - let _ = writeln!(s, "%%CMYKCustomColor: {c} {m} {y} {k} {}", ps::string(name)); + let _ = writeln!(s, "{}{c} {m} {y} {k} {}", if i == 0 { "%%CMYKCustomColor: " } else { "%%+ " }, ps::string(name)); } } diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index f99aea9239..b5437b6700 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -37,7 +37,13 @@ const IMAGE_PARTLY: &str = "partly transparent image pixels are written over whi /// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`). const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; const LARGE_IMAGE: &str = "an image that is too large for EPS was left out"; -const SPOT_GRADIENTS: &str = "gradients of spot colours are written in process colours"; +const SPOT_GRADIENTS_RGB: &str = "gradients mixing a spot color with RGB or Lab colors are written without the spot ink"; +const SPOT_GRADIENTS_L2: &str = + "gradients mixing a spot color with other inks are written in process colors at PostScript Level 2 (Level 3 keeps the spot inks)"; +const SPOT_GRADIENTS_SHARED: &str = "gradients whose spot inks can't share a DeviceN color space are written without the spot inks"; +const SPOT_GRADIENTS_PERCEPTUAL: &str = "Perceptual gradients of spot colors are written in process colors"; +/// The most colorants a DeviceN color space may have (PostScript's limit). +const MAX_DEVICE_N: usize = 32; const MISSING_PATTERN: &str = "missing patterns are written as mid-grey"; const TOO_LARGE: &str = "the artwork is too large for EPS: what follows 256 MB of PostScript was left out"; /// The most PostScript the page body may grow to: symbols and patterns that hold one another @@ -78,6 +84,29 @@ impl Space { } } +/// The color space a gradient's stops are written in: a process space, or one defined in the +/// setup (a spot color's Separation space or a DeviceN space of spot and process inks) by name, +/// with its number of components. +#[derive(Clone, Debug, PartialEq)] +enum GradientSpace { + Process(Space), + Inks(String, usize), +} + +impl GradientSpace { + fn n(&self) -> usize { + match self { + GradientSpace::Process(s) => s.n(), + GradientSpace::Inks(_, n) => *n, + } + } +} + +/// A gradient's stops as written: offsets from 0 to 1 and the components in its space. +type Stops = Vec<(f64, Vec<f32>)>; +/// A gradient's stops before their offsets are put in order and run from 0 to 1. +type RawStops = Vec<(f32, Vec<f32>)>; + /// A colour as written: in a process space (its first [`Space::n`] components) or a tint of a /// spot colour space defined in the setup. #[derive(Clone, Copy, Debug, PartialEq)] @@ -115,6 +144,8 @@ pub(crate) struct Scene<'a> { setup: String, /// Spot colour spaces defined in the setup (`VCsp<i>`): swatch name and CMYK equivalent. spots: Vec<(String, [f32; 4])>, + /// DeviceN color spaces defined in the setup (`VCdn<i>`), as their definitions. + device_n: Vec<String>, warnings: Vec<String>, brushes: Option<Vec<vectorcraft_brush::Brush>>, /// Image keys → what draws them (`None`: left out). @@ -136,6 +167,7 @@ impl<'a> Scene<'a> { body: String::new(), setup: String::new(), spots: vec![], + device_n: vec![], warnings: vec![], brushes: None, images: HashMap::new(), @@ -659,14 +691,189 @@ impl<'a> Scene<'a> { /// The colour space a gradient's stops are written in, and its stops in it from offset 0 to 1 /// (midpoints as stops of their own). - fn gradient_stops(&mut self, g: &vectorcraft_color::Gradient) -> (Space, Vec<(f64, [f32; 4])>) { + fn gradient_stops(&mut self, g: &vectorcraft_color::Gradient) -> (GradientSpace, Stops) { if g.stops.iter().any(|s| s.opacity < 1.0) { self.warn(TRANSPARENCY); } - let doc = self.doc; - if g.stops.iter().any(|s| s.swatch.as_deref().is_some_and(|n| doc.swatch(n).is_some_and(|w| w.spot))) { - self.warn(SPOT_GRADIENTS); + let (space, raw) = match self.ink_stops(g) { + Some(inks) => inks, + None => { + let (space, raw) = self.process_stops(g); + (GradientSpace::Process(space), raw) + } + }; + let mut out: Stops = vec![]; + let mut last = 0.0f64; + for (o, c) in raw { + let o = if o.is_finite() { f64::from(o).clamp(last, 1.0) } else { last }; + last = o; + out.push((o, c)); } + match (out.first().cloned(), out.last().cloned()) { + (Some(first), Some(end)) => { + if first.0 > 0.0 { + out.insert(0, (0.0, first.1)); + } + if end.0 < 1.0 { + out.push((1.0, end.1)); + } + } + _ => out = vec![(0.0, vec![0.0; space.n()]), (1.0, vec![0.0; space.n()])], + } + (space, out) + } + + /// The stops of a gradient with a spot ink as tints of its inks: a Separation space when every + /// stop is a tint of one spot ink or paper white, else (at Level 3) a DeviceN space of the + /// process inks the stops use, in CMYK order, and the spot inks, in the order the stops name + /// them. Paper white adds no ink and a gray stop is black ink. An off-center midpoint is a stop + /// with the inks halfway between its two stops. `None` for a gradient without a spot ink, and, + /// with a warning, for one whose inks can't be kept or that is mixed by the Perceptual method; + /// it is then written in process colors. + fn ink_stops(&mut self, g: &vectorcraft_color::Gradient) -> Option<(GradientSpace, RawStops)> { + let doc = self.doc; + let spot_of = |s: &vectorcraft_color::GradientStop| -> Option<String> { + s.swatch.as_deref().filter(|n| doc.swatch(n).is_some_and(|w| w.spot)).map(str::to_string) + }; + // The spot inks, collected up to one more than a DeviceN space can hold. + let mut names: Vec<String> = vec![]; + for s in &g.stops { + if let Some(n) = spot_of(s) + && !names.contains(&n) + { + names.push(n); + if names.len() > MAX_DEVICE_N { + break; + } + } + } + if names.is_empty() { + return None; + } + if !g.method.is_classic() { + self.warn(SPOT_GRADIENTS_PERCEPTUAL); + return None; + } + if names.len() > MAX_DEVICE_N { + self.warn(SPOT_GRADIENTS_SHARED); + return None; + } + // Paper white exactly: any ink at all, however little, is kept. + let paper = |c: &Color| match *c { + Color::Gray { k } => k <= 0.0, + Color::Cmyk { c, m, y, k } => [c, m, y, k].iter().all(|&v| v <= 0.0), + Color::Rgb { r, g, b } => [r, g, b].iter().all(|&v| v >= 1.0), + Color::Lab { l, a, b } => l >= 100.0 && a == 0.0 && b == 0.0, + }; + // Each stop's ink coverage: the four process inks, then one tint per spot ink. + let mut inks: Vec<Vec<f32>> = Vec::with_capacity(g.stops.len()); + for s in &g.stops { + let mut v = vec![0.0; 4 + names.len()]; + match spot_of(s) { + Some(n) => { + if let Some(i) = names.iter().position(|m| *m == n) { + v[4 + i] = unit(s.tint); + } + } + None if paper(&s.color) => {} + None => match self.process(&s.color) { + Ink::Process(Space::Cmyk, c) => v[..4].copy_from_slice(&c), + Ink::Process(Space::Gray, [lightness, ..]) => v[3] = unit(1.0 - lightness), + _ => { + self.warn(SPOT_GRADIENTS_RGB); + return None; + } + }, + } + inks.push(v); + } + let process: Vec<usize> = (0..4).filter(|&i| inks.iter().any(|v| v[i] > 0.0)).collect(); + let space = if let ([name], true) = (names.as_slice(), process.is_empty()) { + let Some(i) = self.spot_space(name) else { + self.warn(SPOT_GRADIENTS_SHARED); + return None; + }; + GradientSpace::Inks(format!("VCsp{i}"), 1) + } else if self.o.level != Level::Three { + self.warn(SPOT_GRADIENTS_L2); + return None; + } else { + let Some(space) = self.device_n_space(&process, &names) else { + self.warn(SPOT_GRADIENTS_SHARED); + return None; + }; + space + }; + let pick = |v: &[f32]| -> Vec<f32> { process.iter().map(|&i| v[i]).chain(v[4..].iter().copied()).collect() }; + let mut out = vec![]; + for (i, s) in g.stops.iter().enumerate() { + out.push((s.offset, pick(&inks[i]))); + if let (Some(n), Some(next)) = (g.stops.get(i + 1), inks.get(i + 1)) + && (s.midpoint - 0.5).abs() > 1e-3 + { + let half: Vec<f32> = inks[i].iter().zip(next).map(|(a, b)| (a + b) / 2.0).collect(); + out.push((s.offset + (n.offset - s.offset) * s.midpoint, pick(&half))); + } + } + Some((space, out)) + } + + /// A DeviceN color space of process inks `process` (indices into CMYK) and spot inks `names`, + /// defined in the setup the first time, each spot ink with the CMYK equivalent its Separation + /// space has. `None` when a spot ink has no Separation space, two colorants share a name, a + /// spot ink has the name of a process ink, `All` or `None`, or there are more than + /// [`MAX_DEVICE_N`] colorants. + fn device_n_space(&mut self, process: &[usize], names: &[String]) -> Option<GradientSpace> { + const PROCESS: [&str; 4] = ["Cyan", "Magenta", "Yellow", "Black"]; + if process.len() + names.len() > MAX_DEVICE_N { + return None; + } + let mut colorants: Vec<&str> = process.iter().map(|&i| PROCESS[i]).collect(); + let mut weights: Vec<[f32; 4]> = process.iter().map(|&i| [0, 1, 2, 3].map(|j| if i == j { 1.0 } else { 0.0 })).collect(); + for (i, name) in names.iter().enumerate() { + if PROCESS.contains(&name.as_str()) || name == "All" || name == "None" || names[..i].contains(name) { + return None; + } + } + for name in names { + colorants.push(name); + let i = self.spot_space(name)?; + weights.push(self.spots.get(i)?.1); + } + let mut def = String::from("[/DeviceN ["); + for (i, c) in colorants.iter().enumerate() { + if i < process.len() { + let _ = write!(def, "/{c} "); + } else { + let _ = write!(def, "{} cvn ", ps::string(c)); + } + } + // The tint transform: the components into an array, then each CMYK ink the sum of the + // components times their amounts of it. + let n = weights.len(); + let _ = write!(def, "] /DeviceCMYK {{{n} array astore"); + for j in 0..4 { + def.push_str(" 0"); + for (i, w) in weights.iter().enumerate().filter(|(_, w)| w[j] > 0.0) { + let _ = write!(def, " {} index {i} get {} mul add", j + 1, ps::num(f64::from(w[j]))); + } + } + def.push_str(" 5 -1 roll pop}]"); + let i = match self.device_n.iter().position(|d| *d == def) { + Some(i) => i, + None => { + let i = self.device_n.len(); + let _ = writeln!(self.setup, "/VCdn{i} {def} def"); + self.device_n.push(def); + i + } + }; + Some(GradientSpace::Inks(format!("VCdn{i}"), n)) + } + + /// The process color space a gradient's stops are written in, and its stops in it (midpoints + /// as stops of their own). + fn process_stops(&mut self, g: &vectorcraft_color::Gradient) -> (Space, RawStops) { let stops = g.expanded_stops(); let space = if self.cmyk || stops.iter().any(|(_, c, _)| matches!(c, Color::Cmyk { .. })) { Space::Cmyk @@ -686,24 +893,7 @@ impl<'a> Scene<'a> { } } }; - let mut out: Vec<(f64, [f32; 4])> = vec![]; - let mut last = 0.0f64; - for (o, c, _) in &stops { - let o = if o.is_finite() { f64::from(*o).clamp(last, 1.0) } else { last }; - last = o; - out.push((o, comps(c))); - } - match (out.first().copied(), out.last().copied()) { - (Some(first), Some(end)) => { - if first.0 > 0.0 { - out.insert(0, (0.0, first.1)); - } - if end.0 < 1.0 { - out.push((1.0, end.1)); - } - } - _ => out = vec![(0.0, [0.0; 4]), (1.0, [0.0; 4])], - } + let out = stops.iter().map(|(o, c, _)| (*o, comps(c)[..space.n()].to_vec())).collect(); (space, out) } @@ -714,11 +904,12 @@ impl<'a> Scene<'a> { let (space, stops) = self.gradient_stops(&g.gradient); if !stops.windows(2).any(|w| w[1].0 > w[0].0) { if let Some((_, c)) = stops.first() { - self.set_comps(space, *c); + self.set_comps(&space, c); self.rect_fill(area); } return; } + let space = &space; let smooth = self.o.level == Level::Three && !self.o.compatible_gradients; match g.gradient.kind { GradientKind::Radial => { @@ -750,9 +941,9 @@ impl<'a> Scene<'a> { } /// A Level 3 smooth shading of `kind` (2 axial, 3 radial) at `coords`, extended both ways. - fn shading(&mut self, kind: u8, space: Space, coords: &[f64], stops: &[(f64, [f32; 4])]) { + fn shading(&mut self, kind: u8, space: &GradientSpace, coords: &[f64], stops: &[(f64, Vec<f32>)]) { let n = space.n(); - let comps = |c: &[f32; 4]| -> String { + let comps = |c: &[f32]| -> String { let mut s = String::from("["); push_nums(&mut s, &c.iter().take(n).map(|v| f64::from(*v)).collect::<Vec<_>>()); s.pop(); @@ -760,7 +951,7 @@ impl<'a> Scene<'a> { s }; let segments: Vec<_> = stops.windows(2).filter(|w| w[1].0 > w[0].0).collect(); - let interp = |w: &&[(f64, [f32; 4])]| format!("<< /FunctionType 2 /Domain [0 1] /C0 {} /C1 {} /N 1 >>", comps(&w[0].1), comps(&w[1].1)); + let interp = |w: &&[(f64, Vec<f32>)]| format!("<< /FunctionType 2 /Domain [0 1] /C0 {} /C1 {} /N 1 >>", comps(&w[0].1), comps(&w[1].1)); let function = match segments.as_slice() { [one] => interp(one), many => { @@ -778,27 +969,44 @@ impl<'a> Scene<'a> { f } }; - let _ = write!(self.body, "<< /ShadingType {kind} /ColorSpace {} /Coords [", space.name()); + let name = match space { + GradientSpace::Process(s) => s.name(), + GradientSpace::Inks(name, _) => name, + }; + let _ = write!(self.body, "<< /ShadingType {kind} /ColorSpace {name} /Coords ["); push_nums(&mut self.body, coords); let _ = writeln!(self.body, "] /Extend [true true]\n/Function {function} >> shfill"); } /// The bands of each stretch between stops: how many, for colours `a` to `b` over `length` /// points (one per colour level, none thinner than [`MIN_BAND`]). - fn bands(a: &[f32; 4], b: &[f32; 4], length: f64, segments: usize) -> usize { + fn bands(a: &[f32], b: &[f32], length: f64, segments: usize) -> usize { let delta = a.iter().zip(b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max); let by_color = (f64::from(delta) * 255.0).ceil().max(1.0) as usize; let by_size = (length / MIN_BAND).ceil().max(1.0) as usize; by_color.min(by_size).min(MAX_STEPS / segments.max(1)).max(1) } - fn set_comps(&mut self, space: Space, c: [f32; 4]) { - self.set_ink(Ink::Process(space, c)); + fn set_comps(&mut self, space: &GradientSpace, c: &[f32]) { + match space { + GradientSpace::Process(s) => { + let mut v = [0.0; 4]; + for (x, y) in v.iter_mut().zip(c) { + *x = *y; + } + self.set_ink(Ink::Process(*s, v)); + } + GradientSpace::Inks(name, _) => { + let _ = write!(self.body, "{name} setcolorspace "); + push_nums(&mut self.body, &c.iter().map(|v| f64::from(*v)).collect::<Vec<_>>()); + self.line("setcolor"); + } + } } /// A linear gradient from `s` to `e` as bands across it, covering `area`: each band painted /// from where it starts to the far end, so the next one leaves no seam. - fn linear_steps(&mut self, s: Point, e: Point, area: Rect, space: Space, stops: &[(f64, [f32; 4])]) { + fn linear_steps(&mut self, s: Point, e: Point, area: Rect, space: &GradientSpace, stops: &[(f64, Vec<f32>)]) { let d = e - s; let len = d.hypot(); // Gradient space: x along the gradient (0 to 1), y across it in points. @@ -812,21 +1020,21 @@ impl<'a> Scene<'a> { sc.line("rectfill"); }; if let Some((_, c)) = stops.first() { - self.set_comps(space, *c); + self.set_comps(space, c); band(self, t0); } let segments: Vec<_> = stops.windows(2).filter(|w| w[1].0 > w[0].0).collect(); for w in &segments { - let ((oa, ca), (ob, cb)) = (w[0], w[1]); - let n = Self::bands(&ca, &cb, (ob - oa) * len, segments.len()); + let ((oa, ca), (ob, cb)) = (&w[0], &w[1]); + let n = Self::bands(ca, cb, (ob - oa) * len, segments.len()); for k in 0..n { let at = oa + (ob - oa) * k as f64 / n as f64; - self.set_comps(space, mix(&ca, &cb, (k as f32 + 0.5) / n as f32)); + self.set_comps(space, &mix(ca, cb, (k as f32 + 0.5) / n as f32)); band(self, at); } } if let Some((_, c)) = stops.last() { - self.set_comps(space, *c); + self.set_comps(space, c); band(self, 1.0); } self.line("Q"); @@ -834,18 +1042,18 @@ impl<'a> Scene<'a> { /// A radial gradient from focal point `f` to the circle of radius `r` around `c` as discs, /// largest first, over the last colour across `area` (all in the gradient's own space). - fn radial_steps(&mut self, f: Point, c: Point, r: f64, area: Rect, space: Space, stops: &[(f64, [f32; 4])]) { + fn radial_steps(&mut self, f: Point, c: Point, r: f64, area: Rect, space: &GradientSpace, stops: &[(f64, Vec<f32>)]) { if let Some((_, last)) = stops.last() { - self.set_comps(space, *last); + self.set_comps(space, last); self.rect_fill(area); } let segments: Vec<_> = stops.windows(2).filter(|w| w[1].0 > w[0].0).collect(); for w in segments.iter().rev() { - let ((oa, ca), (ob, cb)) = (w[0], w[1]); - let n = Self::bands(&ca, &cb, (ob - oa) * r, segments.len()); + let ((oa, ca), (ob, cb)) = (&w[0], &w[1]); + let n = Self::bands(ca, cb, (ob - oa) * r, segments.len()); for k in (0..n).rev() { let t = oa + (ob - oa) * (k + 1) as f64 / n as f64; - self.set_comps(space, mix(&ca, &cb, (k as f32 + 0.5) / n as f32)); + self.set_comps(space, &mix(ca, cb, (k as f32 + 0.5) / n as f32)); let at = f + (c - f) * t; push_nums(&mut self.body, &[at.x, at.y, r * t]); self.line("0 360 newpath arc fill"); @@ -1145,6 +1353,6 @@ impl<'a> Scene<'a> { } /// `a` to `b` at `t`. -fn mix(a: &[f32; 4], b: &[f32; 4], t: f32) -> [f32; 4] { - [0, 1, 2, 3].map(|i| a[i] + (b[i] - a[i]) * t) +fn mix(a: &[f32], b: &[f32], t: f32) -> Vec<f32> { + a.iter().zip(b).map(|(x, y)| x + (y - x) * t).collect() } diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 6d1331c2f9..5b89922d58 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -3,7 +3,7 @@ use std::sync::Arc; -use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint, Swatch}; +use vectorcraft_color::{Color, Gradient, GradientKind, GradientMethod, GradientPaint, GradientStop, Paint, Swatch}; use vectorcraft_doc::{Appearance, AppearanceItem, Dash, Document, ImageBlob, ImageObject, LineCap, LineJoin, Node, NodeKind}; use vectorcraft_geom::{Affine, PathData, Point, Rect, shapes}; @@ -240,6 +240,245 @@ fn spot_colours_are_separations_and_overprints_are_kept_or_dropped() { assert!(!page_of(&d, &EpsOptions { overprint: Overprint::Discard, ..opts(&d) }).contains("true op")); } +const GOLD: Color = Color::Cmyk { c: 0.0, m: 0.2, y: 0.8, k: 0.1 }; +const LEAF: Color = Color::Cmyk { c: 1.0, m: 0.0, y: 1.0, k: 0.0 }; + +/// A stop linked to spot swatch `name` (of color `color`) at `tint`. +fn spot_stop(offset: f32, name: &str, color: Color, tint: f32) -> GradientStop { + GradientStop { swatch: Some(name.into()), tint, ..GradientStop::new(offset, color.tinted(tint)) } +} + +/// A document with the spot swatches Gold Ink and Leaf Ink and a rectangle filled with a linear +/// gradient of `stops`. +fn spot_gradient_doc(stops: Vec<GradientStop>) -> Document { + spot_gradient_doc_of(Gradient::new(GradientKind::Linear, stops)) +} + +/// [`spot_gradient_doc`] with the rectangle filled with `gradient`. +fn spot_gradient_doc_of(gradient: Gradient) -> Document { + let mut d = doc_with(|_| vec![]); + d.swatches.push(Swatch { name: "Gold Ink".into(), paint: Paint::solid(GOLD), global: true, spot: true }); + d.swatches.push(Swatch { name: "Leaf Ink".into(), paint: Paint::solid(LEAF), global: true, spot: true }); + let paint = Paint::Gradient(Box::new(GradientPaint::new(gradient))); + let n = path(&mut d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 120.0)), paint, Paint::None, 0.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, n).unwrap(); + d +} + +/// The solid fill colors of the objects of `d`, down through groups. +fn fill_colors(d: &Document) -> Vec<Color> { + fn walk(n: &Node, out: &mut Vec<Color>) { + for i in &n.appearance.items { + if let AppearanceItem::Fill(f) = i + && let Some(c) = f.paint.color() + { + out.push(c); + } + } + for c in n.children().into_iter().flatten() { + walk(c, out); + } + } + let mut out = vec![]; + for l in &d.layers { + walk(l, &mut out); + } + out +} + +/// Whether one of `colors` is CMYK `want`, to within rounding. +fn has_cmyk(colors: &[Color], want: [f32; 4]) -> bool { + colors.iter().any(|c| matches!(*c, Color::Cmyk { c, m, y, k } if [c, m, y, k].iter().zip(want).all(|(a, b)| (a - b).abs() < 2e-3))) +} + +#[test] +fn a_gradient_of_one_spot_ink_is_a_separation_shading() { + let d = spot_gradient_doc(vec![ + spot_stop(0.0, "Gold Ink", GOLD, 1.0), + spot_stop(0.5, "Gold Ink", GOLD, 0.2), + GradientStop::new(1.0, Color::rgb(1.0, 1.0, 1.0)), + ]); + let out = export(&d, &opts(&d), None, None).unwrap(); + let ps = text(&out); + assert_eq!(dsc(&ps, "DocumentCustomColors").as_deref(), Some("(Gold Ink)")); + assert!(ps.contains("/VCsp0 [/Separation (Gold Ink) cvn /DeviceCMYK"), "{ps}"); + let page = checked_page(&ps); + assert!(page.contains("/ShadingType 2 /ColorSpace VCsp0 /Coords"), "{page}"); + assert!(page.contains("/C0 [1] /C1 [0.2]") && page.contains("/C0 [0.2] /C1 [0]"), "tints of Gold Ink to paper: {page}"); + assert!(!out.warnings.iter().any(|w| w.contains("spot")), "{:?}", out.warnings); + // Level 2: bands of the ink's tints. + let out = export(&d, &EpsOptions { level: Level::Two, ..opts(&d) }, None, None).unwrap(); + let page = checked_page(&text(&out)); + assert!(!page.contains("shfill") && !page.contains(" k\n"), "{page}"); + assert!(page.contains("VCsp0 setcolorspace 1 setcolor\n") && page.contains("VCsp0 setcolorspace 0 setcolor\n"), "{page}"); + assert!(!out.warnings.iter().any(|w| w.contains("spot")), "{:?}", out.warnings); +} + +#[test] +fn gradients_mixing_spot_inks_with_other_inks_are_device_n_shadings() { + // Gold Ink, with its midpoint at 30%, to Leaf Ink at 50%. + let mut gold = spot_stop(0.0, "Gold Ink", GOLD, 1.0); + gold.midpoint = 0.3; + let two = spot_gradient_doc(vec![gold, spot_stop(1.0, "Leaf Ink", LEAF, 0.5)]); + let out = export(&two, &opts(&two), None, None).unwrap(); + let ps = text(&out); + assert!( + ps.contains("%%DocumentCustomColors: (Gold Ink)\n%%+ (Leaf Ink)\n%%CMYKCustomColor: 0 0.2 0.8 0.1 (Gold Ink)\n%%+ 1 0 1 0 (Leaf Ink)\n"), + "both inks, each list continued right below its comment: {ps}" + ); + assert!( + ps.contains( + "/VCdn0 [/DeviceN [(Gold Ink) cvn (Leaf Ink) cvn ] /DeviceCMYK {2 array astore 0 1 index 1 get 1 mul add \ + 0 2 index 0 get 0.2 mul add 0 3 index 0 get 0.8 mul add 3 index 1 get 1 mul add 0 4 index 0 get 0.1 mul add 5 -1 roll pop}] def" + ), + "{ps}" + ); + let page = checked_page(&ps); + assert!(page.contains("/ShadingType 2 /ColorSpace VCdn0 /Coords") && page.contains("/Bounds [0.3 ]"), "{page}"); + assert!(page.contains("/C0 [1 0] /C1 [0.5 0.25]") && page.contains("/C0 [0.5 0.25] /C1 [0 0.5]"), "the inks through the midpoint: {page}"); + assert!(!out.warnings.iter().any(|w| w.contains("spot")), "{:?}", out.warnings); + + // Gold Ink to 60% process yellow to 40% gray: Yellow, Black and Gold Ink. + let mixed = spot_gradient_doc(vec![ + spot_stop(0.0, "Gold Ink", GOLD, 1.0), + GradientStop::new(0.5, Color::cmyk(0.0, 0.0, 0.6, 0.0)), + GradientStop::new(1.0, Color::Gray { k: 0.4 }), + ]); + let out = export(&mixed, &opts(&mixed), None, None).unwrap(); + let ps = text(&out); + assert!(ps.contains("/VCdn0 [/DeviceN [/Yellow /Black (Gold Ink) cvn ] /DeviceCMYK {3 array astore"), "{ps}"); + let page = checked_page(&ps); + assert!(page.contains("/C0 [0 0 1] /C1 [0.6 0 0]") && page.contains("/C0 [0.6 0 0] /C1 [0 0.4 0]"), "{page}"); + assert!(!out.warnings.iter().any(|w| w.contains("spot")), "{:?}", out.warnings); + + // Read back as bands, the tint transforms give each ink's CMYK equivalent. + for (d, end) in [(&two, [0.5, 0.0, 0.5, 0.0]), (&mixed, [0.0, 0.0, 0.0, 0.4])] { + let out = export(d, &EpsOptions { compatible_gradients: true, ..opts(d) }, None, None).unwrap(); + let page = checked_page(&text(&out)); + assert!(page.contains("VCdn0 setcolorspace ") && !page.contains("shfill"), "{page}"); + let colors = fill_colors(&import(&out.bytes).unwrap().document); + assert!(has_cmyk(&colors, [0.0, 0.2, 0.8, 0.1]) && has_cmyk(&colors, end), "{colors:?}"); + } + + // Level 2 has no DeviceN: process colors, with a warning. + let out = export(&two, &EpsOptions { level: Level::Two, ..opts(&two) }, None, None).unwrap(); + assert!(!text(&out).contains("DeviceN")); + assert!(out.warnings.iter().any(|w| w.contains("process colors at PostScript Level 2")), "{:?}", out.warnings); +} + +#[test] +fn a_gradient_mixing_a_spot_ink_with_rgb_is_written_without_the_ink() { + let d = spot_gradient_doc(vec![spot_stop(0.0, "Gold Ink", GOLD, 1.0), GradientStop::new(1.0, Color::rgb(0.0, 1.0, 0.0))]); + let out = export(&d, &opts(&d), None, None).unwrap(); + let ps = text(&out); + assert!(!ps.contains("/Separation") && !ps.contains("/DeviceN"), "{ps}"); + assert!(out.warnings.iter().any(|w| w.contains("RGB or Lab colors are written without the spot ink")), "{:?}", out.warnings); + // Written as CMYK, the green stop mixes with the ink. + let out = export(&d, &EpsOptions { cmyk: true, ..opts(&d) }, None, None).unwrap(); + assert!(text(&out).contains("/ColorSpace VCdn0")); + assert!(!out.warnings.iter().any(|w| w.contains("spot")), "{:?}", out.warnings); +} + +#[test] +fn spot_inks_named_like_process_inks_all_or_none_are_not_device_n_colorants() { + for name in ["Cyan", "Black", "All", "None"] { + // Gold Ink to the spot ink, with no process ink in the stops. + let mut d = spot_gradient_doc(vec![spot_stop(0.0, "Gold Ink", GOLD, 1.0), spot_stop(1.0, name, LEAF, 1.0)]); + d.swatches.retain(|s| s.name != name); + d.swatches.push(Swatch { name: name.into(), paint: Paint::solid(LEAF), global: true, spot: true }); + let out = export(&d, &opts(&d), None, None).unwrap(); + let ps = text(&out); + assert!(!ps.contains("/DeviceN") && !ps.contains("/Separation"), "{name}: {ps}"); + assert!(out.warnings.iter().any(|w| w.contains("can't share a DeviceN color space")), "{name}: {:?}", out.warnings); + } +} + +#[test] +fn a_device_n_space_has_at_most_32_colorants() { + for (inks, device_n) in [(32, true), (33, false)] { + let names: Vec<String> = (0..inks).map(|i| format!("Ink {i}")).collect(); + let stops = names.iter().enumerate().map(|(i, n)| spot_stop(i as f32 / (inks - 1) as f32, n, LEAF, 1.0)).collect(); + let mut d = spot_gradient_doc(stops); + d.swatches.extend(names.iter().map(|n| Swatch { name: n.clone(), paint: Paint::solid(LEAF), global: true, spot: true })); + let out = export(&d, &opts(&d), None, None).unwrap(); + let ps = text(&out); + assert_eq!(ps.contains("/DeviceN [(Ink 0) cvn "), device_n, "{inks} inks: {ps}"); + assert_eq!(out.warnings.iter().any(|w| w.contains("can't share a DeviceN color space")), !device_n, "{:?}", out.warnings); + } +} + +#[test] +fn gradients_of_more_than_32_spot_inks_are_written_in_process_colors_at_every_level() { + // 400 stops over 40 inks. + let names: Vec<String> = (0..40).map(|i| format!("Ink {i}")).collect(); + let stops = (0..400).map(|i| spot_stop(i as f32 / 399.0, &names[i % names.len()], LEAF, 1.0)).collect(); + let mut d = spot_gradient_doc(stops); + d.swatches.extend(names.iter().map(|n| Swatch { name: n.clone(), paint: Paint::solid(LEAF), global: true, spot: true })); + for level in [Level::Three, Level::Two] { + let out = export(&d, &EpsOptions { level, ..opts(&d) }, None, None).unwrap(); + let ps = text(&out); + assert!(!ps.contains("/DeviceN") && !ps.contains("VCsp"), "{level:?}: {ps}"); + assert!(out.warnings.iter().any(|w| w.contains("can't share a DeviceN color space")), "{level:?}: {:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w.contains("PostScript Level 2")), "{level:?}: {:?}", out.warnings); + } +} + +#[test] +fn near_white_stops_next_to_a_spot_ink_keep_their_ink() { + let d = spot_gradient_doc(vec![spot_stop(0.0, "Gold Ink", GOLD, 1.0), GradientStop::new(1.0, Color::Gray { k: 0.001 })]); + let out = export(&d, &opts(&d), None, None).unwrap(); + let ps = text(&out); + assert!(ps.contains("/VCdn0 [/DeviceN [/Black (Gold Ink) cvn ]"), "{ps}"); + assert!(!out.warnings.iter().any(|w| w.contains("spot")), "{:?}", out.warnings); + // A near-white RGB stop is RGB, not paper. + let d = spot_gradient_doc(vec![spot_stop(0.0, "Gold Ink", GOLD, 1.0), GradientStop::new(1.0, Color::rgb(1.0, 1.0, 0.999))]); + let out = export(&d, &opts(&d), None, None).unwrap(); + assert!(out.warnings.iter().any(|w| w.contains("RGB or Lab colors are written without the spot ink")), "{:?}", out.warnings); +} + +#[test] +fn a_white_stop_linked_to_a_process_swatch_is_paper_next_to_a_spot_ink() { + let white = Color::rgb(1.0, 1.0, 1.0); + let mut d = spot_gradient_doc(vec![ + spot_stop(0.0, "Gold Ink", GOLD, 1.0), + GradientStop { swatch: Some("Paper".into()), ..GradientStop::new(1.0, white) }, + ]); + d.swatches.push(Swatch { name: "Paper".into(), paint: Paint::solid(white), global: true, spot: false }); + let out = export(&d, &opts(&d), None, None).unwrap(); + let page = checked_page(&text(&out)); + assert!(page.contains("/ShadingType 2 /ColorSpace VCsp0 /Coords"), "{page}"); + assert!(!out.warnings.iter().any(|w| w.contains("spot")), "{:?}", out.warnings); +} + +#[test] +fn perceptual_gradients_of_spot_inks_are_written_in_process_colors() { + let stops = vec![spot_stop(0.0, "Gold Ink", GOLD, 1.0), spot_stop(1.0, "Leaf Ink", LEAF, 1.0)]; + let mut perceptual = Gradient::new(GradientKind::Linear, stops.clone()); + perceptual.method = GradientMethod::Perceptual; + let d = spot_gradient_doc_of(perceptual); + let out = export(&d, &opts(&d), None, None).unwrap(); + let page = checked_page(&text(&out)); + assert!(!page.contains("VCdn") && !page.contains("VCsp"), "{page}"); + assert!(page.contains("/ColorSpace /DeviceCMYK"), "{page}"); + assert!(out.warnings.iter().any(|w| w.contains("Perceptual gradients of spot colors are written in process colors")), "{:?}", out.warnings); + // The in-between stops follow the Perceptual mix, as for a gradient without spot inks. + let process = |c: Color| GradientStop::new(0.0, c); + let mut plain = Gradient::new(GradientKind::Linear, vec![process(GOLD), GradientStop { offset: 1.0, ..process(LEAF) }]); + plain.method = GradientMethod::Perceptual; + let p = spot_gradient_doc_of(plain); + let plain_page = checked_page(&text(&export(&p, &opts(&p), None, None).unwrap())); + let shading = |s: &str| -> Option<String> { + let i = s.find("/ShadingType")?; + Some(s[i..i + s[i..].find("shfill")?].to_string()) + }; + assert!(shading(&page).is_some_and(|s| s.contains("/Bounds")), "{page}"); + assert_eq!(shading(&page), shading(&plain_page)); + // Classic keeps the inks. + let d = spot_gradient_doc(stops); + assert!(text(&export(&d, &opts(&d), None, None).unwrap()).contains("/ColorSpace VCdn0")); +} + #[test] fn rgb_is_written_as_cmyk_when_asked_and_in_cmyk_documents() { let d = doc_with(|d| vec![red_rect(d)]); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e90c39ef7a..f6ac63f8e3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1065,6 +1065,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The Open and Place dialogs list PostScript `.ps` files and `.epsf` files. A `.ps` file opens and places through the EPS reader (its first page), also when its header is only `%!`, as the `ps` format, which exports don't write (Print to PostScript does); an `.epsf` file opens and places as EPS. Copied in a file manager, these files paste as EPS, and `clipboard.importEps` also reads PostScript whose header is only `%!` (`crates/engine/src/cmd/fileio/tests_epsimport.rs`). `document.pdfInfo` reads an EPS, a `.ps` file or a `.ai` in PostScript form as one page the size of its bounding box (a US Letter page without one), and its `thumbnail: 1` is a PNG of what that page prints (`crates/engine/src/cmd/fileio/tests_pdfimport.rs`). - EPS export with Use Artboards writes a central EPS file of the whole document, bounded by its visible art, beside the file of each artboard when it writes two or more artboards; a document with no visible art gets only the artboard files (`crates/engine/src/cmd/fileio/tests_eps.rs`). + EPS export writes a linear or radial gradient of tints of one spot color (and paper white) in that ink's Separation space, at Level 2 and 3, and at Level 3 one that mixes a spot color with process or gray colors, or two spot colors, in a DeviceN space of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. At Level 2, such a mix is written in process colors with a warning. In an RGB export, a gradient that mixes a spot color with RGB or Lab colors is written without the spot ink, with a warning; a CMYK export converts those stops to CMYK first, and the gradient follows the rules above. A Perceptual gradient of spot colors, and a mix whose DeviceN space would need more than 32 inks or a spot color named Cyan, Magenta, Yellow, Black, All or None, are also written in process colors with a warning (`crates/eps/src/tests.rs`). - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - PCX files (`.pcx`) open and place, from the ZSoft PCX Technical Reference Manual: 1 bit in the header palette's first two colors (black and white when the version has no palette or both colors are the same), 1 bit in two to four planes and 4 bits with up to 16 colors from the header's palette (the EGA colors for versions 0 and 3), 2 bits in the CGA colors that the header's CGA palette settings pick (background, color burst, palette and intensity), 8 bits with the 256-color palette after the image data (gray levels without one) and 24-bit color in three planes, run-length encoded. The header's HDpi and VDpi size the image. A file of another depth or plane count, one cut short, and one whose pixels as RGBA pass the pixel allowance are refused with a message before its pixels are decoded. Open and Place recognize a PCX file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a PCX file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_pcxread.rs`). - JPEG 2000 JP2 and raw codestream images open and place from `.jpf`, `.jpx`, `.jp2`, `.j2k`, `.j2c` and `.jpc`. The last valid `resc` or `resd` resolution value wins on each axis; an axis with none uses 72 ppi. Multiple codestreams, JPX composition or layers, and unsupported color spaces are refused with a message. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_jp2read.rs`). From a425a893495b4baa14adc9dd2d6962cbc8bfc67e Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sun, 1 Nov 2026 01:47:53 +0300 Subject: [PATCH 206/260] Fix #4820: the Layers panel lists a blend's spine An open blend shows a <Spine> row below its key objects, where Release leaves the spine. A click selects the blend (Shift/Cmd toggles it), so Direct Selection edits the spine on the canvas; a locked blend's row selects nothing, and the row is left out while searching or filtering. --- crates/ui-egui/src/panels/layers.rs | 2 +- crates/ui-egui/src/panels/layers/model.rs | 31 ++++++++++++++-- crates/ui-egui/src/panels/layers/rows.rs | 44 +++++++++++++++++++++++ crates/ui-egui/src/panels/layers/tests.rs | 35 ++++++++++++++++++ docs/ui-parity.md | 4 ++- 5 files changed, 112 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 955eb04b75..f4282ea657 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -397,7 +397,7 @@ fn listed_when_opened(doc: &Document, open: &OpenRows, opts: &PanelOptions, quer } let mut rows = vec![]; push_rows(layer, 0, false, (Color32::PLACEHOLDER, true), (&open, opts, query, filter, doc), &mut rows); - rows.iter().any(|r| r.node.id == id && r.guide.is_none()) + rows.iter().any(|r| r.node.id == id && r.guide.is_none() && !r.spine) } /// The active document's uid and its last selected object, the one Locate Object locates. diff --git a/crates/ui-egui/src/panels/layers/model.rs b/crates/ui-egui/src/panels/layers/model.rs index 722391911c..bbafbb7559 100644 --- a/crates/ui-egui/src/panels/layers/model.rs +++ b/crates/ui-egui/src/panels/layers/model.rs @@ -63,6 +63,8 @@ pub(super) struct Row { pub(super) dim: bool, /// A ruler guide on the layer `node` (its index in the document's guides): the guide's row. pub(super) guide: Option<usize>, + /// The spine of blend `node`: its row, below the blend's key objects (#4820). + pub(super) spine: bool, } /// An object kind under the Filter's By Object (`ui.layersFilter`'s `objects`). @@ -262,10 +264,20 @@ pub(super) fn push_rows( let opens = opens(n, opts) || !guides.is_empty(); let open = opens && (narrowing || open_rows.contains(n.id)); let at = out.len(); - out.push(Row { node: n.clone(), depth, clip_path, opens, open, colour, dim: !shown || n.is_template(), guide: None }); + out.push(Row { node: n.clone(), depth, clip_path, opens, open, colour, dim: !shown || n.is_template(), guide: None, spine: false }); if open { for i in guides.into_iter().rev() { - out.push(Row { node: n.clone(), depth: depth + 1, clip_path: false, opens: false, open: false, colour, dim: !shown, guide: Some(i) }); + out.push(Row { + node: n.clone(), + depth: depth + 1, + clip_path: false, + opens: false, + open: false, + colour, + dim: !shown, + guide: Some(i), + spine: false, + }); } } if open && let Some(children) = n.children() { @@ -273,6 +285,21 @@ pub(super) fn push_rows( push_rows(c, depth + 1, i == 0 && n.clips(), (colour, shown), cx, out); } } + // A blend's spine is a row in it, below its key objects, as Release leaves it (not while + // searching or filtering: it is no object of its own). + if open && !narrowing && matches!(n.kind, NodeKind::Blend { .. }) { + out.push(Row { + node: n.clone(), + depth: depth + 1, + clip_path: false, + opens: false, + open: false, + colour, + dim: !shown, + guide: None, + spine: true, + }); + } // Searching or filtering, a row stays for a match of its own (its name holds the search text // and the filter keeps it) or for a row it keeps inside it. if narrowing && out.len() == at + 1 && !(filter.keeps(n) && (!searching || n.display_name().to_lowercase().contains(query))) { diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index f9e05716db..2c43a363a9 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -156,6 +156,47 @@ fn guide_row(ui: &mut Ui, view: &View, item: &Row, i: usize, out: &mut Out) { } } +/// The row of the spine of blend `item` (#4820): a path mark and `<Path>`, the selection square +/// while the blend is selected. A click selects the blend, whose spine Direct Selection then edits +/// on the canvas; Shift or Cmd adds it to (or takes it from) the selection. The spine of a hidden +/// or locked blend can't be selected. +fn spine_row(ui: &mut Ui, view: &View, item: &Row, out: &mut Out) { + let (t, h) = (&view.t, view.h); + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click()); + let blend = item.node.id; + let selected = view.sel.contains(&blend); + let editable = (view.doc.editable())(blend); + if editable && resp.hovered() { + ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.6)); + } + ui.painter().line_segment([r.left_bottom(), r.right_bottom()], Stroke::new(1.0, t.input_border)); + let mut x = r.left() + 2.0 * COLUMN + 2.0; + colour_bar(ui, &item.node, r, x, item.colour); + x += 6.0 + item.depth as f32 * INDENT + 16.0; + // The path mark: a short diagonal between two anchor dots. + let (a, b) = (egui::pos2(x + 2.0, r.center().y + 5.0), egui::pos2(x + 14.0, r.center().y - 5.0)); + ui.painter().line_segment([a, b], Stroke::new(1.5, t.accent)); + for p in [a, b] { + ui.painter().rect_filled(egui::Rect::from_center_size(p, vec2(3.0, 3.0)), 0.0, t.accent); + } + x += 22.0; + let name = format!("<{}>", tl!("Path")); + let color = if item.dim { t.text_dim } else { t.text }; + ui.painter().text(egui::pos2(x, r.center().y), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(13.0), color); + let col_x = r.right() - 43.5; + ui.painter().line_segment([egui::pos2(col_x, r.top()), egui::pos2(col_x, r.bottom())], Stroke::new(1.0, t.input_border)); + if selected { + let q = egui::Rect::from_center_size(egui::pos2(r.right() - SQUARE_X, r.center().y), vec2(7.0, 7.0)); + ui.painter().rect_filled(q, 0.0, item.colour); + ui.painter().rect_stroke(q, 0.0, Stroke::new(1.0, t.text), StrokeKind::Inside); + } + if editable && resp.clicked() { + let m = ui.input(|i| i.modifiers); + let action = if m.shift || m.command { "select.toggle" } else { "select.set" }; + out.actions.push((action.into(), json!({"ids": [blend.0]}))); + } +} + /// Guide rows `guides` dragged over row `r` (`resp`) of layer `layer`: the row lights up, and the /// release puts them on that layer (`guide.setLayer`, one undo step). fn guide_drop(ui: &Ui, view: &View, guides: &[usize], layer: NodeId, r: egui::Rect, resp: &egui::Response, out: &mut Out) { @@ -206,6 +247,9 @@ pub(super) fn row(ui: &mut Ui, view: &View, item: &Row, out: &mut Out) { if let Some(i) = item.guide { return guide_row(ui, view, item, i, out); } + if item.spine { + return spine_row(ui, view, item, out); + } let n = &*item.node; let (depth, clip_path, has_children, open, color) = (item.depth, item.clip_path, item.opens, item.open, item.colour); let doc = view.doc; diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index b78e6acc59..297afd6936 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -1591,3 +1591,38 @@ fn a_canvas_selection_reveals_its_active_layer() { app.session.active_mut().unwrap().active_layer = doc.layer_of(NodeId(rects[0])); assert!(shown(&mut app, &top) && !shown(&mut app, &bottom), "the highlighted row keeps the view"); } + +/// #4820: an open blend lists its spine below its key objects, and a click on the spine's row +/// selects the blend (whose spine Direct Selection edits); a locked blend's spine row selects +/// nothing, and searching leaves the row out. +#[test] +fn a_blends_spine_is_a_row_below_its_keys_that_selects_the_blend() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap(); + run(&mut app, "file.new", json!({"width": 300, "height": 200})); + let a = run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap(); + let b = run(&mut app, "shape.rectangle", json!({"x": 200, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap(); + run(&mut app, "select.set", json!({"ids": [a, b]})); + let blend = NodeId(run(&mut app, "object.blend.make", json!({}))["id"].as_u64().unwrap()); + run(&mut app, "select.none", json!({})); + expand(&mut app, &json!({})).unwrap(); + let st = app.session.active().unwrap(); + let rows = list_rows(&st.doc, &st.layers_open, &PanelOptions::default(), "", &Filter::default()); + let kinds: Vec<(u64, bool)> = rows.iter().map(|r| (r.node.id.0, r.spine)).collect(); + assert_eq!(kinds[1..], [(blend.0, false), (b, false), (a, false), (blend.0, true)], "the spine row comes last in the blend"); + let rows = list_rows(&st.doc, &st.layers_open, &PanelOptions::default(), "rect", &Filter::default()); + assert!(!rows.iter().any(|r| r.spine), "no spine row while searching"); + // Rows top down: the layer, the blend, both keys (with target circles), then the spine. + let ctx = egui::Context::default(); + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 4); + let spine_row = egui::pos2(150.0, circles[3].y + (circles[3].y - circles[2].y)); + let selected = |app: &VectorcraftApp| app.session.active().unwrap().selection.objects.to_vec(); + click_with(&mut app, &ctx, spine_row, egui::Modifiers::NONE); + assert_eq!(selected(&app), [blend], "its row selects the blend"); + click_with(&mut app, &ctx, spine_row, egui::Modifiers::SHIFT); + assert!(selected(&app).is_empty(), "Shift-click takes it out again"); + run(&mut app, "layer.setProps", json!({"ids": [blend.0], "locked": true})); + click_with(&mut app, &ctx, spine_row, egui::Modifiers::NONE); + assert!(selected(&app).is_empty(), "a locked blend's spine can't be selected"); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 9c01459894..b1a5070568 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Pen: Cmd/Ctrl drags with the lent selection tool, not hidden box handles, #4980) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Layers panel: a blend's spine row, #4820) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -90,6 +90,7 @@ tools, never checked side by side) isn't captured row by row. | Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | +| Layers panel lists a blend's spine (#4820) | done | an open blend shows a `<Path>` row below its key objects, where Release leaves the spine; a click selects the blend (Shift/Cmd toggles it) so Direct Selection edits the spine; a locked blend's row selects nothing; no row while searching or filtering (`a_blends_spine_is_a_row_below_its_keys_that_selects_the_blend`) | | Blend spine Anchor Point conversion and handle editing (#2544) | implemented | symmetric handles, independent drag/retraction, visible-handle policy and selection/stacking covered by tool and engine regressions; Windows native canvas checks and screenshots reviewed in PR #2643 | | Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one; Shift held at the press on an anchor moves it, handles and all (Shift kept down: at 45° steps) instead of pulling out handles | | Pencil: Fidelity, Keep selected, Alt to Smooth, edit selected paths, close by proximity | done | Fidelity goes down to 0.01 pt in the dialog, the tool and `path.freehand` (the Smooth tool keeps 0.05); its slider runs across the Tool Options row on a logarithmic rail from 0.01 to 20 pt, the field shows hundredths, and the slider's and the field's arrow keys step hundredths up to 0.1 pt, tenths up to 1 pt and whole points above (Shift ×10) (#3328); Alt key toggles to Smooth Tool (#2001); Shift held at the press draws a straight line at 45° steps from the Constrain Angle, and Alt held at the press (with Alt key toggles to Smooth Tool off) a straight line at any angle (#3799), with a straight-line cursor while Shift or Alt is held before the press, and a path-continuation cursor over an end of a selected open path, where the line continues the path; Edit Selected Paths continues a selected path from an end and, from a stroke that starts and ends on a selected path, redraws the section between (the shorter way round a closed path, #2850); with Keep selected (Pencil and Paintbrush, on by default) off, the path a stroke draws or continues is not selected afterwards; a filled Pencil path keeps a stroke of None (#1804, part of #1679); while a freehand stroke is drawn back to within Close Paths When Ends Are Within of its start, the Pencil and the Paintbrush show the closing cursor, and a release there closes the path | @@ -387,6 +388,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Layers panel: an open blend lists its spine as a `<Path>` row below its key objects, and a click selects the blend so Direct Selection edits the spine (#4820); scores and estimates unchanged | | 2026-11-01 | minor | Pen with Cmd/Ctrl held: the lent Selection tool no longer scales the path being drawn by bounding-box handles the canvas hides while its end anchor is selected (a flat path did nothing under a resize pointer); a Cmd drag moves the path instead, and with Direct Selection moves anchors and segments, one undo step each (#4980); scores and estimates unchanged | | 2026-11-01 | minor | Dynamic symbols (#4938): Symbol Options › Symbol Type; per-instance appearance for objects of a dynamic symbol's art; Reset in the Properties panel and the Symbols panel menu; on-canvas Direct Selection of the parts remains | | 2026-11-01 | minor | Export for Screens has Include Artboard Fill beside Include Bleed (on by default, remembered; `includeArtboardFill`): the files draw each artboard's background color behind its art, as exports and print now do, and the Print dialog's preview shows it (#4937); scores and estimates unchanged | From 9f64a13a8ac37f9d641195827195147bcd4a5205 Mon Sep 17 00:00:00 2001 From: RicSchonfelder <ricschonfelder@icloud.com> Date: Sat, 31 Oct 2026 20:12:54 -0300 Subject: [PATCH 207/260] i18n(pt-br): translate the rows the sibling catalogs cover The Brazilian Portuguese catalog was marked complete under the tests, but 174 strings that the German, French, Italian and Spanish catalogs already translate still fell back to English: smart object and smart-filter editors, print presets and Japanese paper names, dimension lines and text, the gutter, workspace names, swatch names and canvas messages. Rows follow the catalog's vocabulary (dimension = cota, swatch = amostra, artboard = Mesa de Trabalho, gutter = medianiz, line weight = espessura da linha) and are appended after the existing entries; placeholders, ellipses and colons are unchanged. The parity doc records the new count (6,126) with the commit it was measured on, following the rule in "How it is measured". --- crates/ui-egui/src/i18n/pt-br.tsv | 175 ++++++++++++++++++++++++++++++ docs/localization-parity.md | 6 +- 2 files changed, 178 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 54d1a792eb..ff88df32f2 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6023,6 +6023,181 @@ breakText Glyphs Glifos @msg no object at path {shown} in the symbol's art nenhum objeto no caminho {shown} na arte do símbolo @msg give fill, stroke, opacity and/or blend informe fill, stroke, opacity e/ou blend @msg pass newName, registration, exportType, nineSlice and/or type informe newName, registration, exportType, nineSlice e/ou type +# Strings the sibling catalogs translate that pt-BR did not yet cover (translated 2026-10-31). + on the canvas to create one na tela para criar um + 1 Layer 1 camada + [1P-High View] [1P-Vista alta] + [1P-Low View] [1P-Vista baixa] + [1P-Normal View] [1P-Vista normal] + [2P-High View] [2P-Vista alta] + [2P-Low View] [2P-Vista baixa] + [2P-Normal View] [2P-Vista normal] + [3P-Low View] [3P-Vista baixa] + [3P-Normal View] [3P-Vista normal] + [High Quality Print] [Impressão de alta qualidade] + [High Resolution] [Alta resolução] + [Low Resolution] [Baixa resolução] + [Medium Resolution] [Resolução média] +swatch [None] [Nenhum] + [PDF/X-1a:2001] [PDF/X-1a:2001] + [PDF/X-3:2002] [PDF/X-3:2002] + [PDF/X-4:2010] [PDF/X-4:2010] + [Press Quality] [Qualidade para gráfica] +swatch [Registration] [Registro] + [Smallest File Size] [Menor tamanho de arquivo] + [VectorCraft Default] [Padrão do VectorCraft] +swatch Amber Âmbar + Angular Angular +swatch Aqua Água + Arrow Scale: Escala da seta: + Arrow Style: Estilo da seta: + Art and Bright Colors Arte e cores vivas + Artboard Options: edit with the Artboard tool Opções de Mesa de Trabalho: editar com a ferramenta Mesa de Trabalho + Automation Automação + Away from the Line Longe da linha +swatch Azure Azul-celeste + Between Line and Object Entre a linha e o objeto +swatch Black Preto +swatch Blue Azul + Blur Mode Modo de desfoque +swatch Bright Blue Azul-vivo +swatch Bright Green Verde-vivo +swatch Bright Red Vermelho-vivo +swatch Bright Violet Violeta-vivo +swatch Bright Yellow Amarelo-vivo +swatch Brights Cores vivas +swatch Brown Marrom + Check for Updates… Verificar atualizações… +swatch Chocolate Marrom-chocolate +swatch Coffee Café + Color Table (4 colors) Tabela de cores (4 cores) +swatch Copper Cobre + Create PDF layers from top-level layers Criar camadas de PDF a partir das camadas de nível superior + Current Colors (0) Cores atuais (0) +swatch Cyan Ciano +swatch Cyan Green Verde-ciano + Differences from [Default]: Diferenças em relação a [Padrão]: + Differences from VectorCraft Default: Diferenças em relação ao padrão do VectorCraft: + Dimension Lines Linhas de cota + Dimension Text Texto da cota + Display Exibição + Dot Gain 15% Ganho de ponto 15% + Drag art, colors and text styles here to reuse them across documents. Libraries are stored on this machine — no account required. Arraste arte, cores e estilos de texto para cá para reutilizá-los em outros documentos. As bibliotecas ficam armazenadas nesta máquina — não é necessária uma conta. + Drag out from a circle or arc for its radius, inwards for its diameter. Arraste para fora de um círculo ou arco para obter o raio, e para dentro para obter o diâmetro. + Drag out from a corner, or click two straight lines, then click to place. Arraste a partir de um canto, ou clique em duas linhas retas e depois clique para posicionar. + Drag out from a segment, or click two points, then click to place. Arraste a partir de um segmento, ou clique em dois pontos e depois clique para posicionar. + Edge Only Somente bordas +swatch Emerald Esmeralda + English Inglês +swatch Espresso Expresso + Essentials Essenciais + Essentials Classic Essenciais clássico + Expand 1 Selected Expandir 1 selecionado + Expand Object Expandir objeto + Extension Lines Linhas de extensão + Extension: Extensão: + Font Size: Tamanho da fonte: + Graphic Styles (4) Estilos gráficos (4) + Gray Gamma 2.2 Gama de cinza 2.2 +swatch Grays Cinzas +swatch Green Verde + Gutter Medianiz + Gutter: Medianiz: + Hide Extension Lines Ocultar linhas de extensão + Hide Units Ocultar unidades + High Quality Print Impressão de alta qualidade +digits Hindi Híndi +@msg image '{key}' has no pixels and was left out a imagem '{key}' não tem pixels e foi deixada de fora +swatch Indigo Índigo + Invalid panel layout; restored the default dock Layout de painéis inválido; o dock padrão foi restaurado +font-script Japanese Japonês + Japanese Double Postcard Cartão-postal japonês duplo + Japanese Envelope #3 Envelope japonês nº 3 + Japanese Envelope #4 Envelope japonês nº 4 + Japanese Postcard Cartão-postal japonês + Kaku #2 Kaku #2 + Kaku #3 Kaku #3 + Layout Layout +swatch Lime Lima + Line Type: Tipo de linha: + Line Weight: Espessura da linha: + Load Variable Library Carregar biblioteca de variáveis +swatch Magenta Magenta +@msg not an RTF file: it doesn't start with {\\rtf não é um arquivo RTF: ele não começa com {\\rtf +swatch Ocean Oceano +shape Open Aberta + OpenType OpenType +swatch Orange Laranja +swatch Orange Red Vermelho-alaranjado + Overlay Edge Sobreposição de bordas + Painting Pintura + Part of ArtCraft. MIT OR Apache-2.0. Fonts: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL). Icons: Lucide (ISC) + VectorCraft. Parte do ArtCraft. MIT OR Apache-2.0. Fontes: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL). Ícones: Lucide (ISC) + VectorCraft. + Path Length Comprimento do caminho + PDF/X-1a:2001 PDF/X-1a:2001 + PDF/X-3:2002 PDF/X-3:2002 + PDF/X-4:2010 PDF/X-4:2010 + Phone 375×812 Celular 375×812 + Photo Low Fidelity Foto com baixa fidelidade +swatch Pink Rosa + Position: Posição: + Preparing the image… Preparando a imagem… + Press Quality Qualidade para gráfica + Print & Proof Impressão e prova + Printing & Proofing Impressão e prova + Printing and Proofing Impressão e prova +swatch Purple Púrpura +swatch Radial White, Black Branco e preto (radial) + RECENT (1) RECENTES (1) +swatch Red Vermelho + Reset Automation Redefinir automação + Reset Essentials Classic Redefinir Essenciais clássico + Reset Layout Redefinir layout + Reset Painting Redefinir pintura + Reset Printing and Proofing Redefinir impressão e prova + Reset Tracing Redefinir vetorização + Reset Typography Redefinir tipografia + Reset Web Redefinir Web + Restricted Colors Cores restritas + Right-click an item to move it into this group. Clique com o botão direito em um item para movê-lo para este grupo. +swatch Rose Rosado +swatch Rust Ferrugem +swatch Sand Areia + Scale X Escala X + Scale X: Escala X: + Scale Y Escala Y + Scale Y: Escala Y: + Selected Styles Only (0) Somente estilos selecionados (0) + Selected Swatches Only (0) Somente amostras selecionadas (0) + Simplified Chinese Chinês simplificado + Smallest File Size Menor tamanho de arquivo + Spot Colors (0) Cores Spot (0) +swatch Sunset Pôr do sol + Tablet 1024×768 Tablet 1024×768 +swatch Tan Castanho-claro +swatch Teal Verde-azulado +@msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), which can't be opened yet: save it as PDF, PDF-compatible .ai or SVG este é um arquivo PostScript (um .ai salvo em formato antigo ou sem compatibilidade com PDF, ou um arquivo EPS), que ainda não pode ser aberto: salve-o como PDF, .ai compatível com PDF ou SVG +@msg this kind of brush has no options dialog yet este tipo de pincel ainda não tem caixa de diálogo de opções + Touch Toque + Tracing Vetorização + Tracing the colors… Vetorizando as cores… + Typography Tipografia + Units & Scale Unidades e escala +@msg Unknown dimension style Estilo de cota desconhecido +@msg Unknown unit Unidade desconhecida + VectorCraft VectorCraft + VectorCraft Updates Atualizações do VectorCraft + Video 1920×1080 Vídeo 1920×1080 + Video 3840×2160 Vídeo 3840×2160 +swatch Violet Violeta +swatch Walnut Nogueira + Web Web + Web 1280×720 Web 1280×720 +swatch White Branco +swatch White, Black Branco e preto +swatch Yellow Amarelo +swatch Yellow Green Verde-amarelado + Yonroku-ban Yonroku-ban + ▾ Default Actions ▾ Ações padrão Text Flow Fluxo do texto By Rows Por linhas By Columns Por colunas diff --git a/docs/localization-parity.md b/docs/localization-parity.md index d7ab314f5d..c0bce9c0d2 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,13 +1,13 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (Bosnian (`bs`): complete catalog; previously minor: Vietnamese text: stacked diacritics tested and attach in every form, #4491; previously: Catalan (`ca`) catalog added, complete under the tests) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Brazilian Portuguese: 174 rows for the strings the sibling catalogs translate — smart-filter and print presets, dimension lines, workspace names, swatches, canvas messages; previously minor: Bosnian (`bs`): complete catalog; previously minor: Vietnamese text: stacked diacritics tested and attach in every form, #4491; previously: Catalan (`ca`) catalog added, complete under the tests) Per-language status of VectorCraft's interface. How the catalogs work and how to add a language: [`development.md` › Localisation](development.md#localisation). Part of [target-app-parity.md](target-app-parity.md). **How it is measured:** rows with a translation in each `crates/ui-egui/src/i18n/<code>.tsv`, counted on -origin/main `01e165af`, except the rows that give a count date, which were counted on `main` at `cb0a7d9` (2026-10-21). +origin/main `01e165af`, except the rows that give a count date: those were counted on the `main` commit named in the row (the other dated rows on `main` at `cb0a7d9`, 2026-10-21; the Portuguese row on `main` at `d26dd933a`, 2026-10-31). The reference is the French catalog, which was complete when counted: 3,416 interface strings (menus, command labels, `tl!` literals: panels, dialogs, tooltips, Preferences) plus 604 `@msg` status and error messages, 4,020 in all. A language's % is its rows over 4,020 (capped at 100% per part). A missing @@ -32,7 +32,7 @@ Chinese by `imachus`). Only Georgian is recorded as reviewed by a native speaker | Hindi | `hi` | 0 | none | Devanagari: the document's text shapes (HarfRust), with tests of conjuncts, reph, pre-base matras, nukta forms and caret stops that run when an OpenType Devanagari font is installed, but the egui interface does no complex shaping | no | none | 20–30 | | Arabic | `ar` | 0 | none | document text: bidi layout and Paragraph Direction; interface: no right-to-left layout, no Arabic shaping in egui | no | none | 25–40 | | French | `fr` | 4,020 / 4,020 (100%) | all | Latin | no | full | — (review) | -| Portuguese | `pt-br` | 5,194 catalog entries (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | +| Portuguese | `pt-br` | 6,126 catalog entries (counted 2026-10-31 on `main` at `d26dd933a`): menus, `tl!` literals and messages complete when counted; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | | Indonesian | `id` | 5,279 rows, 750 of them `@msg` (counted 2026-10-21): menus and `tl!` literals complete when counted; its messages are partial; one plural form | dialogs and tooltips all; 750 message rows (French has 796) | Latin | no | full | — (review) | | Japanese | `ja` | 4,004 / 4,020 (99.6%) | all | CJK UI font as above; Japanese IME; vertical type partial; Japanese crop marks and composition settings | no | full | — (review) | | German | `de` | 3,952 / 4,020 (98%; menus, literals and messages complete when counted) | all (602 of 604 message rows; landed 2026-10-10) | Latin | contributor-written, not reviewed | full | — (review) | From dac4dc15ad42002a82a322de12af0814aa67898a Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 06:14:11 +0700 Subject: [PATCH 208/260] i18n(pt-br): leave the product, workspace and perspective preset names in English, as the menu-complete catalogs do --- crates/ui-egui/src/i18n/pt-br.tsv | 20 -------------------- docs/localization-parity.md | 4 ++-- 2 files changed, 2 insertions(+), 22 deletions(-) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index ff88df32f2..1d650bfbab 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6026,14 +6026,6 @@ breakText Glyphs Glifos # Strings the sibling catalogs translate that pt-BR did not yet cover (translated 2026-10-31). on the canvas to create one na tela para criar um 1 Layer 1 camada - [1P-High View] [1P-Vista alta] - [1P-Low View] [1P-Vista baixa] - [1P-Normal View] [1P-Vista normal] - [2P-High View] [2P-Vista alta] - [2P-Low View] [2P-Vista baixa] - [2P-Normal View] [2P-Vista normal] - [3P-Low View] [3P-Vista baixa] - [3P-Normal View] [3P-Vista normal] [High Quality Print] [Impressão de alta qualidade] [High Resolution] [Alta resolução] [Low Resolution] [Baixa resolução] @@ -6053,7 +6045,6 @@ swatch Aqua Água Arrow Style: Estilo da seta: Art and Bright Colors Arte e cores vivas Artboard Options: edit with the Artboard tool Opções de Mesa de Trabalho: editar com a ferramenta Mesa de Trabalho - Automation Automação Away from the Line Longe da linha swatch Azure Azul-celeste Between Line and Object Entre a linha e o objeto @@ -6090,8 +6081,6 @@ swatch Cyan Green Verde-ciano swatch Emerald Esmeralda English Inglês swatch Espresso Expresso - Essentials Essenciais - Essentials Classic Essenciais clássico Expand 1 Selected Expandir 1 selecionado Expand Object Expandir objeto Extension Lines Linhas de extensão @@ -6117,7 +6106,6 @@ font-script Japanese Japonês Japanese Postcard Cartão-postal japonês Kaku #2 Kaku #2 Kaku #3 Kaku #3 - Layout Layout swatch Lime Lima Line Type: Tipo de linha: Line Weight: Espessura da linha: @@ -6126,11 +6114,9 @@ swatch Magenta Magenta @msg not an RTF file: it doesn't start with {\\rtf não é um arquivo RTF: ele não começa com {\\rtf swatch Ocean Oceano shape Open Aberta - OpenType OpenType swatch Orange Laranja swatch Orange Red Vermelho-alaranjado Overlay Edge Sobreposição de bordas - Painting Pintura Part of ArtCraft. MIT OR Apache-2.0. Fonts: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL). Icons: Lucide (ISC) + VectorCraft. Parte do ArtCraft. MIT OR Apache-2.0. Fontes: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL). Ícones: Lucide (ISC) + VectorCraft. Path Length Comprimento do caminho PDF/X-1a:2001 PDF/X-1a:2001 @@ -6144,7 +6130,6 @@ swatch Pink Rosa Press Quality Qualidade para gráfica Print & Proof Impressão e prova Printing & Proofing Impressão e prova - Printing and Proofing Impressão e prova swatch Purple Púrpura swatch Radial White, Black Branco e preto (radial) RECENT (1) RECENTES (1) @@ -6177,20 +6162,15 @@ swatch Tan Castanho-claro swatch Teal Verde-azulado @msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), which can't be opened yet: save it as PDF, PDF-compatible .ai or SVG este é um arquivo PostScript (um .ai salvo em formato antigo ou sem compatibilidade com PDF, ou um arquivo EPS), que ainda não pode ser aberto: salve-o como PDF, .ai compatível com PDF ou SVG @msg this kind of brush has no options dialog yet este tipo de pincel ainda não tem caixa de diálogo de opções - Touch Toque - Tracing Vetorização Tracing the colors… Vetorizando as cores… - Typography Tipografia Units & Scale Unidades e escala @msg Unknown dimension style Estilo de cota desconhecido @msg Unknown unit Unidade desconhecida - VectorCraft VectorCraft VectorCraft Updates Atualizações do VectorCraft Video 1920×1080 Vídeo 1920×1080 Video 3840×2160 Vídeo 3840×2160 swatch Violet Violeta swatch Walnut Nogueira - Web Web Web 1280×720 Web 1280×720 swatch White Branco swatch White, Black Branco e preto diff --git a/docs/localization-parity.md b/docs/localization-parity.md index c0bce9c0d2..f90715f5b8 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Brazilian Portuguese: 174 rows for the strings the sibling catalogs translate — smart-filter and print presets, dimension lines, workspace names, swatches, canvas messages; previously minor: Bosnian (`bs`): complete catalog; previously minor: Vietnamese text: stacked diacritics tested and attach in every form, #4491; previously: Catalan (`ca`) catalog added, complete under the tests) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Brazilian Portuguese: 154 rows for the strings the sibling catalogs translate — smart-filter and print presets, dimension lines, swatches, canvas messages; previously minor: Bosnian (`bs`): complete catalog; previously minor: Vietnamese text: stacked diacritics tested and attach in every form, #4491; previously: Catalan (`ca`) catalog added, complete under the tests) Per-language status of VectorCraft's interface. How the catalogs work and how to add a language: [`development.md` › Localisation](development.md#localisation). Part of @@ -32,7 +32,7 @@ Chinese by `imachus`). Only Georgian is recorded as reviewed by a native speaker | Hindi | `hi` | 0 | none | Devanagari: the document's text shapes (HarfRust), with tests of conjuncts, reph, pre-base matras, nukta forms and caret stops that run when an OpenType Devanagari font is installed, but the egui interface does no complex shaping | no | none | 20–30 | | Arabic | `ar` | 0 | none | document text: bidi layout and Paragraph Direction; interface: no right-to-left layout, no Arabic shaping in egui | no | none | 25–40 | | French | `fr` | 4,020 / 4,020 (100%) | all | Latin | no | full | — (review) | -| Portuguese | `pt-br` | 6,126 catalog entries (counted 2026-10-31 on `main` at `d26dd933a`): menus, `tl!` literals and messages complete when counted; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | +| Portuguese | `pt-br` | 6,106 catalog entries (counted 2026-10-31 on `main` at `d26dd933a`): menus, `tl!` literals and messages complete when counted; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | | Indonesian | `id` | 5,279 rows, 750 of them `@msg` (counted 2026-10-21): menus and `tl!` literals complete when counted; its messages are partial; one plural form | dialogs and tooltips all; 750 message rows (French has 796) | Latin | no | full | — (review) | | Japanese | `ja` | 4,004 / 4,020 (99.6%) | all | CJK UI font as above; Japanese IME; vertical type partial; Japanese crop marks and composition settings | no | full | — (review) | | German | `de` | 3,952 / 4,020 (98%; menus, literals and messages complete when counted) | all (602 of 604 message rows; landed 2026-10-10) | Latin | contributor-written, not reviewed | full | — (review) | From 4211424855e3454aac6bd2c13f73ef5e9d94ca99 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 06:33:48 +0700 Subject: [PATCH 209/260] i18n(pt-br): the Language menu shows English in its own name --- crates/ui-egui/src/i18n/pt-br.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 1d650bfbab..53bee8c061 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6079,7 +6079,7 @@ swatch Cyan Green Verde-ciano Drag out from a segment, or click two points, then click to place. Arraste a partir de um segmento, ou clique em dois pontos e depois clique para posicionar. Edge Only Somente bordas swatch Emerald Esmeralda - English Inglês + English English swatch Espresso Expresso Expand 1 Selected Expandir 1 selecionado Expand Object Expandir objeto From 2f8ff1a224728b8003beeb03b6b0a0a87ef47ff9 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 14:47:29 -0700 Subject: [PATCH 210/260] Tabs: Ctrl-dragging a tab stop moves all the stops together In the Tabs panel, a stop dragged on the ruler with Ctrl held (Command on macOS) moves every stop by the same distance, set in one text.tabs.set and one undo step. The stops keep their order, alignment, leaders and Align On, and the ruler draws them at their new positions during the drag. Ctrl is read when the drag starts, as the Left Indent marker reads it. A drag that would take the leftmost stop below 0 leaves it at 0, and one that would take the rightmost past 100,000 pt leaves it at 100,000 pt, keeping the spacing of the others. A Ctrl-drag released off the ruler deletes only the dragged stop, as a plain drag does. A plain drag still moves one stop. --- crates/ui-egui/src/panels/tabs.rs | 44 +++++++++++-- crates/ui-egui/src/panels/tabs/tests.rs | 84 +++++++++++++++++++++++++ docs/target-app-parity.md | 1 + docs/type-parity.md | 2 +- 4 files changed, 126 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rs index 040ff676cc..81abe5c68f 100644 --- a/crates/ui-egui/src/panels/tabs.rs +++ b/crates/ui-egui/src/panels/tabs.rs @@ -1,7 +1,8 @@ //! Tabs panel: tab-stop alignment, X position (Y in vertical type), leader and "align on", and a //! ruler numbered in the General unit on which a click adds a stop, dragging moves one and dragging -//! it off the ruler deletes it. A stop placed or dragged on the ruler lands on the nearest whole -//! point. With Snap to Unit on, or Shift held, it lands on the ruler's nearest tick. +//! it off the ruler deletes it. Ctrl-dragging a stop (Command on macOS) moves all the stops by the +//! same distance. A stop placed or dragged on the ruler lands on the nearest whole point. With Snap +//! to Unit on, or Shift held, it lands on the ruler's nearest tick. use egui::{Sense, Stroke, Ui, vec2}; use serde_json::{Value, json}; @@ -40,6 +41,9 @@ fn align_id(a: TabAlign) -> &'static str { /// The panel body's margin and the ruler's own inset: the ruler's 0 is this far right of the panel. const RULER_LEFT: f32 = 10.0 + 4.0; +/// The largest stop position `text.tabs.set` takes, in points. +const MAX_STOP: f64 = 100_000.0; + #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum IndentMarker { Upper, @@ -302,6 +306,29 @@ fn apply_moved(app: &mut VectorcraftApp, ctx: &egui::Context, stops: &mut Vec<Ta }) } +/// `stops` with every stop moved by the distance that takes stop `i` to `position`, or by less +/// when that would put a stop below 0 or past [`MAX_STOP`], so the leftmost stop ends at 0 or the +/// rightmost at [`MAX_STOP`] and the stops keep their spacing. The stops keep their order, +/// alignment, leader and "align on". `None` when there is no stop `i`. +fn moved_all(stops: &[TabStop], i: usize, position: f64) -> Option<Vec<TabStop>> { + let from = stops.get(i)?.position; + let lowest = stops.iter().map(|s| s.position).fold(f64::INFINITY, f64::min); + let highest = stops.iter().map(|s| s.position).fold(f64::NEG_INFINITY, f64::max); + let offset = (position - from).min(MAX_STOP - highest).max(-lowest); + Some(stops.iter().map(|s| TabStop { position: s.position + offset, ..s.clone() }).collect()) +} + +/// Move every stop as [`moved_all`] does, in one `text.tabs.set`, and select stop `i`. Returns its +/// index, or `None` when the stops are not set and `stops` and the selection stay as they were. +fn apply_moved_all(app: &mut VectorcraftApp, ctx: &egui::Context, stops: &mut Vec<TabStop>, i: usize, position: f64) -> Option<usize> { + let moved = moved_all(stops, i, position)?; + apply(app, &moved).then(|| { + *stops = moved; + set_pstate(ctx, "tabs-sel", i); + i + }) +} + pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let Some((node, para, span)) = current_para(app) else { @@ -429,7 +456,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { Some((marker, value, both)) }); paint_markers(ui, &p, &t, MarkerPaint { rect, span, para: ¶, mixed_left, selected: selected_marker, drag: marker_drag, preview }, to_x); - for (i, s) in stops.iter().enumerate() { + let drag: Option<usize> = pstate(ui.ctx(), "tabs-drag"); + let drag_all = drag.is_some() && pstate::<bool>(ui.ctx(), "tabs-drag-all"); + // While a Ctrl-drag (Command on macOS) is on the ruler, the stops are drawn where the drop puts them. + let all_preview = drag.filter(|_| drag_all).and_then(|i| { + let pointer = ui.input(|input| input.pointer.any_down().then(|| input.pointer.interact_pos()).flatten())?; + (pointer.y <= rect.bottom() + 20.0).then(|| moved_all(&stops, i, place(pointer.x))).flatten() + }); + for (i, s) in all_preview.as_deref().unwrap_or(&stops).iter().enumerate() { let x = to_x(s.position); let c = if i == sel && selected_marker.is_none() { t.accent } else { t.text }; let y = rect.bottom() - 2.0; @@ -445,7 +479,6 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { p.circle_filled(egui::pos2(x + 3.0, y - 6.0), 1.5, c); } } - let drag: Option<usize> = pstate(ui.ctx(), "tabs-drag"); // The stop within 5 px of `x`. let hit_at = |x: f32| stops.iter().position(|s| (to_x(s.position) - x).abs() <= 5.0); let cancel_drag = ui.input(|i| i.key_pressed(egui::Key::Escape)); @@ -466,6 +499,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } else { let hit = hit_at(pos.x); set_pstate(ui.ctx(), "tabs-drag", hit); + set_pstate(ui.ctx(), "tabs-drag-all", hit.is_some() && ui.input(|i| i.modifiers.command)); if let Some(i) = hit { set_pstate::<Option<IndentMarker>>(ui.ctx(), "tabs-marker-sel", None); set_pstate(ui.ctx(), "tabs-sel", i); @@ -489,6 +523,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Dragged off the ruler: delete. stops.remove(i); apply(app, &stops); + } else if drag_all { + apply_moved_all(app, ui.ctx(), &mut stops, i, place(pos.x)); } else { apply_moved(app, ui.ctx(), &mut stops, i, place(pos.x)); } diff --git a/crates/ui-egui/src/panels/tabs/tests.rs b/crates/ui-egui/src/panels/tabs/tests.rs index ad8f86a52d..b38a64c044 100644 --- a/crates/ui-egui/src/panels/tabs/tests.rs +++ b/crates/ui-egui/src/panels/tabs/tests.rs @@ -619,6 +619,90 @@ fn a_stop_dragged_past_another_stays_selected() { assert!(texts.iter().any(|(t, _)| *t == shown), "{shown} in {texts:?}"); } +/// Press on the stop at `from` (points), move to `to` and release there with Ctrl (Command on +/// macOS) held → the stems' x positions painted in the frame before the release. +fn command_drag_on_ruler(ctx: &egui::Context, app: &mut VectorcraftApp, from: f64, to: f64) -> Vec<f32> { + let labels = ruler_frame(ctx, app, vec![], false); + let [(zero, a), (next, b), ..] = &labels[..] else { panic!("ruler labels {labels:?}") }; + assert_eq!(zero, "0"); + let per = next.parse::<f64>().unwrap() * app.session.general_unit().points(); + let x = |pt: f64| a.x - 2.0 + (pt / per) as f32 * (b.x - a.x); + let y = a.y + 15.0; + let command = egui::Event::ModifiersChanged(egui::Modifiers::COMMAND); + let button = + |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::COMMAND }; + let (press, end) = (egui::pos2(x(from), y), egui::pos2(x(to), y)); + ruler_frame(ctx, app, vec![command.clone(), egui::Event::PointerMoved(press), button(press, true)], false); + for f in [0.25, 0.5] { + ruler_frame(ctx, app, vec![command.clone(), egui::Event::PointerMoved(press.lerp(end, f))], false); + } + let stems = stems_frame(ctx, app, vec![command.clone(), egui::Event::PointerMoved(end)]); + ruler_frame(ctx, app, vec![command, button(end, false)], false); + ruler_frame(ctx, app, vec![], false); + stems.into_iter().map(|(x, _)| x).collect() +} + +/// Ctrl-dragging a stop (Command on macOS) moves every stop by the same distance in one +/// `text.tabs.set`, one undo step, keeping each stop's alignment and leader, and the ruler shows +/// them moving during the drag. A plain drag still moves one stop. +#[test] +fn command_drag_moves_all_the_stops_together() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b c", "area": {"width": 300, "height": 100}})).unwrap(); + app.session + .execute( + "text.tabs.set", + &json!({"stops": [{"position": 30, "leader": "."}, {"position": 50, "align": "right"}, {"position": 80, "align": "decimal", "alignOn": ","}]}), + ) + .unwrap(); + let ctx = egui::Context::default(); + let positions = |app: &VectorcraftApp| current(app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>(); + let before = app.session.active().unwrap().history.undo.len(); + let during = command_drag_on_ruler(&ctx, &mut app, 50.0, 70.0); + assert_eq!(positions(&app), [50.0, 70.0, 100.0]); + let stops = current(&app).unwrap().1; + assert_eq!(stops.iter().map(|s| s.align).collect::<Vec<_>>(), [TabAlign::Left, TabAlign::Right, TabAlign::Decimal]); + assert_eq!((stops[0].leader.as_str(), stops[2].align_on), (".", ',')); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); + assert_eq!(pstate::<usize>(&ctx, "tabs-sel"), 1); + let after: Vec<f32> = stems_frame(&ctx, &mut app, vec![]).into_iter().map(|(x, _)| x).collect(); + assert_eq!(during.len(), 3, "{during:?}"); + assert!(during.iter().zip(&after).all(|(d, a)| (d - a).abs() < 0.5), "during the drag {during:?}, after it {after:?}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(positions(&app), [30.0, 50.0, 80.0]); + drag_on_ruler(&ctx, &mut app, 50.0, 70.0, false); + assert_eq!(positions(&app), [30.0, 70.0, 80.0]); +} + +/// A Ctrl-drag (Command on macOS) that would put a stop below 0 stops when the leftmost stop +/// reaches 0, so the stops keep their spacing. +#[test] +fn command_drag_stops_at_zero_and_keeps_the_spacing() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap(); + app.session.execute("text.tabs.set", &json!({"stops": [{"position": 30}, {"position": 50}]})).unwrap(); + let ctx = egui::Context::default(); + command_drag_on_ruler(&ctx, &mut app, 50.0, 5.0); + assert_eq!(current(&app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>(), [0.0, 20.0]); + assert_eq!(moved_all(¤t(&app).unwrap().1, 1, 0.0).unwrap().iter().map(|s| s.position).collect::<Vec<_>>(), [0.0, 20.0]); + assert!(moved_all(&[], 0, 10.0).is_none()); +} + +/// A Ctrl-drag (Command on macOS) that would put a stop past 100,000 pt stops when the rightmost +/// stop reaches 100,000 pt, so the stops move and keep their spacing. +#[test] +fn command_drag_stops_at_the_largest_position_and_keeps_the_spacing() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap(); + app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50}, {"position": 99_990}]})).unwrap(); + let ctx = egui::Context::default(); + command_drag_on_ruler(&ctx, &mut app, 50.0, 70.0); + assert_eq!(current(&app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>(), [60.0, 100_000.0]); +} + /// A stop placed by a click on the ruler or dragged on it lands on the nearest whole point, and /// the moved stop stays selected. A position typed in the X field keeps its hundredths of a point. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f6ac63f8e3..27ebc9383b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -507,6 +507,7 @@ since 2026-10-01. - **The text style panel menus' Duplicate and Delete:** in the Character Styles and Paragraph Styles panel menus, Duplicate highlights the copy, as Create New Style highlights the new style, and Delete leaves no style highlighted, as the Delete button does, so Duplicate, Clear Overrides, Redefine and Style Options are disabled until another style is clicked. A highlighted style that is renamed in Style Options or deleted by a command is no longer highlighted either. The tests `panels::text_styles::tests::panel_menu_duplicate_and_delete_update_the_highlighted_style` and `a_highlighted_style_that_is_no_longer_listed_is_not_highlighted` cover this. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Names of new styles and symbols:** `charStyle.new` and `paraStyle.new` trim the white space around the name they are given, as `charStyle.rename` and `paraStyle.rename` do, and refuse a name that is then empty; Duplicate names its copy from the trimmed name. `symbol.new` and `symbol.duplicate` trim the name as Symbol Options does, and `library.use` adds a library's text style under its trimmed name. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Naming a new text style first:** Alt-click on New in the Character Styles or Paragraph Styles panel opens New Character Style or New Paragraph Style (`ui.newCharStyle`, `ui.newParaStyle`) with the name a plain click's style gets; OK makes the style from the text selected when the dialog opened, and Cancel adds none. Tests `panels::text_styles::tests::alt_clicking_new_character_style_asks_for_its_name` and `alt_clicking_new_paragraph_style_asks_for_its_name`. Public reference: [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Set options (except for Actions, Brushes, Swatches, and Symbols panels)". +- **Moving all tab stops:** in the Tabs panel, a stop dragged on the ruler with Ctrl held (Command on macOS) moves every stop by the same distance, in one `text.tabs.set` and one undo step; the stops keep their order, alignment and leaders, the ruler shows them moving during the drag, and a drag that would take the leftmost stop below 0 leaves it at 0, or the rightmost past 100,000 pt leaves it at 100,000 pt, with the other stops at their spacing from it. Ctrl must be held when the drag starts. Tests `panels::tabs::tests::command_drag_moves_all_the_stops_together`, `command_drag_stops_at_zero_and_keeps_the_spacing` and `command_drag_stops_at_the_largest_position_and_keeps_the_spacing`. Public reference: [Manage tab stops](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/manage-tab-stops.html), which says that a Ctrl-drag (Windows) or Command-drag (macOS) of a tab moves all the tab stops at the same time. - **Width Point Edit:** Shift-double-click enables Adjust Adjoining Width Points; plain double-click and direct opening retain the default. Tool dispatch and headless dialog tests cover neighboring widths, Undo/Redo and Cancel. Public reference: [Variable-width strokes](https://helpx.adobe.com/illustrator/using/stroke-object.html). Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a feature lands. diff --git a/docs/type-parity.md b/docs/type-parity.md index 521d216855..6346c1b864 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -43,7 +43,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Hyphenation… and Justification… options | done | Hyphenation… (`ui.hyphenation`, `text.setFormat`) sets each paragraph's Words Longer Than, After First, Before Last, Hyphen Limit, Hyphenation Zone (Single-line Composer only) and Hyphenate Capitalized Words, and paragraph styles carry them (#2310). Justification… (`ui.justification`, `text.setFormat`, #2755) sets Word Spacing, Letter Spacing and Glyph Scaling (Minimum, Desired, Maximum), Auto Leading and Single Word Justification; Desired applies to every line, justified lines and the Every-line Composer use the ranges. Vertical type isn't glyph scaled; type on a path doesn't use them. Evidence: `crates/text/src/tests/justify.rs`, `dialogs::justification::tests` | | Roman Hanging Punctuation | done | Paragraph panel menu › Roman Hanging Punctuation, `text.setFormat {romanHangingPunctuation}` (#2756): per paragraph, Optical Margin Alignment's punctuation and amounts without the letters; paragraph styles carry it. Evidence: `tests::roman_hanging_punctuation_hangs_punctuation_but_not_letters`, `typecmd::area_tests::roman_hanging_punctuation_is_set_per_paragraph_and_saved_only_when_on` | | Hyphenation… and Justification… options | done | Hyphenation… (`ui.hyphenation`, `text.setFormat`) sets each paragraph's Words Longer Than, After First, Before Last, Hyphen Limit, Hyphenation Zone (Single-line Composer only) and Hyphenate Capitalized Words, and paragraph styles carry them (#2310). Justification… (`ui.justification`, `text.setFormat`, #2755) sets Word Spacing, Letter Spacing and Glyph Scaling (Minimum, Desired, Maximum), Auto Leading and Single Word Justification; Desired applies to every line, justified lines and the Every-line Composer use the ranges. Vertical type isn't glyph scaled; type on a path doesn't use them. Auto Leading also sets the Leading the Character panel shows for Auto type, the leading Alt+↑/↓ (`type.step`) steps from, per paragraph, and the lines Fill with Placeholder Text counts. Evidence: `crates/text/src/tests/justify.rs`, `dialogs::justification::tests`, `tests_prefs::auto_leading_steps_and_fills_from_the_paragraph_auto_leading`, `panels::character` test `leading_field_shows_the_paragraph_auto_leading` | -| Tab stops and leaders; Tabs panel | partial | Tabs panel and stops with leaders in the model (`text.tabs.set`); a stop drags from where the press landed (#1458); leaders fill the tab's gap, repeated on a grid so they line up from line to line (#1877) | +| Tab stops and leaders; Tabs panel | partial | Tabs panel and stops with leaders in the model (`text.tabs.set`); a stop drags from where the press landed (#1458); leaders fill the tab's gap, repeated on a grid so they line up from line to line (#1877); Ctrl-dragging a stop (Command on macOS) moves all the stops together | | Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters` | | Spell check (Check Spelling, Auto Spell Check, custom dictionary) | missing | menu stubs; needs an openly licensed dictionary | | Smart Punctuation, Change Case, Find & Replace | done | | From 4a804b96bdd5fd54304f0830da919efaafffbf1b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 15:45:27 -0700 Subject: [PATCH 211/260] Tabs: Escape pressed as a stop is released cancels the drag The stop drop now checks Escape the way the indent-marker drop does, so Escape in the release frame leaves the stops as they were after a plain drag, a Ctrl-drag (Command on macOS) of all the stops, or a drag off the ruler. --- crates/ui-egui/src/panels/tabs.rs | 1 + crates/ui-egui/src/panels/tabs/tests.rs | 43 +++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rs index 81abe5c68f..1e0818454f 100644 --- a/crates/ui-egui/src/panels/tabs.rs +++ b/crates/ui-egui/src/panels/tabs.rs @@ -515,6 +515,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { set_marker(app, marker, place(pos.x), ¶, span, &targets, both); } } else if resp.drag_stopped() + && !cancel_drag && let (Some(i), Some(pos)) = (drag, resp.interact_pointer_pos()) { set_pstate::<Option<usize>>(ui.ctx(), "tabs-drag", None); diff --git a/crates/ui-egui/src/panels/tabs/tests.rs b/crates/ui-egui/src/panels/tabs/tests.rs index b38a64c044..b598d0c2a3 100644 --- a/crates/ui-egui/src/panels/tabs/tests.rs +++ b/crates/ui-egui/src/panels/tabs/tests.rs @@ -703,6 +703,49 @@ fn command_drag_stops_at_the_largest_position_and_keeps_the_spacing() { assert_eq!(current(&app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>(), [60.0, 100_000.0]); } +/// Press on the stop at `from` (points), move to `to` and `below` px under the ruler, and release +/// there in the same frame as Escape, Ctrl (Command on macOS) held when `command`. +fn escaped_drag_on_ruler(ctx: &egui::Context, app: &mut VectorcraftApp, from: f64, to: f64, below: f32, command: bool) { + let labels = ruler_frame(ctx, app, vec![], false); + let [(zero, a), (next, b), ..] = &labels[..] else { panic!("ruler labels {labels:?}") }; + assert_eq!(zero, "0"); + let per = next.parse::<f64>().unwrap() * app.session.general_unit().points(); + let x = |pt: f64| a.x - 2.0 + (pt / per) as f32 * (b.x - a.x); + let y = a.y + 15.0; + let modifiers = if command { egui::Modifiers::COMMAND } else { egui::Modifiers::NONE }; + let held = egui::Event::ModifiersChanged(modifiers); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers }; + let (press, end) = (egui::pos2(x(from), y), egui::pos2(x(to), y + below)); + ruler_frame(ctx, app, vec![held.clone(), egui::Event::PointerMoved(press), button(press, true)], false); + for f in [0.25, 0.5, 1.0] { + ruler_frame(ctx, app, vec![held.clone(), egui::Event::PointerMoved(press.lerp(end, f))], false); + } + ruler_frame(ctx, app, vec![held, escape, button(end, false)], false); + ruler_frame(ctx, app, vec![], false); +} + +/// Escape pressed in the frame a stop is released cancels the drag: a plain drag, a Ctrl-drag +/// (Command on macOS) and a drag off the ruler all leave the stops where they were. +#[test] +fn escape_in_the_release_frame_cancels_a_stop_drag() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap(); + app.session.execute("text.tabs.set", &json!({"stops": [{"position": 30}, {"position": 50}]})).unwrap(); + let ctx = egui::Context::default(); + let positions = |app: &VectorcraftApp| current(app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>(); + let before = app.session.active().unwrap().history.undo.len(); + for (below, command) in [(0.0, false), (0.0, true), (60.0, false), (60.0, true)] { + escaped_drag_on_ruler(&ctx, &mut app, 50.0, 70.0, below, command); + assert_eq!(positions(&app), [30.0, 50.0], "{below} px below, command {command}"); + } + assert_eq!(app.session.active().unwrap().history.undo.len(), before); + // The next drag without Escape still moves the stop. + drag_on_ruler(&ctx, &mut app, 50.0, 70.0, false); + assert_eq!(positions(&app), [30.0, 70.0]); +} + /// A stop placed by a click on the ruler or dragged on it lands on the nearest whole point, and /// the moved stop stays selected. A position typed in the X field keeps its hundredths of a point. #[test] From 5fdccdf60255f761ceea3e2716eadb42fad90878 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 14:57:13 -0700 Subject: [PATCH 212/260] Place: Word 97-2003 .doc files place as area type with their formatting File > Place reads a Word 97-2003 document (a compound file named .doc, or one that holds a WordDocument stream) and sets its main text as area type, as it does for .rtf and .docx files. The text comes from the piece table, in 16-bit Unicode or compressed 8-bit pieces. Formatting is resolved from the style sheet's default font, the paragraph style, the character style and the direct character and paragraph properties, and keeps the same properties the .docx reader maps. Table cells are separated by tabs and each row is a paragraph, and a field places as its result. Hidden and deleted text, pictures, headers, footers, notes, comments and text boxes are left out, and the reply's warnings name each kind of content left out or changed once. Word 6.0 and Word 95 documents, encrypted documents and documents last saved with fast save are refused, and so are structures that lie outside their streams. The compound file is read with the cfb crate (MIT), which adds one package to Cargo.lock. --- Cargo.lock | 12 + crates/engine/Cargo.toml | 2 + crates/engine/src/cmd/fileio.rs | 5 +- crates/engine/src/cmd/fileio/formats.rs | 15 +- crates/engine/src/cmd/place.rs | 12 + crates/engine/src/cmd/place/doc.rs | 1161 +++++++++++++++++++++++ crates/engine/src/tests/textimport.rs | 363 ++++++- crates/engine/tests/text_import_fuzz.rs | 162 +++- docs/file-format-parity.md | 4 +- docs/mcp.md | 12 + docs/target-app-parity.md | 1 + 11 files changed, 1734 insertions(+), 15 deletions(-) create mode 100644 crates/engine/src/cmd/place/doc.rs diff --git a/Cargo.lock b/Cargo.lock index 934be1b120..248679aaca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -705,6 +705,17 @@ dependencies = [ "shlex", ] +[[package]] +name = "cfb" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f13298d9178622b7916ec5d01d470425c04273c8ed07e87b1c38b34c4f4612b" +dependencies = [ + "fnv", + "uuid", + "web-time", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -6205,6 +6216,7 @@ dependencies = [ name = "vectorcraft-engine" version = "0.19.0" dependencies = [ + "cfb", "craft-docpath", "crc32fast", "flate2", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 7b1199277b..9d4ad73995 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -40,6 +40,8 @@ hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["st flate2 = { workspace = true } # The XML parts of Word documents placed as type (place/docx.rs). roxmltree = "0.21" +# The compound file that holds a Word 97-2003 document placed as type (place/doc.rs). +cfb = "0.15" kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index b873f36387..4079b42301 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -124,8 +124,9 @@ pub(crate) use export_names::{default_name, merge, unique_file_names, with_black use export_names::{distinct_names, write_encoded}; use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, writable}; pub use formats::{ - DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, export_extensions, extension, file_stem, - format, format_for_name, has_own_title, library_open_filters, open_filters, place_filters, plugin_formats, titled_for_export, writable_format, + DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, export_extensions, extension, + file_stem, format, format_for_name, has_own_title, library_open_filters, open_filters, place_filters, plugin_formats, titled_for_export, + writable_format, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index a1687e214f..8df1788459 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -566,8 +566,14 @@ pub const RTF_EXTS: &[&str] = &["rtf"]; /// Word documents: File → Place sets them as area type with their formatting. pub const DOCX_EXTS: &[&str] = &["docx"]; -/// Every extension File → Place reads: [`OPEN_EXTS`], [`TEXT_EXTS`], [`RTF_EXTS`] and -/// [`DOCX_EXTS`]. +/// Word 97-2003 documents: File → Place sets them as area type with their formatting. +pub const DOC_EXTS: &[&str] = &["doc"]; + +/// The Place dialog's Word filter: Word documents and Word 97-2003 documents. +const WORD_EXTS: &[&str] = &["docx", "doc"]; + +/// Every extension File → Place reads: [`OPEN_EXTS`], [`TEXT_EXTS`], [`RTF_EXTS`], +/// [`DOCX_EXTS`] and [`DOC_EXTS`]. pub const PLACE_EXTS: &[&str] = &[ "vectorcraft", "drawcraft", @@ -610,6 +616,7 @@ pub const PLACE_EXTS: &[&str] = &[ "txt", "rtf", "docx", + "doc", ]; /// One dialog filter per readable format. @@ -645,13 +652,13 @@ pub fn library_open_filters( } /// File → Place dialog filters: "All placeable files", then one per placeable format, then text, -/// RTF and Word. +/// RTF and Word (`.docx` and `.doc`). pub fn place_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> { std::iter::once(("All placeable files", PLACE_EXTS)) .chain(format_filters().filter(|(_, exts)| exts.iter().all(|ext| PLACE_EXTS.contains(ext)))) .chain(std::iter::once(("Text", TEXT_EXTS))) .chain(std::iter::once(("RTF", RTF_EXTS))) - .chain(std::iter::once(("Word", DOCX_EXTS))) + .chain(std::iter::once(("Word", WORD_EXTS))) } /// A format by id or extension (any case, leading dot allowed; `jpeg` finds `jpg`): a built-in diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 2ab05f69e8..d76de1adb7 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -20,6 +20,8 @@ //! - An RTF file becomes area type with its character and paragraph formatting ([`rtf`]). //! - A Word document (`.docx`) becomes area type with the character and paragraph formatting its //! styles and direct formatting give ([`docx`]). +//! - A Word 97-2003 document (`.doc`) becomes area type the same way, its main text read from its +//! compound file, with a warning for each kind of content left out ([`doc`]). //! - A VectorCraft document placed from a file with Link (the default) becomes a placed document: //! one locked object showing the artboard `page`, linked to the file and read again when it //! changes ([`document`]); without Link, an editable copy of its art. @@ -30,6 +32,7 @@ //! `place` tool) with several files, which emits one `file.place` per click or drag. pub(crate) mod adopt; +mod doc; pub(crate) mod document; pub(crate) mod docx; mod rtf; @@ -169,6 +172,15 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa } return Ok(Loaded { name, format: &docx::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings: vec![], link: None, board: None }); } + // A Word 97-2003 document is recognized by its name or by its compound file's WordDocument + // stream. + if doc::is_doc(src.name, &src.bytes) { + let (story, warnings) = doc::import(&src.bytes, cmd)?; + if story.plain_text().trim().is_empty() { + return Err(bad(cmd, format!("`{name}` has no text to place"))); + } + return Ok(Loaded { name, format: &doc::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings, link: None, board: None }); + } let format = fileio::detect(src.name, &src.bytes) .ok_or_else(|| bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)")))?; let page = match p.get("page") { diff --git a/crates/engine/src/cmd/place/doc.rs b/crates/engine/src/cmd/place/doc.rs new file mode 100644 index 0000000000..3ae2410bae --- /dev/null +++ b/crates/engine/src/cmd/place/doc.rs @@ -0,0 +1,1161 @@ +//! Placing a Word 97-2003 document (`.doc`): its main text set as area type with the character and +//! paragraph formatting VectorCraft has, read as \[MS-DOC\] describes the Word Binary File Format +//! (<https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-doc/262caa01-60a5-479e-b710-1e966936a524>) +//! from the compound file \[MS-CFB\] describes +//! (<https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-cfb/53989ce4-7b05-4f8d-829b-d08d6148375b>). +//! +//! - The `WordDocument` stream starts with the file information block (FIB, §2.5.1), which locates +//! the structures read from the `0Table` or `1Table` stream (`fWhichTblStm`). Documents saved by +//! Word 97 and later (`nFib` 0x00C1 and above) are read; older ones, encrypted or obfuscated ones +//! and ones last saved with fast save (`fComplex`) are refused. +//! - Text: the main document's `ccpText` characters, from the pieces the Clx's PlcPcd lists +//! (§2.9.38, §2.8.35) in their order, each in 16-bit Unicode or in compressed 8-bit text with the +//! mapping §2.9.73 gives. A paragraph mark (U+000D) ends a paragraph, and so does a page or +//! section break (U+000C) at the end of a paragraph's properties (PapxFkp); a line break +//! (U+000B) starts a new paragraph in the same formatting. A table's cells (cell marks, U+0007) +//! are separated by tabs and each row (a table terminating mark) is a paragraph. Tabs are tabs, +//! and U+001E and U+001F are the nonbreaking and optional hyphens. Of a field (U+0013, U+0014 and +//! U+0015), its result is read. +//! - Character formatting: the font (`sprmCRgFtc0`, named by the font table SttbfFfn), the size, +//! bold, italic, underline (every style but none), strikethrough and double strikethrough, all +//! caps, small caps, superscript and subscript, raised and lowered text (`sprmCHpsPos`) and the +//! color (`sprmCIco`, `sprmCCv`). +//! - Paragraph formatting: alignment (`sprmPJc80`, then `sprmPJc`: start and end follow the +//! direction, and the kashida alignments are justified with Short, Medium or Long kashidas), the +//! left and right indents (the physical ones Word 97 writes, unless the logical ones later +//! versions write are given), first-line indent, space before and after, and direction +//! (`sprmPFBiDi`). +//! - Formatting is resolved as "Determining Formatting Properties" describes: the style sheet's +//! default font and 10 pt, then the paragraph style (STSH, §2.9.271) and the styles it is based +//! on, then the run's character style (`sprmCIstd`) and the styles it is based on, then the +//! direct formatting of the run (Chpx) and of the paragraph (Papx). A toggle operand of 0x80 or +//! 0x81 takes or reverses the value the styles give. +//! +//! Hidden text, deleted revisions, field instructions, pictures and embedded objects, note and +//! comment references and the other stories (footnotes, endnotes, headers, footers, comments and +//! text boxes) are left out. The reply's warnings name each kind of content that was left out or +//! changed, once: pictures and objects, fields, the other stories, tracked changes and tables. A +//! stream larger than [`MAX_STREAM`] bytes, a main text longer than [`text::MAX_TEXT`] characters, +//! more than [`MAX_PIECES`] pieces or [`MAX_PAGES`] property pages, and placed type of more than +//! [`MAX_PARAGRAPHS`] paragraphs or [`MAX_RUNS`] runs are refused, and so is a structure that lies +//! outside its stream. + +use std::io::{Cursor, Read}; + +use vectorcraft_doc::text::Kashida; +use vectorcraft_doc::{CharPosition, CharStyle, Justify, ParaDirection, ParaStyle, ScriptMetrics, TextRun}; + +use super::text::{self, Story}; +use super::{EngineError, Paint, Result, bad, fileio}; + +/// Word 97-2003 documents as `file.place` reports them (not a format `document.open` reads). +pub(super) const FORMAT: fileio::Format = fileio::Format { + id: "doc", + label: "Word 97-2003", + extensions: fileio::DOC_EXTS, + mime: "application/msword", + read: true, + write: false, + raster: false, + options: &[], +}; + +/// The first bytes of a compound file (\[MS-CFB\] §2.2). +const SIGNATURE: [u8; 8] = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]; +/// The most bytes a stream read from the compound file may hold. +const MAX_STREAM: u64 = 64 << 20; +/// The most pieces the main text may be made of. +const MAX_PIECES: usize = 100_000; +/// The most 512-byte pages of character or of paragraph properties read. +const MAX_PAGES: usize = 16_384; +/// The most styles read from the style sheet (`Stshif.cstd` is below 0x0FFE). +const MAX_STYLES: usize = 0x0FFE; +/// The most styles one style's chain of `istdBase` takes in. +const MAX_BASED_ON: usize = 32; +/// The most fonts read from the font table (SttbfFfn's `cData` is at most 0x7FF0). +const MAX_FONTS: usize = 0x7FF0; +/// The most bytes of a font name kept. +const MAX_NAME: usize = 256; +/// The most paragraphs placed type takes from one Word document. +const MAX_PARAGRAPHS: usize = 100_000; +/// The most runs of one character formatting placed type takes from one Word document. +const MAX_RUNS: usize = 100_000; +/// The deepest nesting of fields read; deeper ones are left out with their results. +const MAX_FIELDS: usize = 64; +/// `istdBase` of a style that is based on none. +const NO_STYLE: u16 = 0x0FFF; + +/// The FibRgFcLcb97 pairs read (§2.5.6), by their index. +const STSHF: usize = 1; +const PLCF_BTE_CHPX: usize = 12; +const PLCF_BTE_PAPX: usize = 13; +const STTBF_FFN: usize = 15; +const CLX: usize = 33; +/// The number of pairs FibRgFcLcb97 holds. +const FC_LCB_97: u16 = 0x005D; + +/// Is the file `name` with `bytes` a Word 97-2003 document: a compound file named `.doc`, or one +/// that holds a `WordDocument` stream? +pub(super) fn is_doc(name: &str, bytes: &[u8]) -> bool { + bytes.starts_with(&SIGNATURE) + && (fileio::DOC_EXTS.contains(&fileio::extension(name).as_str()) + || cfb::CompoundFile::open(Cursor::new(bytes)).is_ok_and(|f| f.is_stream("/WordDocument"))) +} + +/// The main text of a Word 97-2003 document's `bytes` (a compound file) with its character and +/// paragraph formatting, and a warning for each kind of content left out or changed. +pub(super) fn import(bytes: &[u8], cmd: &str) -> Result<(Story, Vec<String>)> { + let mut file = cfb::CompoundFile::open(Cursor::new(bytes)).map_err(|_| damaged(cmd, "its compound file structure is damaged"))?; + let wd = stream(&mut file, "WordDocument", cmd)?.ok_or_else(|| bad(cmd, "not a Word document: its compound file has no WordDocument stream"))?; + let fib = Fib::read(&wd, cmd)?; + let table_name = if fib.table_one { "1Table" } else { "0Table" }; + let table = stream(&mut file, table_name, cmd)?.ok_or_else(|| damaged(cmd, format!("it has no {table_name} stream")))?; + let clx = fib.part(&table, CLX, cmd)?.ok_or_else(|| damaged(cmd, "it has no piece table"))?; + let text = main_text(&wd, &pieces(clx, cmd)?, fib.ccp_text, cmd)?; + let chpx = match fib.part(&table, PLCF_BTE_CHPX, cmd)? { + Some(plc) => runs(&wd, plc, Fkp::Chpx, cmd)?, + None => vec![], + }; + let papx = match fib.part(&table, PLCF_BTE_PAPX, cmd)? { + Some(plc) => runs(&wd, plc, Fkp::Papx, cmd)?, + None => vec![], + }; + let sheet = match fib.part(&table, STSHF, cmd)? { + Some(stsh) => Sheet::read(stsh, cmd)?, + None => Sheet::default(), + }; + let fonts = match fib.part(&table, STTBF_FFN, cmd)? { + Some(sttb) => fonts(sttb, cmd)?, + None => vec![], + }; + let mut r = Reader::new(&sheet, &fonts); + r.read(&text, &chpx, &papx); + let warnings = r.warnings(&fib); + Ok((r.finish(cmd)?, warnings)) +} + +/// The error for a Word document whose structures can't be read. +fn damaged(cmd: &str, why: impl std::fmt::Display) -> EngineError { + bad(cmd, format!("can't read this Word document: {why}")) +} + +/// The stream `name` of the compound file; None when it has no such stream. +fn stream(file: &mut cfb::CompoundFile<Cursor<&[u8]>>, name: &str, cmd: &str) -> Result<Option<Vec<u8>>> { + if !file.is_stream(name) { + return Ok(None); + } + let s = file.open_stream(name).map_err(|_| damaged(cmd, format!("its {name} stream is damaged")))?; + if s.len() > MAX_STREAM { + return Err(bad(cmd, format!("the Word document is too large to place (its {name} stream holds more than {} MB)", MAX_STREAM >> 20))); + } + let mut out = vec![]; + s.take(MAX_STREAM).read_to_end(&mut out).map_err(|_| damaged(cmd, format!("its {name} stream is damaged")))?; + Ok(Some(out)) +} + +/// The little-endian 16-bit integer at `at`. +fn u16_at(b: &[u8], at: usize) -> Option<u16> { + b.get(at..at.checked_add(2)?).and_then(|s| s.try_into().ok()).map(u16::from_le_bytes) +} + +/// The little-endian 32-bit integer at `at`. +fn u32_at(b: &[u8], at: usize) -> Option<u32> { + b.get(at..at.checked_add(4)?).and_then(|s| s.try_into().ok()).map(u32::from_le_bytes) +} + +/// `len` bytes of `b` from `at`. +fn bytes_at(b: &[u8], at: usize, len: usize) -> Option<&[u8]> { + b.get(at..at.checked_add(len)?) +} + +/// What the reader takes from the file information block. +struct Fib { + /// The table stream is `1Table` (else `0Table`). + table_one: bool, + /// The main document's length in characters. + ccp_text: u32, + /// The lengths of the footnotes, headers and footers, comments, endnotes, text boxes and + /// header text boxes (`ccpFtn`, `ccpHdd`, `ccpAtn`, `ccpEdn`, `ccpTxbx`, `ccpHdrTxbx`). + stories: [u32; 6], + /// FibRgFcLcb's offset and size pairs. + fc_lcb: Vec<(u32, u32)>, +} + +impl Fib { + /// The FIB at the start of the WordDocument stream `wd` (§2.5.1). + fn read(wd: &[u8], cmd: &str) -> Result<Self> { + if u16_at(wd, 0) != Some(0xA5EC) { + return Err(bad(cmd, "not a Word document: its WordDocument stream doesn't start with a file information block")); + } + let field = |at: usize| u16_at(wd, at).ok_or_else(|| damaged(cmd, "its file information block is cut short")); + if field(2)? < 0x00C1 { + return Err(bad( + cmd, + "the Word document was saved by Word 6.0 or Word 95, which VectorCraft doesn't read; save it as a Word 97-2003 document", + )); + } + let flags = field(10)?; + // fEncrypted (fObfuscated only says how). + if flags & 0x0100 != 0 { + return Err(bad(cmd, "the Word document is encrypted or protected with a password; save it without one to place it")); + } + // fComplex: the last save was an incremental (fast) save. + if flags & 0x0004 != 0 { + return Err(bad( + cmd, + "the Word document was last saved with fast save, which VectorCraft doesn't read; save it again with fast save turned off", + )); + } + // csw (14 16-bit values) and cslw (22 32-bit values) are fixed. + if field(32)? != 0x000E || field(62)? != 0x0016 { + return Err(damaged(cmd, "its file information block is damaged")); + } + let count = field(152)?; + if count < FC_LCB_97 { + return Err(damaged(cmd, "its file information block is damaged")); + } + let pair = |i: usize| Some((u32_at(wd, 154 + 8 * i)?, u32_at(wd, 158 + 8 * i)?)); + let fc_lcb = + (0..usize::from(count)).map(pair).collect::<Option<Vec<_>>>().ok_or_else(|| damaged(cmd, "its file information block is cut short"))?; + // FibRgLw97 starts at 64: ccpText is its fourth value. + let lw = |i: usize| u32_at(wd, 64 + 4 * i).unwrap_or_default(); + Ok(Self { table_one: flags & 0x0200 != 0, ccp_text: lw(3), stories: [lw(4), lw(5), lw(7), lw(8), lw(9), lw(10)], fc_lcb }) + } + + /// The structure FibRgFcLcb's pair `index` locates in the table stream `table`; None when it + /// is empty. + fn part<'a>(&self, table: &'a [u8], index: usize, cmd: &str) -> Result<Option<&'a [u8]>> { + let Some(&(fc, lcb)) = self.fc_lcb.get(index).filter(|(_, lcb)| *lcb > 0) else { return Ok(None) }; + bytes_at(table, fc as usize, lcb as usize).map(Some).ok_or_else(|| damaged(cmd, "a table it lists lies outside its table stream")) + } +} + +/// A piece of the text (Pcd): characters `cp..end`, stored from file position `fc`. +struct Piece { + cp: u32, + end: u32, + fc: u32, + /// Compressed 8-bit text (else 16-bit Unicode). + compressed: bool, +} + +/// The pieces the Clx `clx` lists (§2.9.38), in character order. +fn pieces(clx: &[u8], cmd: &str) -> Result<Vec<Piece>> { + let broken = || damaged(cmd, "its piece table is damaged"); + let mut at = 0usize; + // Prc records (property modifiers for pieces) come first. + while clx.get(at) == Some(&0x01) { + let size = u16_at(clx, at + 1).map(|v| v as i16).filter(|v| *v >= 0).ok_or_else(broken)?; + at += 3 + size as usize; + } + if clx.get(at) != Some(&0x02) { + return Err(broken()); + } + let lcb = u32_at(clx, at + 1).ok_or_else(broken)? as usize; + let plc = bytes_at(clx, at + 5, lcb).ok_or_else(broken)?; + if lcb < 4 || !(lcb - 4).is_multiple_of(12) { + return Err(broken()); + } + let n = (lcb - 4) / 12; + if n > MAX_PIECES { + return Err(bad(cmd, format!("the Word document's text is made of more than {MAX_PIECES} pieces, too many to place"))); + } + let mut out = Vec::with_capacity(n); + for i in 0..n { + let (cp, end) = (u32_at(plc, 4 * i).ok_or_else(broken)?, u32_at(plc, 4 * i + 4).ok_or_else(broken)?); + // A Pcd: 2 bytes of flags, then FcCompressed (fc in bits 0 to 29, fCompressed in bit 30). + let raw = u32_at(plc, 4 * (n + 1) + 8 * i + 2).ok_or_else(broken)?; + if end <= cp || out.last().is_some_and(|p: &Piece| p.end != cp) || (i == 0 && cp != 0) { + return Err(broken()); + } + let compressed = raw & 0x4000_0000 != 0; + let fc = raw & 0x3FFF_FFFF; + out.push(Piece { cp, end, fc: if compressed { fc / 2 } else { fc }, compressed }); + } + Ok(out) +} + +/// A character of the main text: the character, the file position of its bytes, and their number. +type Char = (char, u32, u8); + +/// The first `ccp` characters of the pieces, read from the WordDocument stream `wd`. +fn main_text(wd: &[u8], pieces: &[Piece], ccp: u32, cmd: &str) -> Result<Vec<Char>> { + if ccp as usize > text::MAX_TEXT { + return Err(bad(cmd, format!("the Word document has too much text to place as type (at most {} MB)", text::MAX_TEXT >> 20))); + } + if pieces.last().is_none_or(|p| p.end < ccp) { + return Err(damaged(cmd, "its piece table doesn't cover its text")); + } + let outside = || damaged(cmd, "a piece of its text lies outside its WordDocument stream"); + let mut out = Vec::with_capacity(ccp as usize); + for p in pieces.iter().take_while(|p| p.cp < ccp) { + let n = (p.end.min(ccp) - p.cp) as usize; + if p.compressed { + let b = bytes_at(wd, p.fc as usize, n).ok_or_else(outside)?; + out.extend(b.iter().zip(p.fc..).map(|(&c, fc)| (compressed(c), fc, 1))); + continue; + } + let b = bytes_at(wd, p.fc as usize, n.checked_mul(2).ok_or_else(outside)?).ok_or_else(outside)?; + let units: Vec<(u16, u32)> = b.as_chunks::<2>().0.iter().zip((p.fc..).step_by(2)).map(|(&u, fc)| (u16::from_le_bytes(u), fc)).collect(); + let mut i = 0; + while let Some(&(u, fc)) = units.get(i) { + let pair = units.get(i + 1).map(|&(low, _)| low).filter(|low| (0xD800..0xDC00).contains(&u) && (0xDC00..0xE000).contains(low)); + let c = match pair { + Some(low) => char::decode_utf16([u, low]).next().and_then(|c| c.ok()), + None => char::from_u32(u32::from(u)), + }; + let width = if pair.is_some() { 4 } else { 2 }; + out.push((c.unwrap_or(char::REPLACEMENT_CHARACTER), fc, width)); + i += usize::from(width / 2); + } + } + Ok(out) +} + +/// Byte `b` of compressed text (§2.9.73): the byte as a Unicode character, except the ones that +/// stand for these. +fn compressed(b: u8) -> char { + const MAPPED: [(u8, char); 24] = [ + (0x82, '\u{201A}'), + (0x83, '\u{0192}'), + (0x84, '\u{201E}'), + (0x85, '\u{2026}'), + (0x86, '\u{2020}'), + (0x87, '\u{2021}'), + (0x88, '\u{02C6}'), + (0x89, '\u{2030}'), + (0x8A, '\u{0160}'), + (0x8B, '\u{2039}'), + (0x8C, '\u{0152}'), + (0x91, '\u{2018}'), + (0x92, '\u{2019}'), + (0x93, '\u{201C}'), + (0x94, '\u{201D}'), + (0x95, '\u{2022}'), + (0x96, '\u{2013}'), + (0x97, '\u{2014}'), + (0x98, '\u{02DC}'), + (0x99, '\u{2122}'), + (0x9A, '\u{0161}'), + (0x9B, '\u{203A}'), + (0x9C, '\u{0153}'), + (0x9F, '\u{0178}'), + ]; + MAPPED.iter().find(|(k, _)| *k == b).map_or(char::from(b), |(_, c)| *c) +} + +/// Which property pages a bin table points to. +#[derive(Clone, Copy, PartialEq)] +enum Fkp { + /// ChpxFkp (§2.9.33): character properties. + Chpx, + /// PapxFkp (§2.9.174): paragraph properties. + Papx, +} + +/// The file positions `start..end` and the properties a property page gives them. +struct Run { + start: u32, + end: u32, + /// The paragraph style (Papx only). + istd: u16, + grpprl: Vec<u8>, +} + +/// The runs of the property pages the bin table `plc` (PlcBteChpx or PlcBtePapx) points to, in +/// the WordDocument stream `wd`, ordered by file position. +fn runs(wd: &[u8], plc: &[u8], kind: Fkp, cmd: &str) -> Result<Vec<Run>> { + let broken = || damaged(cmd, "its character or paragraph properties are damaged"); + if plc.len() < 4 || !(plc.len() - 4).is_multiple_of(8) { + return Err(broken()); + } + let n = (plc.len() - 4) / 8; + if n > MAX_PAGES { + return Err(bad(cmd, format!("the Word document has more than {MAX_PAGES} pages of properties, too many to place"))); + } + let mut out = vec![]; + for i in 0..n { + // PnFkpChpx and PnFkpPapx: the page number in bits 0 to 21. + let pn = u32_at(plc, 4 * (n + 1) + 4 * i).ok_or_else(broken)? & 0x003F_FFFF; + let page = bytes_at(wd, pn as usize * 512, 512).ok_or_else(broken)?; + page_runs(page, kind, &mut out).ok_or_else(broken)?; + } + out.sort_by_key(|r| r.start); + Ok(out) +} + +/// The runs of one 512-byte property page; None when it is damaged. +fn page_runs(page: &[u8], kind: Fkp, out: &mut Vec<Run>) -> Option<()> { + let count = usize::from(*page.get(511)?); + let most = if kind == Fkp::Chpx { 0x65 } else { 0x1D }; + if count == 0 || count > most { + return None; + } + for i in 0..count { + let (start, end) = (u32_at(page, 4 * i)?, u32_at(page, 4 * i + 4)?); + // ChpxFkp's rgb: one byte each; PapxFkp's rgbx: 13-byte BxPap, its first byte the offset. + let entry = 4 * (count + 1) + if kind == Fkp::Chpx { i } else { 13 * i }; + let offset = usize::from(*page.get(entry)?) * 2; + let (istd, grpprl) = match (offset, kind) { + (0, _) => (0, vec![]), + (_, Fkp::Chpx) => { + let cb = usize::from(*page.get(offset)?); + (0, bytes_at(page, offset + 1, cb).filter(|_| offset + 1 + cb <= 511)?.to_vec()) + } + (_, Fkp::Papx) => { + // PapxInFkp: 2 × cb − 1 bytes, or (cb = 0) 2 × cb′ bytes after cb′. + let (at, len) = match usize::from(*page.get(offset)?) { + 0 => (offset + 2, usize::from(*page.get(offset + 1)?) * 2), + cb => (offset + 1, 2 * cb - 1), + }; + let grp = bytes_at(page, at, len).filter(|_| at + len <= 511 && len >= 2)?; + (u16_at(grp, 0)?, grp.get(2..)?.to_vec()) + } + }; + if end <= start { + return None; + } + out.push(Run { start, end, istd, grpprl }); + } + Some(()) +} + +/// The run of `runs` (ordered by file position) that holds file position `fc`. +fn run_at(runs: &[Run], fc: u32) -> Option<usize> { + let i = runs.partition_point(|r| r.start <= fc).checked_sub(1)?; + runs.get(i).filter(|r| fc < r.end).map(|_| i) +} + +/// The size of the operand of `sprm` (§2.2.5.1) whose bytes start `rest`. +fn operand_len(sprm: u16, rest: &[u8]) -> Option<usize> { + Some(match sprm >> 13 { + 0 | 1 => 1, + 2 | 4 | 5 => 2, + 3 => 4, + 7 => 3, + // sprmTDefTable: a 2-byte size of the rest, plus 1. + _ if sprm == 0xD608 => usize::from(u16_at(rest, 0)?) + 1, + // sprmPChgTabs with cb 255: the deleted tabs with their close tolerances, then the added + // tabs with their descriptors. + _ if sprm == 0xC615 && rest.first() == Some(&255) => { + let deleted = usize::from(*rest.get(1)?); + let added = usize::from(*rest.get(2 + 4 * deleted)?); + 3 + 4 * deleted + 3 * added + } + _ => usize::from(*rest.first()?) + 1, + }) +} + +/// Calls `f` with each Prl of `grpprl`: its sprm and its operand. +fn each_prl(grpprl: &[u8], mut f: impl FnMut(u16, &[u8])) { + let mut at = 0; + while let Some(sprm) = u16_at(grpprl, at) { + let rest = grpprl.get(at + 2..).unwrap_or_default(); + let Some((n, op)) = operand_len(sprm, rest).and_then(|n| Some((n, rest.get(..n)?))) else { return }; + // A variable operand's bytes follow its size. + let op = if sprm >> 13 == 6 && !matches!(sprm, 0xD608 | 0xC615) { op.get(1..).unwrap_or_default() } else { op }; + f(sprm, op); + at += 2 + n; + } +} + +/// A style of the style sheet. +struct Style { + /// 1: paragraph style, 2: character style. + stk: u8, + base: u16, + papx: Vec<u8>, + chpx: Vec<u8>, +} + +/// The style sheet: its styles by istd and its default font. +#[derive(Default)] +struct Sheet { + styles: Vec<Option<Style>>, + /// `Stshif.ftcAsci`. + font: Option<u16>, +} + +impl Sheet { + /// The style sheet STSH (§2.9.271). + fn read(stsh: &[u8], cmd: &str) -> Result<Self> { + let broken = || damaged(cmd, "its style sheet is damaged"); + let size = usize::from(u16_at(stsh, 0).ok_or_else(broken)?); + let stshi = bytes_at(stsh, 2, size).ok_or_else(broken)?; + let count = usize::from(u16_at(stshi, 0).ok_or_else(broken)?).min(MAX_STYLES); + // cbSTDBaseInFile: StdfBase, and StdfPost2000 when it is 18. + let base_size = usize::from(u16_at(stshi, 2).ok_or_else(broken)?).max(10); + let font = u16_at(stshi, 12); + let mut at = 2 + size; + let mut styles = Vec::with_capacity(count); + for _ in 0..count { + let Some(len) = u16_at(stsh, at) else { break }; + let std = bytes_at(stsh, at + 2, usize::from(len)).ok_or_else(broken)?; + styles.push(if std.is_empty() { None } else { Some(style(std, base_size).ok_or_else(broken)?) }); + // LPStd records start on even offsets. + at += 2 + usize::from(len) + usize::from(len) % 2; + } + Ok(Self { styles, font }) + } + + /// Style `istd` of kind `stk` and the styles it is based on, the first of the chain first. + fn chain(&self, istd: u16, stk: u8) -> Vec<&Style> { + let mut seen: Vec<u16> = vec![]; + let mut chain = vec![]; + let mut next = istd; + while next != NO_STYLE && !seen.contains(&next) && seen.len() < MAX_BASED_ON { + let Some(s) = self.styles.get(usize::from(next)).and_then(Option::as_ref).filter(|s| s.stk == stk) else { break }; + seen.push(next); + chain.push(s); + next = s.base; + } + chain.reverse(); + chain + } +} + +/// A style definition (STD, §2.9.258) whose Stdf takes `base_size` bytes; None when it is damaged. +fn style(std: &[u8], base_size: usize) -> Option<Style> { + let kind = u16_at(std, 2)?; + let (stk, base) = ((kind & 0x000F) as u8, kind >> 4); + let cupx = usize::from(u16_at(std, 4)? & 0x000F); + // xstzName: a length, the characters and a terminating zero. + let name = usize::from(u16_at(std, base_size)?); + let mut at = base_size + 2 + 2 * name + 2; + let mut upx = vec![]; + for _ in 0..cupx { + let len = usize::from(u16_at(std, at)?); + upx.push(bytes_at(std, at + 2, len)?); + // Each LPUpx is padded to an even length. + at += 2 + len + len % 2; + } + let (papx, chpx) = match (stk, upx.as_slice()) { + // UpxPapx: the istd, then the paragraph properties; then UpxChpx. + (1, [p, c, ..]) => (p.get(2..)?.to_vec(), c.to_vec()), + (2, [c, ..]) => (vec![], c.to_vec()), + _ => (vec![], vec![]), + }; + Some(Style { stk, base, papx, chpx }) +} + +/// The font names of the font table SttbfFfn (§2.9.286). +fn fonts(sttb: &[u8], cmd: &str) -> Result<Vec<String>> { + let broken = || damaged(cmd, "its font table is damaged"); + let count = usize::from(u16_at(sttb, 0).ok_or_else(broken)?).min(MAX_FONTS); + let mut at = 4; + let mut out = Vec::with_capacity(count); + for _ in 0..count { + let len = usize::from(*sttb.get(at).ok_or_else(broken)?); + let ffn = bytes_at(sttb, at + 1, len).ok_or_else(broken)?; + // FFN: 39 bytes of family, weight, character set, PANOSE and signature, then the name. + let units = ffn.get(39..).unwrap_or_default().as_chunks::<2>().0.iter().map(|&u| u16::from_le_bytes(u)).take_while(|&u| u != 0); + let name: String = char::decode_utf16(units).map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER)).collect(); + out.push(font_name(&name)); + at += 1 + len; + } + Ok(out) +} + +/// Font name `name` trimmed, and cut at the last character that ends within [`MAX_NAME`] bytes. +fn font_name(name: &str) -> String { + let name = name.trim(); + let end = (0..=MAX_NAME.min(name.len())).rev().find(|&i| name.is_char_boundary(i)).unwrap_or_default(); + name.get(..end).unwrap_or_default().to_string() +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Script { + #[default] + Normal, + Super, + Sub, +} + +/// Character formatting. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Chars { + /// The font's number in the font table. + font: Option<u16>, + half_points: u16, + bold: bool, + italic: bool, + caps: bool, + small_caps: bool, + strike: bool, + dstrike: bool, + hidden: bool, + underline: bool, + script: Script, + /// Raised (positive) or lowered text in half points. + shift: i16, + color: Option<[u8; 3]>, + /// Deleted and inserted revisions. + deleted: bool, + inserted: bool, + /// A special character (sprmCFSpec): a picture, a note reference or a symbol. + special: bool, +} + +impl Default for Chars { + fn default() -> Self { + Self { + font: None, + // The default size: 20 half points. + half_points: 20, + bold: false, + italic: false, + caps: false, + small_caps: false, + strike: false, + dstrike: false, + hidden: false, + underline: false, + script: Script::Normal, + shift: 0, + color: None, + deleted: false, + inserted: false, + special: false, + } + } +} + +/// The colors of `sprmCIco` (Ico, §2.9.119), 1 to 16; 0 is automatic. +const ICO: [[u8; 3]; 16] = [ + [0, 0, 0], + [0, 0, 0xFF], + [0, 0xFF, 0xFF], + [0, 0xFF, 0], + [0xFF, 0, 0xFF], + [0xFF, 0, 0], + [0xFF, 0xFF, 0], + [0xFF, 0xFF, 0xFF], + [0, 0, 0x80], + [0, 0x80, 0x80], + [0, 0x80, 0], + [0x80, 0, 0x80], + [0x80, 0, 0], + [0x80, 0x80, 0], + [0x80, 0x80, 0x80], + [0xC0, 0xC0, 0xC0], +]; + +impl Chars { + /// The character properties of `grpprl` applied over this formatting; a toggle operand of + /// 0x80 or 0x81 takes or reverses the value of `style`, the formatting its styles give. + fn apply(&mut self, grpprl: &[u8], style: &Chars) { + each_prl(grpprl, |sprm, op| { + let byte = op.first().copied(); + let word = u16_at(op, 0); + let toggle = |state: &mut bool, of_style: bool| match byte { + Some(0) => *state = false, + Some(1) => *state = true, + Some(0x80) => *state = of_style, + Some(0x81) => *state = !of_style, + _ => {} + }; + match sprm { + 0x0800 => toggle(&mut self.deleted, style.deleted), + 0x0801 => toggle(&mut self.inserted, style.inserted), + 0x0835 => toggle(&mut self.bold, style.bold), + 0x0836 => toggle(&mut self.italic, style.italic), + 0x0837 => toggle(&mut self.strike, style.strike), + 0x083A => toggle(&mut self.small_caps, style.small_caps), + 0x083B => toggle(&mut self.caps, style.caps), + 0x083C => toggle(&mut self.hidden, style.hidden), + 0x0855 => toggle(&mut self.special, style.special), + 0x2A53 => toggle(&mut self.dstrike, style.dstrike), + 0x2A3E => self.underline = byte.is_some_and(|k| k != 0), + 0x2A42 => self.color = byte.and_then(|i| usize::from(i).checked_sub(1)).and_then(|i| ICO.get(i)).copied(), + 0x4A43 => self.half_points = word.filter(|v| (2..=3276).contains(v)).unwrap_or(self.half_points), + 0x4845 => self.shift = word.map_or(self.shift, |v| v as i16), + 0x2A48 => { + self.script = match byte { + Some(1) => Script::Super, + Some(2) => Script::Sub, + _ => Script::Normal, + } + } + 0x4A4F => self.font = word.or(self.font), + // COLORREF: red, green, blue, then 0xFF for the automatic color. + 0x6870 => { + if let [r, g, b, auto] = *op { + self.color = (auto != 0xFF).then_some([r, g, b]); + } + } + _ => {} + } + }); + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Align { + #[default] + Left, + Center, + Right, + /// Justified, the last line at the start, with the kashida length of the kashida alignments. + Both(Kashida), + /// Justified, the last line too. + Distribute, + Start, + End, +} + +/// Paragraph formatting; lengths in twips. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Para { + align: Align, + /// The physical left and right indents (`sprmPDxaLeft80`, `sprmPDxaRight80`). + left: Option<i16>, + right: Option<i16>, + /// The logical start and end indents (`sprmPDxaLeft`, `sprmPDxaRight`). + start: Option<i16>, + end: Option<i16>, + first: i16, + before: u16, + after: u16, + rtl: Option<bool>, + /// The paragraph's mark ends a table row (`sprmPFTtp`, or `sprmPFInnerTtp` in a nested table). + row_end: bool, + /// The paragraph's mark ends a cell of a nested table (`sprmPFInnerTableCell`). + cell_end: bool, +} + +impl Para { + /// The paragraph properties of `grpprl` applied over this formatting. + fn apply(&mut self, grpprl: &[u8]) { + each_prl(grpprl, |sprm, op| { + let byte = op.first().copied(); + let word = u16_at(op, 0); + match sprm { + 0x2403 => { + self.align = match byte { + Some(1) => Align::Center, + Some(2) => Align::Right, + Some(3..=5) => Align::Both(Kashida::None), + Some(_) => Align::Left, + None => self.align, + } + } + 0x2461 => { + self.align = match byte { + Some(0) => Align::Start, + Some(1) => Align::Center, + Some(2) => Align::End, + Some(3) => Align::Both(Kashida::None), + Some(5) => Align::Both(Kashida::Medium), + Some(7) => Align::Both(Kashida::Long), + Some(8) => Align::Both(Kashida::Short), + Some(4 | 9) => Align::Distribute, + _ => self.align, + } + } + 0x840F => self.left = word.map(|v| v as i16), + 0x840E => self.right = word.map(|v| v as i16), + 0x845E => self.start = word.map(|v| v as i16), + 0x845D => self.end = word.map(|v| v as i16), + 0x8411 | 0x8460 => self.first = word.map_or(self.first, |v| v as i16), + 0xA413 => self.before = word.unwrap_or(self.before), + 0xA414 => self.after = word.unwrap_or(self.after), + 0x2441 => self.rtl = byte.map(|v| v != 0), + 0x2417 | 0x244C => self.row_end = byte.is_some_and(|v| v != 0), + 0x244B => self.cell_end = byte.is_some_and(|v| v != 0), + _ => {} + } + }); + } + + /// The paragraph attributes of this formatting. + fn style(&self) -> ParaStyle { + let rtl = self.rtl == Some(true); + let (physical_start, physical_end) = if rtl { (self.right, self.left) } else { (self.left, self.right) }; + let (start, end) = (self.start.or(physical_start).unwrap_or_default(), self.end.or(physical_end).unwrap_or_default()); + let (left, right) = if rtl { (end, start) } else { (start, end) }; + let points = |v: f64| (v / 20.0).clamp(-1296.0, 1296.0); + ParaStyle { + justify: match self.align { + Align::Left => Justify::Left, + Align::Center => Justify::Center, + Align::Right => Justify::Right, + Align::Both(_) if rtl => Justify::JustifyRight, + Align::Both(_) => Justify::JustifyLeft, + Align::Distribute => Justify::JustifyAll, + Align::Start => Justify::Auto, + Align::End if rtl => Justify::Left, + Align::End => Justify::Right, + }, + left_indent: points(f64::from(left)), + right_indent: points(f64::from(right)), + first_line_indent: points(f64::from(self.first)), + space_before: points(f64::from(self.before)), + space_after: points(f64::from(self.after)), + direction: self.rtl.map(|rtl| if rtl { ParaDirection::RightToLeft } else { ParaDirection::LeftToRight }), + kashida: if let Align::Both(k) = self.align { k } else { Kashida::None }, + ..ParaStyle::default() + } + } +} + +/// The kinds of content a warning names. +#[derive(Clone, Copy, Default)] +struct Seen { + pictures: bool, + fields: bool, + revisions: bool, + tables: bool, +} + +struct Reader<'a> { + sheet: &'a Sheet, + fonts: &'a [String], + /// The paragraph being read. + para: Para, + /// A paragraph that has ended (its formatting and its mark's): its break goes before the + /// next text. + pending: Option<(Para, Chars)>, + /// The last cell's paragraph, which its row's break ends. + cell_end: Option<(Para, Chars)>, + /// A cell just ended: a tab goes before the next character of its row. + cell_tab: bool, + /// The fields open: true while their instructions are being read. + fields: Vec<bool>, + /// Fields begun past [`MAX_FIELDS`] and not yet ended. + field_overflow: usize, + /// The text, in runs of one character formatting; paragraphs end with `\n`. + spans: Vec<(String, Chars)>, + /// The bytes of text in `spans`. + len: usize, + /// The formatting of each paragraph that has ended. + paras: Vec<Para>, + /// Past [`MAX_PARAGRAPHS`], [`MAX_RUNS`] or [`text::MAX_TEXT`]. + full: bool, + seen: Seen, +} + +impl<'a> Reader<'a> { + /// A reader of text formatted with the styles of `sheet` and the fonts of `fonts`. + fn new(sheet: &'a Sheet, fonts: &'a [String]) -> Self { + Self { + sheet, + fonts, + para: Para::default(), + pending: None, + cell_end: None, + cell_tab: false, + fields: vec![], + field_overflow: 0, + spans: vec![], + len: 0, + paras: vec![], + full: false, + seen: Seen::default(), + } + } + + /// The text `text`, with the character properties of `chpx` and the paragraph properties of + /// `papx`. + fn read(&mut self, text: &[Char], chpx: &[Run], papx: &[Run]) { + let mut start = 0; + while start < text.len() && !self.full { + // A paragraph runs to its mark: a paragraph or cell mark, or a page or section break at + // the end of its paragraph properties. + let ends = |&(c, fc, width): &Char| { + matches!(c, '\r' | '\u{7}') + || (c == '\u{C}' && run_at(papx, fc).and_then(|i| papx.get(i)).is_some_and(|r| r.end == fc + u32::from(width))) + }; + let end = text.get(start..).and_then(|rest| rest.iter().position(ends)).map_or(text.len(), |at| start + at + 1); + let segment = text.get(start..end).unwrap_or_default(); + let mark_fc = segment.last().map(|&(_, fc, _)| fc).unwrap_or_default(); + let (para, base) = self.paragraph(run_at(papx, mark_fc).and_then(|i| papx.get(i))); + self.para = para; + let mut cached: Option<(Option<usize>, Chars)> = None; + for (k, ch) in segment.iter().enumerate() { + let run = run_at(chpx, ch.1); + let chars = match cached { + Some((r, chars)) if r == run => chars, + _ => self.chars(base, run.and_then(|i| chpx.get(i)).map_or(&[][..], |r| r.grpprl.as_slice())), + }; + cached = Some((run, chars)); + self.character(ch.0, chars, k + 1 == segment.len() && ends(ch)); + } + start = end; + } + } + + /// A paragraph's formatting and its text's formatting before character styles and direct + /// formatting, from its properties `run`. + fn paragraph(&self, run: Option<&Run>) -> (Para, Chars) { + let mut para = Para::default(); + let mut chars = Chars { font: self.sheet.font, ..Chars::default() }; + for s in self.sheet.chain(run.map_or(0, |r| r.istd), 1) { + para.apply(&s.papx); + let style = chars; + chars.apply(&s.chpx, &style); + } + if let Some(r) = run { + para.apply(&r.grpprl); + } + (para, chars) + } + + /// The formatting of text whose paragraph gives `base` and whose properties are `grpprl`: its + /// character style (`sprmCIstd`), then its direct formatting. + fn chars(&self, base: Chars, grpprl: &[u8]) -> Chars { + let mut style = base; + each_prl(grpprl, |sprm, op| { + if sprm == 0x4A30 + && let Some(istd) = u16_at(op, 0) + { + style = base; + for s in self.sheet.chain(istd, 2) { + let before = style; + style.apply(&s.chpx, &before); + } + } + }); + let mut chars = style; + chars.apply(grpprl, &style); + chars + } + + /// Character `c` of the main text in formatting `chars`; `mark`: it ends its paragraph's + /// properties (a page or section break that does is a paragraph's end). + fn character(&mut self, c: char, chars: Chars, mark: bool) { + if chars.inserted || chars.deleted { + self.seen.revisions = true; + } + if chars.deleted { + return; + } + match c { + '\u{13}' => { + self.seen.fields = true; + if self.fields.len() < MAX_FIELDS && self.field_overflow == 0 { + self.fields.push(true); + } else { + self.field_overflow += 1; + } + return; + } + '\u{14}' if self.field_overflow == 0 => { + if let Some(instructions) = self.fields.last_mut() { + *instructions = false; + } + return; + } + '\u{15}' => { + if self.field_overflow > 0 { + self.field_overflow -= 1; + } else { + self.fields.pop(); + } + return; + } + _ => {} + } + if self.field_overflow > 0 || self.fields.contains(&true) || chars.hidden { + return; + } + let para = self.para; + match c { + '\r' if para.row_end => self.row_end(para, chars), + '\r' if para.cell_end => self.cell(para, chars), + '\r' => self.end_paragraph(para, chars), + '\u{7}' if para.row_end => self.row_end(para, chars), + '\u{7}' => self.cell(para, chars), + '\u{C}' if mark => self.end_paragraph(para, chars), + '\u{B}' => self.end_paragraph(para, chars), + '\u{1}' | '\u{8}' => self.seen.pictures = true, + '\u{1E}' => self.put('\u{2011}', chars), + '\u{1F}' => self.put('\u{AD}', chars), + '\t' => self.put('\t', chars), + // Note references, separators and symbols. + '(' if chars.special => {} + c if c.is_control() => {} + c => self.put(c, chars), + } + } + + /// The end of a paragraph in formatting `para` whose mark is in formatting `mark`. + fn end_paragraph(&mut self, para: Para, mark: Chars) { + self.flush(); + self.pending = Some((para, mark)); + } + + /// The end of a table cell: its paragraph goes on in the next cell, after a tab. + fn cell(&mut self, para: Para, mark: Chars) { + self.seen.tables = true; + self.flush(); + if self.cell_tab { + self.push('\t', mark); + } + self.cell_end = Some((para, mark)); + self.cell_tab = true; + } + + /// The end of a table row: its cells' paragraph ends. + fn row_end(&mut self, para: Para, mark: Chars) { + self.seen.tables = true; + self.flush(); + self.cell_tab = false; + self.pending = Some(self.cell_end.take().unwrap_or((para, mark))); + } + + /// Character `c` of the document's text in formatting `chars`. + fn put(&mut self, c: char, chars: Chars) { + self.flush(); + if std::mem::take(&mut self.cell_tab) { + self.push('\t', chars); + } + self.push(c, chars); + } + + /// Writes the break of the paragraph that has ended. + fn flush(&mut self) { + let Some((para, mark)) = self.pending.take() else { return }; + if self.paras.len() >= MAX_PARAGRAPHS { + self.full = true; + return; + } + self.paras.push(para); + // A cell that starts with a break is still separated from the cell before it. + if std::mem::take(&mut self.cell_tab) { + self.push('\t', mark); + } + self.push('\n', mark); + } + + /// Adds `c` to the text in formatting `chars`. + fn push(&mut self, c: char, chars: Chars) { + self.len += c.len_utf8(); + if self.len > text::MAX_TEXT { + self.full = true; + return; + } + let runs = self.spans.len(); + match self.spans.last_mut() { + Some((s, f)) if *f == chars => s.push(c), + _ if runs >= MAX_RUNS => self.full = true, + _ => self.spans.push((c.to_string(), chars)), + } + } + + /// A warning for each kind of content that was left out or changed: what the text held, and + /// the other stories `fib` gives a length. + fn warnings(&self, fib: &Fib) -> Vec<String> { + let mut out = vec![]; + if self.seen.pictures { + out.push("the Word document's pictures and embedded objects were left out".to_string()); + } + if self.seen.fields { + out.push("the Word document's fields were placed as the text of their results".to_string()); + } + if self.seen.revisions { + out.push("the Word document's tracked changes were accepted: deleted text was left out and inserted text kept".to_string()); + } + if self.seen.tables { + out.push("the Word document's tables were placed as paragraphs with their cells separated by tabs".to_string()); + } + let names = ["footnotes", "headers and footers", "comments", "endnotes", "text boxes"]; + let [ftn, hdd, atn, edn, txbx, hdr_txbx] = fib.stories; + let present = [ftn, hdd, atn, edn, txbx.max(hdr_txbx)]; + let stories: Vec<&str> = names.iter().zip(present).filter(|(_, n)| *n > 0).map(|(name, _)| *name).collect(); + if let Some((last, rest)) = stories.split_last() { + let list = if rest.is_empty() { (*last).to_string() } else { format!("{} and {last}", rest.join(", ")) }; + out.push(format!("the Word document's {list} were left out")); + } + out + } + + /// The character attributes of formatting `c`. + fn style(&self, c: &Chars) -> CharStyle { + let mut s = CharStyle::default(); + if let Some(name) = c.font.and_then(|i| self.fonts.get(usize::from(i))).filter(|n| !n.is_empty()) { + s.font_family.clone_from(name); + } + s.font_style = match (c.bold, c.italic) { + (true, true) => "Bold Italic", + (true, false) => "Bold", + (false, true) => "Italic", + (false, false) => "Regular", + } + .into(); + s.size = (f64::from(c.half_points) / 2.0).clamp(0.1, 1296.0); + s.baseline_shift = (f64::from(c.shift) / 2.0).clamp(-1296.0, 1296.0); + if let Some([r, g, b]) = c.color { + s.fill = Paint::solid(vectorcraft_color::Color::rgb8(r, g, b)); + } + s.underline = c.underline; + s.strikethrough = c.strike || c.dstrike; + s.all_caps = c.caps; + // Document Setup's proportions replace these when the type is placed. + s.small_caps = c.small_caps.then_some(70.0); + s.position = match c.script { + Script::Normal => CharPosition::Normal, + Script::Super => CharPosition::Superscript(ScriptMetrics::DEFAULT), + Script::Sub => CharPosition::Subscript(ScriptMetrics::DEFAULT), + }; + s + } + + /// The text read, without blank paragraphs at its end, and each paragraph's attributes. + fn finish(mut self, cmd: &str) -> Result<Story> { + if self.full { + return Err(bad( + cmd, + format!( + "the Word document has too much text or formatting to place as type (at most {MAX_PARAGRAPHS} paragraphs, {MAX_RUNS} runs and {} MB of text)", + text::MAX_TEXT >> 20 + ), + )); + } + let last = self.pending.take().map_or(self.para, |(para, _)| para); + self.paras.push(last); + let mut all: String = self.spans.iter().map(|(s, _)| s.as_str()).collect(); + while self.paras.len() > 1 + && let Some(at) = all.rfind('\n') + && all.get(at + 1..).is_some_and(|tail| tail.trim().is_empty()) + { + all.truncate(at); + self.paras.pop(); + } + let mut keep = all.len(); + let mut runs: Vec<TextRun> = vec![]; + for (s, chars) in &self.spans { + let piece = s.get(..keep.min(s.len())).unwrap_or_default(); + keep -= piece.len(); + if piece.is_empty() { + continue; + } + let style = self.style(chars); + match runs.last_mut() { + Some(r) if r.style == style => r.text.push_str(piece), + _ => runs.push(TextRun::new(piece, style)), + } + } + let paras = self.paras.iter().map(Para::style).collect(); + Ok(Story { runs, paras }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compressed_text_maps_the_bytes_the_specification_lists() { + let decoded: String = [b'a', 0x80, 0x82, 0x93, 0x94, 0x9E, 0x9F, 0xE9].map(compressed).iter().collect(); + assert_eq!(decoded, "a\u{80}‚“”\u{9E}Ÿé", "not Windows-1252: 0x80 and 0x9E are themselves"); + } + + #[test] + fn operands_take_the_size_their_sprm_gives() { + let mut seen = vec![]; + // sprmCFBold 1, sprmCHps 24, sprmCCv, a variable operand of 2 bytes, then a cut-off Prl. + let grpprl = [0x35, 0x08, 0x01, 0x43, 0x4A, 24, 0, 0x70, 0x68, 1, 2, 3, 0, 0x2A, 0xC6, 2, 9, 9, 0x43, 0x4A, 1]; + each_prl(&grpprl, |sprm, op| seen.push((sprm, op.to_vec()))); + assert_eq!(seen, [(0x0835, vec![1]), (0x4A43, vec![24, 0]), (0x6870, vec![1, 2, 3, 0]), (0xC62A, vec![9, 9])]); + } +} diff --git a/crates/engine/src/tests/textimport.rs b/crates/engine/src/tests/textimport.rs index d87909bbab..4091191613 100644 --- a/crates/engine/src/tests/textimport.rs +++ b/crates/engine/src/tests/textimport.rs @@ -467,15 +467,368 @@ fn malformed_docx_fails_cleanly() { assert_eq!(s.doc().unwrap().history.undo.len(), 2, "failed places leave no undo step"); } +/// The bytes of the Prls `prls`: each sprm and its operand. +fn prls(prls: &[(u16, &[u8])]) -> Vec<u8> { + prls.iter().flat_map(|(sprm, op)| sprm.to_le_bytes().into_iter().chain(op.iter().copied())).collect() +} + +/// A style of a [`Word97`] document: its kind (1 paragraph, 2 character), the style it is based +/// on, and its paragraph and character properties. +type Word97Style = (u16, u16, Vec<u8>, Vec<u8>); + +/// A Word 97-2003 document, built as \[MS-DOC\] lays one out: a file information block, the main +/// text's pieces stored last first, one property page per run of up to 16 character or paragraph +/// property runs, the piece table, style sheet and font table in the table stream, all in a +/// compound file. +#[derive(Default)] +struct Word97 { + /// The main text's pieces: their text and whether it is stored compressed. + pieces: Vec<(&'static str, bool)>, + /// Character properties of characters `start..end`. + chpx: Vec<(u32, u32, Vec<u8>)>, + /// The paragraph style and properties of the paragraph whose mark is character `cp`; a + /// character's paragraph is the first one whose mark is at or after it. + papx: Vec<(u32, u16, Vec<u8>)>, + /// The styles by istd; None: an empty slot. + styles: Vec<Option<Word97Style>>, + fonts: Vec<&'static str>, + /// FibBase's flags and `nFib` (0: 0x00C1). + flags: u16, + nfib: u16, + /// The table stream is `0Table` (else `1Table`). + zero_table: bool, + /// `ccpFtn`, `ccpHdd`, `ccpAtn`, `ccpEdn`, `ccpTxbx` and `ccpHdrTxbx`. + stories: [u32; 6], + /// Characters `ccpText` gives beyond the pieces. + ccp_extra: u32, + /// A Clx to write instead of the pieces'. + clx: Option<Vec<u8>>, +} + +/// One 512-byte property page of `runs` (file positions and properties), written to `wd`; its +/// page number. +fn property_page(runs: &[(u32, u32, Vec<u8>)], papx: bool, wd: &mut Vec<u8>) -> u32 { + let mut page = [0u8; 512]; + let n = runs.len(); + for (i, r) in runs.iter().enumerate() { + page[4 * i..4 * i + 4].copy_from_slice(&r.0.to_le_bytes()); + } + page[4 * n..4 * n + 4].copy_from_slice(&runs[n - 1].1.to_le_bytes()); + let mut top = 511; + for (i, (_, _, props)) in runs.iter().enumerate() { + let blob = match (papx, props.len() % 2) { + (false, _) if props.is_empty() => continue, + (false, _) => [vec![props.len() as u8], props.clone()].concat(), + // PapxInFkp: cb with 2 × cb − 1 bytes, or 0 and cb′ with 2 × cb′ bytes. + (true, 1) => [vec![props.len().div_ceil(2) as u8], props.clone()].concat(), + (true, _) => [vec![0, (props.len() / 2) as u8], props.clone()].concat(), + }; + top = (top - blob.len()) & !1; + page[top..top + blob.len()].copy_from_slice(&blob); + page[4 * (n + 1) + if papx { 13 * i } else { i }] = (top / 2) as u8; + } + page[511] = n as u8; + wd.resize(wd.len().div_ceil(512) * 512, 0); + let pn = (wd.len() / 512) as u32; + wd.extend(page); + pn +} + +impl Word97 { + fn build(&self) -> Vec<u8> { + let mut wd = vec![0u8; 900]; + let mut stored = vec![0u32; self.pieces.len()]; + for (i, (text, compressed)) in self.pieces.iter().enumerate().rev() { + stored[i] = wd.len() as u32; + if *compressed { + wd.extend(text.chars().map(|c| match c { + '“' => 0x93, + '”' => 0x94, + c => u8::try_from(u32::from(c)).unwrap(), + })); + } else { + wd.extend(text.encode_utf16().flat_map(u16::to_le_bytes)); + } + } + // Each character's file position and size, in character order. + let mut chars: Vec<(u32, u32)> = vec![]; + for ((text, compressed), &at) in self.pieces.iter().zip(&stored) { + let w = if *compressed { 1 } else { 2 }; + chars.extend((0..text.encode_utf16().count() as u32).map(|k| (at + k * w, w))); + } + let chpx_of = |cp: u32| (0u32, self.chpx.iter().rev().find(|(s, e, _)| (*s..*e).contains(&cp)).map(|r| r.2.clone()).unwrap_or_default()); + let papx_of = |cp: u32| { + let p = self.papx.iter().filter(|(mark, _, _)| *mark >= cp).min_by_key(|(mark, _, _)| *mark); + p.map_or((u32::MAX, vec![0, 0]), |(mark, istd, g)| (*mark, [istd.to_le_bytes().to_vec(), g.clone()].concat())) + }; + let mut bins = vec![]; + for (papx, of) in [(false, &chpx_of as &dyn Fn(u32) -> (u32, Vec<u8>)), (true, &papx_of)] { + let mut runs: Vec<(u32, u32, u32, Vec<u8>)> = vec![]; + for (cp, &(fc, w)) in chars.iter().enumerate() { + let (key, props) = of(cp as u32); + match runs.last_mut() { + Some((_, end, k, p)) if *end == fc && *k == key && *p == props => *end = fc + w, + _ => runs.push((fc, fc + w, key, props)), + } + } + // Pages of contiguous runs, 16 at most. + let mut groups: Vec<Vec<(u32, u32, Vec<u8>)>> = vec![]; + for (start, end, _, props) in runs { + match groups.last_mut() { + Some(g) if g.len() < 16 && g.last().unwrap().1 == start => g.push((start, end, props)), + _ => groups.push(vec![(start, end, props)]), + } + } + let mut fcs: Vec<u32> = groups.iter().map(|g| g[0].0).collect(); + fcs.extend(groups.last().map(|g| g.last().unwrap().1)); + let pns: Vec<u32> = groups.iter().map(|g| property_page(g, papx, &mut wd)).collect(); + bins.push([fcs, pns].concat().into_iter().flat_map(u32::to_le_bytes).collect::<Vec<u8>>()); + } + let mut cps = vec![0u32]; + for (text, _) in &self.pieces { + cps.push(cps.last().unwrap() + text.encode_utf16().count() as u32); + } + let pcds = self.pieces.iter().zip(&stored).flat_map(|((_, compressed), &at)| { + let fc = if *compressed { (at * 2) | 0x4000_0000 } else { at }; + [&[0u8, 0][..], &fc.to_le_bytes(), &[0, 0]].concat() + }); + let plc: Vec<u8> = cps.iter().flat_map(|c| c.to_le_bytes()).chain(pcds).collect(); + let clx = self.clx.clone().unwrap_or_else(|| [vec![0x02], (plc.len() as u32).to_le_bytes().to_vec(), plc].concat()); + let words = |v: &[u16]| v.iter().flat_map(|w| w.to_le_bytes()).collect::<Vec<u8>>(); + let mut stsh = words(&[18, self.styles.len() as u16, 10, 1, 0, 15, 0, 0, 0, 0]); + for (istd, s) in self.styles.iter().enumerate() { + let Some((stk, base, papx, chpx)) = s else { + stsh.extend([0, 0]); + continue; + }; + let upx = |bytes: Vec<u8>| [words(&[bytes.len() as u16]), bytes.clone(), vec![0; bytes.len() % 2]].concat(); + let grlpupx = match stk { + 1 => [upx([(istd as u16).to_le_bytes().to_vec(), papx.clone()].concat()), upx(chpx.clone())].concat(), + _ => upx(chpx.clone()), + }; + let cupx = if *stk == 1 { 2 } else { 1 }; + let mut std = words(&[0x0FFE, stk | (base << 4), cupx | (0x0FFF << 4), 0, 0, 1, u16::from(b'S'), 0]); + std.extend(grlpupx); + let len = std.len() as u16; + std[6..8].copy_from_slice(&len.to_le_bytes()); + stsh.extend(len.to_le_bytes()); + stsh.extend(std); + } + let mut ffn = words(&[self.fonts.len() as u16, 0]); + for name in &self.fonts { + let units: Vec<u16> = name.encode_utf16().chain([0]).collect(); + ffn.push((39 + 2 * units.len()) as u8); + ffn.extend([0u8; 39]); + ffn.extend(words(&units)); + } + let mut table = vec![]; + let mut pairs = vec![(0u32, 0u32); 0x5D]; + for (index, part) in [(1, stsh), (12, bins[0].clone()), (13, bins[1].clone()), (15, ffn), (33, clx)] { + pairs[index] = (table.len() as u32, part.len() as u32); + table.extend(part); + } + let mut put = |at: usize, bytes: &[u8]| wd[at..at + bytes.len()].copy_from_slice(bytes); + let flags = self.flags | if self.zero_table { 0 } else { 0x0200 }; + put(0, &words(&[0xA5EC, if self.nfib == 0 { 0x00C1 } else { self.nfib }])); + put(10, &words(&[flags, 0x00BF])); + put(32, &words(&[14])); + put(62, &words(&[22])); + put(76, &(chars.len() as u32 + self.ccp_extra).to_le_bytes()); + for (i, n) in [4, 5, 7, 8, 9, 10].into_iter().zip(self.stories) { + put(64 + 4 * i, &n.to_le_bytes()); + } + put(152, &words(&[0x5D])); + for (i, (fc, lcb)) in pairs.iter().enumerate() { + put(154 + 8 * i, &[fc.to_le_bytes(), lcb.to_le_bytes()].concat()); + } + compound_file(&[("WordDocument", &wd), (if self.zero_table { "0Table" } else { "1Table" }, &table)]) + } +} + +/// A compound file holding `streams`. +fn compound_file(streams: &[(&str, &[u8])]) -> Vec<u8> { + let mut cf = cfb::CompoundFile::create(std::io::Cursor::new(Vec::new())).unwrap(); + for (name, bytes) in streams { + std::io::Write::write_all(&mut cf.create_stream(name).unwrap(), bytes).unwrap(); + } + cf.flush().unwrap(); + cf.into_inner().into_inner() +} + +#[test] +fn doc_places_as_area_type_with_its_styles_and_formatting() { + let navy: &[u8] = &[0x1F, 0x38, 0x64, 0]; + // Normal: 11 pt with 8 pt after; Heading (based on Normal): centered, 12 pt before and none + // after, in Arial, bold, 16 pt and navy; Emphasis, a character style: italic. + let mut styles = vec![ + Some((1, 0x0FFF, prls(&[(0xA414, &[160, 0])]), prls(&[(0x4A43, &[22, 0])]))), + Some(( + 1, + 0, + prls(&[(0x2403, &[1]), (0xA413, &[240, 0]), (0xA414, &[0, 0])]), + prls(&[(0x4A4F, &[1, 0]), (0x0835, &[1]), (0x4A43, &[32, 0]), (0x6870, navy)]), + )), + ]; + styles.resize_with(10, || None); + styles.push(Some((2, 0x0FFF, vec![], prls(&[(0x0836, &[1])])))); + // The first piece holds characters 0 to 24 ("notes" at 7, the first paragraph mark at 12), the + // second "styled" at 25, "2" at 31, "hidden" at 32, "gone" at 38, " café ✓ " at 42, the field + // at 50 (its result "7" at 58) and the paragraph mark at 60. + let doc = Word97 { + pieces: vec![("Report notes\r“Plain” and ", true), ("styled2hiddengone café ✓ \u{13} PAGE \u{14}7\u{15}\r", false)], + chpx: vec![ + (7, 12, prls(&[(0x4A30, &[10, 0])])), + (25, 31, prls(&[(0x4A4F, &[2, 0]), (0x0836, &[1]), (0x2A3E, &[1])])), + (31, 32, prls(&[(0x2A48, &[1])])), + (32, 38, prls(&[(0x083C, &[1])])), + (38, 42, prls(&[(0x0800, &[1])])), + (42, 50, prls(&[(0x0801, &[1])])), + ], + papx: vec![(12, 1, vec![]), (60, 0, prls(&[(0x840F, &[0xD0, 0x02]), (0x8411, &(-360i16).to_le_bytes()), (0x2403, &[3])]))], + styles, + fonts: vec!["Times New Roman", "Arial", "Courier New"], + ..Word97::default() + }; + let mut s = session(); + s.execute("document.setup", &json!({"superscript": {"size": 50, "position": 40}})).unwrap(); + let file = json!({"name": "report.doc", "dataBase64": vectorcraft_format::base64_encode(&doc.build())}); + let r = s.execute("file.place", &file).unwrap(); + assert_eq!((r["format"].as_str(), r["name"].as_str()), (Some("doc"), Some("report.doc"))); + let (text, frame) = placed(&s, &r); + assert_eq!(text, "Report notes\n“Plain” and styled2 café ✓ 7", "hidden and deleted text and the field's instructions are left out"); + assert!(close(frame, Rect::new(36.0, 36.0, 364.0, 264.0)), "the artboard less a 36 pt margin: {frame:?}"); + let n = s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).unwrap().clone(); + let NodeKind::Text(t) = &n.kind else { panic!("not type") }; + let runs: Vec<_> = t.runs.iter().map(|r| (r.text.as_str(), r.style.font_family.as_str(), r.style.font_style.as_str(), r.style.size)).collect(); + assert_eq!( + runs, + [ + ("Report ", "Arial", "Bold", 16.0), + ("notes", "Arial", "Bold Italic", 16.0), + ("\n", "Arial", "Bold", 16.0), + ("“Plain” and ", "Times New Roman", "Regular", 11.0), + ("styled", "Courier New", "Italic", 11.0), + ("2", "Times New Roman", "Regular", 11.0), + (" café ✓ 7", "Times New Roman", "Regular", 11.0), + ] + ); + let navy = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb8(0x1F, 0x38, 0x64)); + assert_eq!((t.runs[0].style.fill == navy, t.runs[1].style.fill == navy, t.runs[3].style.fill == navy), (true, true, false)); + assert_eq!((t.runs[3].style.underline, t.runs[4].style.underline), (false, true)); + let superscript = vectorcraft_doc::ScriptMetrics { size: 50.0, position: 40.0 }; + assert_eq!(t.runs[5].style.position, vectorcraft_doc::CharPosition::Superscript(superscript), "in Document Setup's proportions"); + let paras = t.paragraph_styles(); + let summary: Vec<_> = paras.iter().map(|p| (p.justify, p.left_indent, p.first_line_indent, p.space_before, p.space_after)).collect(); + assert_eq!(summary, [(vectorcraft_doc::Justify::Center, 0.0, 0.0, 12.0, 0.0), (vectorcraft_doc::Justify::JustifyLeft, 36.0, -18.0, 0.0, 8.0)]); + let fields = "the Word document's fields were placed as the text of their results"; + let revisions = "the Word document's tracked changes were accepted: deleted text was left out and inserted text kept"; + assert_eq!(r["warnings"], json!([fields, revisions])); + let st = s.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.selection.objects.len()), (2, 1), "Document Setup and Place, each one undo step"); + // Info and the place cursor report it as a Word 97-2003 document, with the same warnings. + let info = s.execute("file.place.info", &file).unwrap(); + assert_eq!((info["format"].as_str(), info["width"].as_f64(), &info["warnings"]), (Some("doc"), Some(468.0), &json!([fields, revisions]))); + let q = s.execute("file.place.queue", &json!({"files": [file]})).unwrap(); + assert_eq!((q["count"].as_u64(), q["files"][0]["format"].as_str()), (Some(1), Some("doc"))); +} + +#[test] +fn doc_tables_breaks_and_other_stories_place_as_paragraphs_and_tabs_with_warnings() { + let in_table = prls(&[(0x2416, &[1])]); + // A line break; a table row of two cells; a page break inside a paragraph and a section break + // that ends one; a picture, a tab and a nonbreaking hyphen; right-to-left justified text. + let text = "Line one\u{B}line two\ra\u{7}b\u{7}\u{7}x\u{C}y\rsec\u{C}next\rpic\u{1}ture\tend\u{1E}ok\rrtl\r"; + let doc = Word97 { + pieces: vec![(text, true)], + // Marks: the first paragraph's at 17, the cells' at 19 and 21, the row's at 22, the page + // break at 24 inside the paragraph that ends at 26, the section break at 30, and the + // paragraph marks at 35, 51 and 55. + papx: vec![ + (17, 0, vec![]), + (19, 0, in_table.clone()), + (21, 0, in_table), + (22, 0, prls(&[(0x2416, &[1]), (0x2417, &[1])])), + (26, 0, vec![]), + (30, 0, vec![]), + (35, 0, vec![]), + (51, 0, vec![]), + (55, 0, prls(&[(0x2441, &[1]), (0x2461, &[3])])), + ], + zero_table: true, + stories: [5, 0, 2, 0, 0, 0], + ..Word97::default() + }; + let mut s = session(); + // Recognized by its WordDocument stream whatever its name says. + let r = s.execute("file.place", &json!({"name": "notes.bin", "dataBase64": vectorcraft_format::base64_encode(&doc.build())})).unwrap(); + assert_eq!(r["format"].as_str(), Some("doc")); + assert_eq!(placed(&s, &r).0, "Line one\nline two\na\tb\nxy\nsec\nnext\npicture\tend\u{2011}ok\nrtl"); + let n = s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).unwrap().clone(); + let NodeKind::Text(t) = &n.kind else { panic!("not type") }; + let last = t.paragraph_styles().last().cloned().unwrap(); + assert_eq!((last.justify, last.direction), (vectorcraft_doc::Justify::JustifyRight, Some(vectorcraft_doc::ParaDirection::RightToLeft))); + assert_eq!( + r["warnings"], + json!([ + "the Word document's pictures and embedded objects were left out", + "the Word document's tables were placed as paragraphs with their cells separated by tabs", + "the Word document's footnotes and comments were left out", + ]) + ); +} + +#[test] +fn malformed_doc_fails_cleanly() { + let mut s = session(); + let place = |s: &mut Session, name: &str, bytes: &[u8]| { + s.execute("file.place", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).map_err(|e| e.to_string()) + }; + let words = || Word97 { pieces: vec![("words\r", true)], ..Word97::default() }; + let e = place(&mut s, "a.doc", b"Plain words, not a compound file").unwrap_err(); + assert!(e.contains("not a format VectorCraft reads"), "{e}"); + // An RTF file named `.doc` is still placed as RTF. + let r = place(&mut s, "a.doc", br"{\rtf1 Rich}").unwrap(); + assert_eq!((r["format"].as_str(), placed(&s, &r).0.as_str()), (Some("rtf"), "Rich")); + let e = place(&mut s, "a.doc", &compound_file(&[("Other", b"x")])).unwrap_err(); + assert!(e.contains("no WordDocument stream"), "{e}"); + let e = place(&mut s, "a.bin", &compound_file(&[("Other", b"x")])).unwrap_err(); + assert!(e.contains("not a format VectorCraft reads"), "a compound file of something else isn't read as a Word document: {e}"); + let e = place(&mut s, "a.doc", &[&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1][..], &[0; 600]].concat()).unwrap_err(); + assert!(e.contains("compound file structure is damaged"), "{e}"); + let e = place(&mut s, "a.doc", &compound_file(&[("WordDocument", &[0; 900])])).unwrap_err(); + assert!(e.contains("doesn't start with a file information block"), "{e}"); + let e = place(&mut s, "a.doc", &Word97 { nfib: 0x0065, ..words() }.build()).unwrap_err(); + assert!(e.contains("Word 6.0 or Word 95"), "{e}"); + let e = place(&mut s, "a.doc", &Word97 { flags: 0x0100, ..words() }.build()).unwrap_err(); + assert!(e.contains("encrypted"), "{e}"); + let e = place(&mut s, "a.doc", &Word97 { flags: 0x0004, ..words() }.build()).unwrap_err(); + assert!(e.contains("fast save"), "{e}"); + let e = place(&mut s, "a.doc", &Word97 { ccp_extra: 3, ..words() }.build()).unwrap_err(); + assert!(e.contains("doesn't cover its text"), "{e}"); + // A piece stored past the end of the WordDocument stream. + let far = [&0u32.to_le_bytes()[..], &6u32.to_le_bytes(), &[0, 0], &0x00FF_0000u32.to_le_bytes(), &[0, 0]].concat(); + let clx = [&[0x02][..], &(far.len() as u32).to_le_bytes(), &far].concat(); + let e = place(&mut s, "a.doc", &Word97 { clx: Some(clx), ..words() }.build()).unwrap_err(); + assert!(e.contains("lies outside its WordDocument stream"), "{e}"); + let e = place(&mut s, "a.doc", &Word97 { clx: Some(vec![0x02, 0xFF, 0xFF, 0, 0]), ..words() }.build()).unwrap_err(); + assert!(e.contains("piece table is damaged"), "{e}"); + let e = place(&mut s, "a.doc", &Word97 { pieces: vec![("\r\r", true)], ..Word97::default() }.build()).unwrap_err(); + assert!(e.contains("no text to place"), "{e}"); + let r = place(&mut s, "a.doc", &words().build()).unwrap(); + assert_eq!(placed(&s, &r).0, "words"); + assert_eq!(s.doc().unwrap().history.undo.len(), 2, "failed places leave no undo step"); +} + #[test] fn place_reads_what_open_reads_and_text_files() { - use cmd::fileio::{DOCX_EXTS, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS}; - assert_eq!(PLACE_EXTS, [OPEN_EXTS, TEXT_EXTS, RTF_EXTS, DOCX_EXTS].concat()); + use cmd::fileio::{DOC_EXTS, DOCX_EXTS, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS}; + assert_eq!(PLACE_EXTS, [OPEN_EXTS, TEXT_EXTS, RTF_EXTS, DOCX_EXTS, DOC_EXTS].concat()); let filters: Vec<_> = cmd::fileio::place_filters().collect(); - assert_eq!((filters.first(), filters.last()), (Some(&("All placeable files", PLACE_EXTS)), Some(&("Word", DOCX_EXTS)))); - assert_eq!(filters.get(filters.len() - 3..), Some(&[("Text", TEXT_EXTS), ("RTF", RTF_EXTS), ("Word", DOCX_EXTS)][..])); + let word: (&str, &[&str]) = ("Word", &["docx", "doc"]); + assert_eq!((filters.first(), filters.last()), (Some(&("All placeable files", PLACE_EXTS)), Some(&word))); + assert_eq!(filters.get(filters.len() - 3..), Some(&[("Text", TEXT_EXTS), ("RTF", RTF_EXTS), word][..])); assert!( - !cmd::fileio::open_filters().any(|(_, exts)| exts.contains(&"txt") || exts.contains(&"rtf") || exts.contains(&"docx")), + !cmd::fileio::open_filters().any(|(_, exts)| ["txt", "rtf", "docx", "doc"].iter().any(|e| exts.contains(e))), "Open doesn't read text, RTF or Word files" ); } diff --git a/crates/engine/tests/text_import_fuzz.rs b/crates/engine/tests/text_import_fuzz.rs index 867b016a97..3ea6f94d9a 100644 --- a/crates/engine/tests/text_import_fuzz.rs +++ b/crates/engine/tests/text_import_fuzz.rs @@ -1,6 +1,6 @@ //! Untrusted text files placed with File → Place never crash: any bytes, with any Text Import -//! Options, place as area type or fail with an error, and so do hostile RTF files and Word -//! documents. +//! Options, place as area type or fail with an error, and so do hostile RTF files, Word documents +//! and Word 97-2003 documents. //! //! `PROPTEST_CASES=20000 cargo test -p vectorcraft-engine --test text_import_fuzz` runs a deeper search. // Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). @@ -91,6 +91,164 @@ proptest! { }); prop_assert!(r.is_ok(), "panicked: {:?}", r.err()); } + + #[test] + fn any_doc_places_without_panics( + text in prop::collection::vec(prop::sample::select(DOC_CHARS.chars().collect::<Vec<_>>()), 1..60), + compressed in any::<bool>(), + chpx in arb_grpprl(), + papx in arb_grpprl(), + istd in 0u16..4, + stsh in prop_oneof![1 => prop::collection::vec(any::<u8>(), 0..120), 3 => arb_stsh()], + ffn in prop::collection::vec(any::<u8>(), 0..80), + changes in prop_oneof![ + 3 => Just(vec![]), + 1 => prop::collection::vec((any::<bool>(), any::<prop::sample::Index>(), any::<u8>()), 1..4), + ], + name in prop::sample::select(vec!["fuzz.doc", "fuzz.bin"]), + ) { + vectorcraft_text::FontDb::global().set_system_fallback(false); + let text: String = text.into_iter().collect(); + let (mut wd, mut table) = word97(&text, compressed, &chpx, istd, &papx, &stsh, &ffn); + // A changed byte anywhere in either stream: in the FIB, the text, a property page or a + // table. + for (in_table, at, byte) in changes { + let stream = if in_table { &mut table } else { &mut wd }; + let i = at.index(stream.len()); + stream[i] = byte; + } + let mut cf = cfb::CompoundFile::create(std::io::Cursor::new(Vec::new())).unwrap(); + std::io::Write::write_all(&mut cf.create_stream("WordDocument").unwrap(), &wd).unwrap(); + std::io::Write::write_all(&mut cf.create_stream("1Table").unwrap(), &table).unwrap(); + cf.flush().unwrap(); + let data = cf.into_inner().into_inner(); + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&data), "thumbnail": 8}); + let _ = s.execute("file.place.info", &p); + let _ = s.execute("file.place", &p); + }); + prop_assert!(r.is_ok(), "panicked: {:?}", r.err()); + } +} + +/// Characters of a Word document's text: letters, marks of paragraphs, cells and breaks, fields, +/// pictures, hyphens and surrogate-free Unicode. +const DOC_CHARS: &str = "ab \r\u{7}\u{B}\u{C}\u{13}\u{14}\u{15}\u{1}\u{8}\t\u{1E}\u{1F}(é“✓"; + +/// Character and paragraph properties: Prls the Word 97-2003 reader knows, with operands in and out +/// of range, and raw bytes. +fn arb_grpprl() -> impl Strategy<Value = Vec<u8>> { + let prl = prop_oneof![ + prop::sample::select(vec![ + &[0x35, 0x08, 0x81][..], + &[0x35, 0x08, 0x80], + &[0x3C, 0x08, 0x01], + &[0x00, 0x08, 0x01], + &[0x01, 0x08, 0x01], + &[0x55, 0x08, 0x01], + &[0x30, 0x4A, 0x0A, 0x00], + &[0x30, 0x4A, 0xFF, 0xFF], + &[0x43, 0x4A, 0xFF, 0xFF], + &[0x4F, 0x4A, 0x07, 0x00], + &[0x42, 0x2A, 0x63], + &[0x70, 0x68, 1, 2, 3, 0xFF], + &[0x45, 0x48, 0x00, 0x80], + &[0x03, 0x24, 0x09], + &[0x61, 0x24, 0x08], + &[0x17, 0x24, 0x01], + &[0x4B, 0x24, 0x01], + &[0x41, 0x24, 0x01], + &[0x0F, 0x84, 0x00, 0x80], + &[0x13, 0xA4, 0xFF, 0xFF], + &[0x08, 0xD6, 0xFF, 0xFF], + &[0x15, 0xC6, 0xFF, 0x7F], + &[0x2A, 0xC6, 0xFF], + ]) + .prop_map(<[u8]>::to_vec), + prop::collection::vec(any::<u8>(), 0..4), + ]; + prop::collection::vec(prl, 0..6).prop_map(|p| p.concat()) +} + +/// A style sheet of up to four styles (paragraph or character, based on another or none) with +/// properties of [`arb_grpprl`], or empty slots. +fn arb_stsh() -> impl Strategy<Value = Vec<u8>> { + let style = prop::option::of((1u16..3, prop_oneof![Just(0x0FFFu16), 0u16..5], arb_grpprl(), arb_grpprl())); + prop::collection::vec(style, 0..5).prop_map(|styles| { + let words = |v: &[u16]| v.iter().flat_map(|w| w.to_le_bytes()).collect::<Vec<u8>>(); + let mut stsh = words(&[18, styles.len() as u16, 10, 1, 0, 15, 0, 0, 0, 0]); + for s in styles { + let Some((stk, base, papx, chpx)) = s else { + stsh.extend([0, 0]); + continue; + }; + let upx = |b: Vec<u8>| [words(&[b.len() as u16]), b.clone(), vec![0; b.len() % 2]].concat(); + let (cupx, grlpupx) = if stk == 1 { (2, [upx([vec![0, 0], papx].concat()), upx(chpx)].concat()) } else { (1, upx(chpx)) }; + let mut std = words(&[0x0FFE, stk | (base << 4), cupx | (0x0FFF << 4), 0, 0, 1, u16::from(b'S'), 0]); + std.extend(grlpupx); + stsh.extend((std.len() as u16).to_le_bytes()); + stsh.extend(std); + } + stsh + }) +} + +/// The WordDocument and table streams of a Word 97-2003 document whose main text is `text` in one +/// piece, with one page of character properties `chpx` and one of paragraph properties `papx` of +/// style `istd` covering it, and the style sheet `stsh` and font table `ffn`. +fn word97(text: &str, compressed: bool, chpx: &[u8], istd: u16, papx: &[u8], stsh: &[u8], ffn: &[u8]) -> (Vec<u8>, Vec<u8>) { + let mut wd = vec![0u8; 1024]; + let at = wd.len() as u32; + if compressed { + wd.extend(text.chars().map(|c| if c == '“' { 0x93 } else { u32::from(c).min(0xFF) as u8 })); + } else { + wd.extend(text.encode_utf16().flat_map(u16::to_le_bytes)); + } + let ccp = text.encode_utf16().count() as u32; + let end = wd.len() as u32; + // One page each: a run of every character, its properties near the page's end. + let page = |props: Vec<u8>, papx: bool| { + let mut p = vec![0u8; 512]; + p[0..4].copy_from_slice(&at.to_le_bytes()); + p[4..8].copy_from_slice(&end.to_le_bytes()); + let blob = if papx { [vec![0, (props.len() / 2) as u8], props].concat() } else { [vec![props.len() as u8], props].concat() }; + let top = (511 - blob.len().min(400)) & !1; + let n = blob.len().min(511 - top); + p[top..top + n].copy_from_slice(&blob[..n]); + p[8] = (top / 2) as u8; + p[511] = 1; + p + }; + let papx_props = [istd.to_le_bytes().to_vec(), papx.to_vec(), vec![0; papx.len() % 2]].concat(); + wd.resize(wd.len().div_ceil(512) * 512, 0); + let chpx_page = (wd.len() / 512) as u32; + wd.extend(page(chpx.iter().copied().take(200).collect(), false)); + wd.extend(page(papx_props.into_iter().take(400).collect(), true)); + let bte = |pn: u32| [at, end, pn].into_iter().flat_map(u32::to_le_bytes).collect::<Vec<u8>>(); + let fc = if compressed { (at * 2) | 0x4000_0000 } else { at }; + let plc = [&0u32.to_le_bytes()[..], &ccp.to_le_bytes(), &[0, 0], &fc.to_le_bytes(), &[0, 0]].concat(); + let clx = [&[0x02][..], &(plc.len() as u32).to_le_bytes(), &plc].concat(); + let mut table = vec![]; + let mut pairs = vec![(0u32, 0u32); 0x5D]; + for (index, part) in [(1, stsh.to_vec()), (12, bte(chpx_page)), (13, bte(chpx_page + 1)), (15, ffn.to_vec()), (33, clx)] { + pairs[index] = (table.len() as u32, part.len() as u32); + table.extend(part); + } + let words = |v: &[u16]| v.iter().flat_map(|w| w.to_le_bytes()).collect::<Vec<u8>>(); + let mut put = |at: usize, bytes: &[u8]| wd[at..at + bytes.len()].copy_from_slice(bytes); + put(0, &words(&[0xA5EC, 0x00C1])); + put(10, &words(&[0x0200, 0x00BF])); + put(32, &words(&[14])); + put(62, &words(&[22])); + put(76, &ccp.to_le_bytes()); + put(80, &1u32.to_le_bytes()); + put(152, &words(&[0x5D])); + for (i, (fc, lcb)) in pairs.iter().enumerate() { + put(154 + 8 * i, &[fc.to_le_bytes(), lcb.to_le_bytes()].concat()); + } + (wd, table) } /// A well-formed paragraph, or a table row of two such paragraphs. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 1d84d38623..a3858ef8e5 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -17,7 +17,7 @@ from the public specifications, and users' own `.ai` files are used locally only | | Illustrator | VectorCraft | Notes | |---|---:|---:|---| -| Formats opened or placed | ~30 | 27 | missing: FreeHand, CorelDRAW, DWG, HEIC/HEIF, PICT, Pixar, Word `.doc`, PS | +| Formats opened or placed | ~30 | 28 | missing: FreeHand, CorelDRAW, DWG, HEIC/HEIF, PICT, Pixar, PS | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (no Illustrator editing data) or as legacy version 7 (layers and groups, one artboard per file) | | Formats exported | ~16 | 17 | missing: DWG, 3D (OBJ/USDA/glTF); extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | | **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting | @@ -113,7 +113,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Text `.txt` | place, export | place (Text Import Options) | yes | | | RTF `.rtf` | place | place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only | | Word `.docx` | place | place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out | -| Word `.doc` | place | no | no | | +| Word `.doc` | place | place (area type with the same formatting as `.docx`, from the style sheet's styles and direct formatting; Word 97 and later) | no | `tests/textimport.rs`, `place/doc.rs`; fuzzed (`text_import_fuzz.rs`); pictures, headers, footers, notes, comments and text boxes are left out with a warning; encrypted and fast-saved documents are refused | | CSS | export (CSS Properties) | — | yes | | | OBJ / USDA / glTF | 3D export | — | no | needs 3D (gap G3) | | Affinity `.af`, `.afdesign`, `.afpub` | no | yes (beyond Illustrator) | no (#665) | 51 pinned files, [affinity-validation.md](affinity-validation.md) | diff --git a/docs/mcp.md b/docs/mcp.md index f40709cb37..d9030f9cfa 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3832,6 +3832,18 @@ more than 16 MiB or nests elements more than 256 deep, and a document with more paragraphs or runs are refused. `file.place` answers `format: "docx"`. +A Word 97-2003 document (a compound file named `.doc`, or one that holds a `WordDocument` stream; an RTF file named +`.doc` is placed as RTF) is placed the same way and keeps the same formatting, taken from the style sheet's default +font, the paragraph style and the character style (and the styles each is based on) and direct formatting. Its main +text is read; table cells are separated by tabs and each row is a paragraph, and a field places as its result. Hidden +and deleted text, field instructions, pictures and embedded objects, headers, footers, notes, comments and text boxes +are left out, and `warnings` names each kind of content left out or changed once (pictures and objects, fields, +tracked changes, tables, and the other stories the document has). Documents saved by Word 6.0 or Word 95, encrypted or +password-protected documents and documents last saved with fast save are refused, and so are a stream larger than +64 MiB, a document with more than 4 MiB of text, 100,000 pieces, 16,384 pages of properties or 100,000 paragraphs or +runs, and one whose structures lie outside their streams. +`file.place` answers `format: "doc"`. + ## PDF presets `pdf.preset.list` lists the built-in presets (`VectorCraft Default`, which preserves editing, then High Quality Print, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 27ebc9383b..0a5187b947 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1093,6 +1093,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - File › Place reads RTF files as area type with their formatting: each run's font, size, bold and italic, underline, strikethrough, caps, superscript or subscript, baseline shift and color, and each paragraph's alignment, indents, space before and after and direction. Table cells are separated by tabs; hidden text, pictures, headers, footers and notes are left out (`file.place`, `crates/engine/src/tests/textimport.rs`). - File › Place reads Word `.docx` documents as area type with the same formatting, taken from the document defaults, the paragraph and character styles (their toggle properties reversing each other) and direct formatting, the theme's fonts included. Table rows are paragraphs with their cells separated by tabs; hidden and deleted text, field instructions, pictures, headers, footers and notes are left out (`file.place`, `crates/engine/src/tests/textimport.rs`). - A Word paragraph justified with a low, medium or high kashida length places justified with Insert Kashidas set to Short, Medium or Long (`file.place`, `crates/engine/src/tests/textimport.rs`). + - File › Place reads Word 97-2003 `.doc` documents as area type with the same formatting, read from the main text's pieces, the style sheet's paragraph and character styles and direct formatting. Table rows are paragraphs with their cells separated by tabs and fields place as their results; hidden and deleted text, pictures, headers, footers, notes, comments and text boxes are left out, and `warnings` names each kind left out or changed. Encrypted documents, documents last saved with fast save and Word 6.0 and Word 95 documents are refused (`file.place`, `crates/engine/src/tests/textimport.rs`). - On the desktop, File › Place reads and decodes files off the UI thread, one at a time, and places each once it is read, with "Placing" in the status bar and the busy spinner until then: the Place dialog's OK, a file dropped on the canvas, a click or drag of the place cursor, and the OK of the PDF, DXF and text import options. The files and thumbnails the place cursor is loaded with are read the same way, and the Place dialog's lines about its files are read on a thread of their own. Files are placed in the order they were started; a file is not placed while a dialog is open or a drag is under way, and a file whose document was closed meanwhile is not placed. `file.place` and `file.place.queue` over MCP and scripts reply as before. - The pixels of a PNG, JPEG, GIF or WebP file that Place decodes to check them are kept in the image store the renderers share, so the canvas's first frame with the placed image draws them without decoding the file again on the UI thread: File › Place, a file dropped on the canvas, a click or drag of the place cursor, `file.place`, and Paste of such an image. A CMYK JPEG is still decoded when it is first drawn (`crates/ui-egui/src/placing.rs`, `crates/render/src/tests.rs`). - A photo whose EXIF orientation turns or flips it (a camera held upright or upside down) is placed and opened upright, as it was taken; the image is stored as it is seen (#4284). From 859b3732c1698faba34c8d6fd96c1f2962b31a1e Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 06:35:39 +0700 Subject: [PATCH 213/260] Fix #4977: Blob Brush and Eraser show their tip's outline at the pointer --- crates/engine/src/tooling.rs | 8 ++- crates/tools/src/context.rs | 3 + crates/tools/src/cursor.rs | 8 +-- crates/tools/src/cursors.toml | 6 +- crates/tools/src/draw2/gesture.rs | 34 +++++++++++- crates/tools/src/draw2/gesture/tests.rs | 73 ++++++++++++++++++++++++- crates/tools/src/lib.rs | 9 ++- crates/ui-egui/src/canvas/cursor.rs | 4 +- crates/ui-egui/src/cursors.rs | 5 ++ docs/ui-parity.md | 4 +- 10 files changed, 139 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 642d9a0349..c54bda1297 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -327,6 +327,7 @@ impl Session { }, screen: view.screen, plane_widget: self.prefs.perspective_widget.show.then_some(self.prefs.perspective_widget.position), + precise_cursors: self.precise_cursors(), }; let tool = &mut self.tool; match crate::guard::catch_panic(|| f(tool.as_mut(), &cx)) { @@ -619,7 +620,12 @@ impl Session { } None => self.with_tool_cx(view, |t, cx| t.cursor(cx, p, mods)), }; - if self.prefs.use_precise_cursors || self.caps_lock { c.precise() } else { c } + if self.precise_cursors() { c.precise() } else { c } + } + + /// General › Use Precise Cursors is on, or Caps Lock is. + fn precise_cursors(&self) -> bool { + self.prefs.use_precise_cursors || self.caps_lock } pub fn tool_options(&self) -> Value { diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 7773762f2e..d6860bb7bc 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -253,6 +253,9 @@ pub struct ToolContext<'a> { pub screen: Option<ScreenFrame>, /// Where the Plane Switching Widget sits (Perspective Grid Options); None while it's hidden. pub plane_widget: Option<distort::perspective::widget::WidgetCorner>, + /// General › Use Precise Cursors, or Caps Lock while it is on: the drawing tools' pointers are + /// crosshairs ([`crate::Cursor::precise`]), and the Blob Brush and the Eraser show no tip outline. + pub precise_cursors: bool, } impl ToolContext<'_> { diff --git a/crates/tools/src/cursor.rs b/crates/tools/src/cursor.rs index b34c323099..f7eb200ead 100644 --- a/crates/tools/src/cursor.rs +++ b/crates/tools/src/cursor.rs @@ -125,9 +125,11 @@ pub enum Cursor { /// the path. Also while a stroke is drawn back near its start, where releasing the mouse button /// closes the path. A crosshair with a ring. PaintbrushClose, - /// The Blob Brush tool. + /// The Blob Brush tool: a dot at the brush's centre, the tool drawing the tip's outline round + /// it on the canvas. BlobBrush, - /// The Eraser tool. + /// The Eraser tool: a dot at the tip's centre, the tool drawing the tip's outline round it on + /// the canvas. Eraser, /// The Smooth tool. Smooth, @@ -305,8 +307,6 @@ impl Cursor { | Cursor::MagicWand | Cursor::Pencil | Cursor::Paintbrush - | Cursor::BlobBrush - | Cursor::Eraser | Cursor::Smooth | Cursor::PathEraser | Cursor::Join diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index 7eaefffc94..80e51276b6 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -583,14 +583,16 @@ look = "The Paintbrush cursor with a ring badge (closing the loop), like PenClos [[cursor]] id = "BlobBrush" group = "Drawing and editing tools" -shown_when = ["The Blob Brush tool: paints filled shapes that merge with touching ones of the same colour. No brush-size outline shows while hovering."] +shown_when = ["The Blob Brush tool: paints filled shapes that merge with touching ones of the same colour. The tool draws the tip's outline (its size, angle and roundness, at the zoom) round the pointer on the canvas, before and while painting; with precise cursors (Caps Lock) the crosshair shows instead."] hotspot = "The brush centre." +look = "Only a small dot at the centre: the tip outline drawn on the canvas is the rest of the pointer." [[cursor]] id = "Eraser" group = "Drawing and editing tools" -shown_when = ["The Eraser tool: a drag erases the area it covers. No size outline shows while hovering."] +shown_when = ["The Eraser tool: a drag erases the area it covers. The tool draws the tip's outline (its size, angle and roundness, at the zoom) round the pointer on the canvas, before and while erasing; with precise cursors (Caps Lock) the crosshair shows instead."] hotspot = "The eraser's centre." +look = "Only a small dot at the centre, as the Blob Brush's: the tip outline drawn on the canvas is the rest of the pointer." [[cursor]] id = "Smooth" diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 045a3304ea..a3c3cd93ec 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -22,9 +22,9 @@ use serde_json::{Value, json}; use vectorcraft_doc::{NodeId, NodeKind}; -use vectorcraft_geom::Point; +use vectorcraft_geom::{Affine, Point}; -use super::{FEEDBACK, blob_area, eraser_area, points_json, polyline}; +use super::{FEEDBACK, blob_area, blob_tip, eraser_area, eraser_tip, points_json, polyline}; use crate::guides::DrawSnap; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -116,6 +116,9 @@ pub struct GestureTool { pub close_within: f64, /// Smart Guides for the Pencil's ends. snap: DrawSnap, + /// Where the Blob Brush's or the Eraser's tip outline shows: the pointer over the canvas, + /// unless Cmd/Ctrl lends a selection tool or Alt the Smooth tool. + tip_at: Option<Point>, } /// The paths a stroke can redraw for selected object `id`: the path itself, or a compound path's @@ -191,6 +194,7 @@ impl GestureTool { edit_within: 12.0, close_within: 15.0, snap: DrawSnap::default(), + tip_at: None, } } @@ -274,6 +278,22 @@ impl GestureTool { start + vectorcraft_geom::constrain_angle_from(p - start, 180.0, self.shift_line.unwrap_or(cx.constrain_angle)) } + /// The Blob Brush's or the Eraser's tip at the pointer, before and while painting: its outline + /// `size` across at its angle and roundness, at the zoom, black on a white halo so it reads on + /// any art. Precise cursors show only the crosshair, and smoothing shows no tip. + fn tip_outline(&self, cx: &ToolContext) -> Vec<Overlay> { + let Some(at) = self.tip_at.filter(|_| !self.smoothing && !cx.precise_cursors) else { return vec![] }; + let tip = if self.id == "blobBrush" { blob_tip(self.angle, self.roundness) } else { eraser_tip(self.angle, self.roundness) }; + let r = self.size / 2.0; + // A tolerance relative to the radius: four arcs at any size or zoom. + let circle = kurbo::Shape::to_path(&kurbo::Circle::new(Point::ORIGIN, r), 0.1 * r.max(1e-6)); + let path = Affine::translate(at.to_vec2()) * tip * circle; + vec![ + Overlay::Path { path: path.clone(), color: [0xff, 0xff, 0xff], width: 3.0, dashed: false }, + Overlay::Path { path, color: [0, 0, 0], width: 1.0, dashed: false }, + ] + } + /// Forget the stroke. fn clear(&mut self) { self.moved = false; @@ -476,6 +496,9 @@ impl Tool for GestureTool { } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> { let p = ev.pos; + if self.varies_size() { + self.tip_at = (!ev.mods.cmd && !self.blob_alt_smooths(ev.mods)).then_some(p); + } match ev.kind { PointerKind::Move if self.snaps() => { self.snap.hover(cx, p, &[], None); @@ -665,8 +688,12 @@ impl Tool for GestureTool { _ => vec![], } } + fn hover_ended(&mut self, _cx: &ToolContext) { + self.tip_at = None; + } fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> { let began = self.began; + self.tip_at = None; // Drags past the last preview are in the stroke kept, too, and with Live curve fitting // off the stroke kept is fitted. let stale = (began && (self.previewed != self.points.len() || !self.live_fit) && self.draws_path() && !self.smoothing) @@ -685,6 +712,7 @@ impl Tool for GestureTool { let mut o = self.snap.guides().to_vec(); // A path being drawn shows itself, except with the Pencil's Live preview off. if !self.active || self.points.len() < 2 || (self.began && self.previews()) { + o.extend(self.tip_outline(cx)); return o; } // A Blob Brush drag that smooths shows the Smooth tool's thin line. @@ -727,6 +755,8 @@ impl Tool for GestureTool { let length = self.points.windows(2).map(|w| w[0].distance(w[1])).sum(); o.push(Overlay::Measure { p: last + vectorcraft_geom::Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("L: {}", cx.len(length)) }); } + // Over the stroke's footprint, which reaches the tip's edge at the pointer. + o.extend(self.tip_outline(cx)); o } fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor { diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 1d6cc8acef..29fe7614fa 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -344,7 +344,8 @@ fn blob_brush_shift_keeps_the_stroke_horizontal_or_vertical() { let (d, _) = doc_with_rect(); let s = Selection::default(); let p = paint(); - let mut cx = cx(&d, &s, &p); + // Precise cursors: no tip outline, only the stroke's own overlay. + let mut cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; let shift = Mods { shift: true, ..Default::default() }; let mut t = GestureTool::new("blobBrush"); let ev = |k, x, y, m| PointerEvent::new(k, x, y).with_mods(m); @@ -1358,7 +1359,8 @@ fn the_eraser_sends_its_tip_and_shows_the_area_it_covers() { let (d, _) = doc_with_rect(); let s = Selection::default(); let p = paint(); - let cx = cx(&d, &s, &p); + // Precise cursors: no tip outline, only the stroke's own overlay. + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; let mut t = GestureTool::new("eraser"); t.set_option("size", &json!(20)); t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0)); @@ -1438,6 +1440,73 @@ fn the_blob_brush_sends_its_tip_and_shows_the_area_it_covers() { assert!(vectorcraft_geom::Shape::bounding_box(path).height() < 0.1, "{o:?}"); } +/// #4977: the Blob Brush and the Eraser show their tip at the pointer before a press and while +/// painting: its outline at its size, angle and roundness, a black line on a white halo, following +/// `[` / `]` and Tool Options at once. It goes when the hover ends, with precise cursors (Caps +/// Lock), while Cmd/Ctrl lends a selection tool and while Alt lends the Blob Brush the Smooth +/// tool. The other gesture tools show none. +#[test] +fn the_blob_brush_and_the_eraser_show_their_tip_at_the_pointer() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let bounds = |t: &GestureTool, cx: &ToolContext| match &t.overlays(cx)[..] { + [Overlay::Path { path: halo, color: [0xff, 0xff, 0xff], width: 3.0, .. }, Overlay::Path { path, color: [0, 0, 0], width: 1.0, .. }] => { + assert_eq!(halo, path); + Some(vectorcraft_geom::Shape::bounding_box(path)) + } + [] => None, + o => panic!("{o:?}"), + }; + let near = |b: Option<vectorcraft_geom::Rect>, want: (f64, f64, f64, f64)| { + let b = b.unwrap_or_else(|| panic!("no tip")); + assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}"); + }; + let hover = |t: &mut GestureTool, cx: &ToolContext, m: Mods| t.pointer(cx, &PointerEvent::new(PointerKind::Move, 100.0, 50.0).with_mods(m)); + for id in ["blobBrush", "eraser"] { + let mut t = GestureTool::new(id); + assert_eq!(bounds(&t, &cx), None, "{id}: nothing before the pointer comes"); + hover(&mut t, &cx, Mods::default()); + near(bounds(&t, &cx), (95.0, 45.0, 105.0, 55.0)); + // `]` grows it at once, without a move; Tool Options too. + t.key(&cx, ToolKey::BracketRight, Mods::default()); + near(bounds(&t, &cx), (94.5, 44.5, 105.5, 55.5)); + t.set_option("size", &json!(20)); + near(bounds(&t, &cx), (90.0, 40.0, 110.0, 60.0)); + // Upright and a quarter as wide: 5 pt across, 20 pt tall. + t.set_option("angle", &json!(90)); + t.set_option("roundness", &json!(25)); + near(bounds(&t, &cx), (97.5, 40.0, 102.5, 60.0)); + // It follows the drag, over the stroke's footprint. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 50.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 200.0, 50.0)); + let o = t.overlays(&cx); + assert!(matches!(&o[o.len() - 2..], [Overlay::Path { width: 3.0, .. }, Overlay::Path { color: [0, 0, 0], width: 1.0, .. }]), "{id}: {o:?}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 200.0, 50.0)); + let precise = ToolContext { precise_cursors: true, ..crate::testutil::cx(&d, &s, &p) }; + assert_eq!(bounds(&t, &precise), None, "{id}: precise cursors show the crosshair alone"); + t.hover_ended(&cx); + assert_eq!(bounds(&t, &cx), None, "{id}: gone with the hover"); + hover(&mut t, &cx, Mods::default()); + assert!(t.deactivate(&cx).is_empty()); + assert_eq!(bounds(&t, &cx), None, "{id}: gone with the tool"); + } + // Alt before a press lends the Blob Brush the Smooth tool, and Cmd/Ctrl either tool a + // selection tool, whose cursors show instead. + let mut t = GestureTool::new("blobBrush"); + hover(&mut t, &cx, Mods { alt: true, ..Default::default() }); + assert_eq!(bounds(&t, &cx), None); + let mut t = GestureTool::new("eraser"); + hover(&mut t, &cx, Mods { cmd: true, ..Default::default() }); + assert_eq!(bounds(&t, &cx), None); + for id in ["pencil", "paintbrush", "smooth", "knife", "pathEraser", "join"] { + let mut t = GestureTool::new(id); + hover(&mut t, &cx, Mods::default()); + assert!(!t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Path { width, .. } if *width == 3.0)), "{id}"); + } +} + #[test] fn smooth_needs_selection_and_brackets_resize() { let (d, _) = doc_with_rect(); diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 29bac11734..67d2f59095 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -507,6 +507,7 @@ pub(crate) mod testutil { construction_angles: guides::construction_angles(guides::DEFAULT_CONSTRUCTION_ANGLES), screen: None, plane_widget: Some(Default::default()), + precise_cursors: false, } } } @@ -553,7 +554,13 @@ mod cursor_tests { ] { assert_eq!(cursor_at(id, &d, away), c, "{id}"); assert_eq!(c.precise(), Cursor::Crosshair, "{id}"); - assert_eq!(c.stand_in(), Some(if id == "mesh" { Cursor::PenAdd } else { Cursor::Crosshair }), "{id}"); + // The Blob Brush's and the Eraser's dot is drawn: their tip outline goes round it. + let stand_in = match id { + "mesh" => Some(Cursor::PenAdd), + "blobBrush" | "eraser" => None, + _ => Some(Cursor::Crosshair), + }; + assert_eq!(c.stand_in(), stand_in, "{id}"); } // Away from a selected path the Pencil shows its new-path cursor, drawn with a star; its // own cursor, for drawing and for a selected path under the pointer, borrows the crosshair. diff --git a/crates/ui-egui/src/canvas/cursor.rs b/crates/ui-egui/src/canvas/cursor.rs index 85ec1622ae..1056e79e7d 100644 --- a/crates/ui-egui/src/canvas/cursor.rs +++ b/crates/ui-egui/src/canvas/cursor.rs @@ -120,13 +120,13 @@ pub(super) fn cursor_icon(c: Cursor) -> egui::CursorIcon { Cursor::Blend | Cursor::BlendObject | Cursor::BlendAnchor | Cursor::ShapeBuilder | Cursor::ShapeBuilderErase => C::Crosshair, Cursor::PencilClose | Cursor::PencilStraight | Cursor::PencilContinue | Cursor::PaintbrushClose => C::Crosshair, Cursor::TypeVertical => C::VerticalText, + // The system has no tip outline to go round: its crosshair aims as well. + Cursor::BlobBrush | Cursor::Eraser => C::Crosshair, // Not drawn yet: the cursor each borrows. Cursor::Lasso | Cursor::MagicWand | Cursor::Pencil | Cursor::Paintbrush - | Cursor::BlobBrush - | Cursor::Eraser | Cursor::Smooth | Cursor::PathEraser | Cursor::Join diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index 55312c3523..c9a0bf9a9a 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -554,6 +554,11 @@ fn glyph(c: Cursor, p: Pos2) -> Option<Vec<Shape>> { double_arrow(ink, p + vec2(15.0, 18.0), vec2(1.0, 0.0)); } Cursor::Crosshair => crosshair(ink, p), + // Only the centre: the tool draws the tip's outline round it, at the zoom. + Cursor::BlobBrush | Cursor::Eraser => { + ink.circle_filled(p, 2.5, HALO); + ink.circle_filled(p, 1.25, INK); + } // The Pencil's crosshair with the Pen's star where the closing ring goes. Cursor::PencilNew => { crosshair(ink, p); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b1a5070568..c1feab7e4b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Layers panel: a blend's spine row, #4820) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Blob Brush and Eraser show their tip's outline at the pointer, #4977) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -87,6 +87,7 @@ tools, never checked side by side) isn't captured row by row. | Anchor Point and Curvature tools' own cursors | done | the caret on the anchor it converts; the pen nib with a curve badge | | Free Transform's Cmd/Ctrl side-shear cursor | done | two arrows passing along the side (ShearH, ShearV), instead of the resize arrow across it | | Cursors of their own for Lasso, Magic Wand, the freehand tools, Shaper, Live Paint Bucket, Measure, Print Tiling, the symbolism tools, vertical type, Scissors (over a segment and away), Mesh and Puppet Warp | partial | each tool returns its own cursor and Use Precise Cursors turns them into the crosshair; until they're drawn they borrow the crosshair, the I-beam, the Pen's add cursor or not-allowed | +| Blob Brush and Eraser: the tip's outline at the pointer | done | before a press and while painting, the outline of the tip (its size, angle and roundness, at the zoom) follows the pointer, black on a white halo, round a small centre dot; `[` / `]` and Tool Options change it at once; precise cursors (Caps Lock) show only the crosshair; it goes when the pointer leaves the canvas, while Cmd/Ctrl lends a selection tool and while Alt lends the Blob Brush the Smooth tool (#4977); `crates/tools/src/draw2/gesture.rs` and its tests | | Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | @@ -388,6 +389,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Blob Brush and Eraser: the tip's outline (size, angle, roundness, at the zoom) follows the pointer before and while painting, around a small centre dot, updating at once with `[` / `]` and Tool Options; precise cursors (Caps Lock) show only the crosshair (#4977); scores and estimates unchanged (estimated) | | 2026-11-01 | minor | Layers panel: an open blend lists its spine as a `<Path>` row below its key objects, and a click selects the blend so Direct Selection edits the spine (#4820); scores and estimates unchanged | | 2026-11-01 | minor | Pen with Cmd/Ctrl held: the lent Selection tool no longer scales the path being drawn by bounding-box handles the canvas hides while its end anchor is selected (a flat path did nothing under a resize pointer); a Cmd drag moves the path instead, and with Direct Selection moves anchors and segments, one undo step each (#4980); scores and estimates unchanged | | 2026-11-01 | minor | Dynamic symbols (#4938): Symbol Options › Symbol Type; per-instance appearance for objects of a dynamic symbol's art; Reset in the Properties panel and the Symbols panel menu; on-canvas Direct Selection of the parts remains | From 8805fa8214bfc71636a64313becfebb1e80c8277 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 16:13:42 -0700 Subject: [PATCH 214/260] Place: Word .doc text with a broken surrogate pair is refused, and fields without a result warn A 16-bit piece holding half of a UTF-16 surrogate pair was placed with U+FFFD in its place; the document is now refused. A pair split between two pieces is decoded as one character. A field with no result (no separator, never ended, or nested past 64) is left out with its own warning, and the warning about fields placed as their results is given only for fields that have one. --- crates/engine/src/cmd/place/doc.rs | 62 ++++++++++++++++----------- crates/engine/src/tests/textimport.rs | 25 ++++++++++- docs/mcp.md | 9 ++-- docs/target-app-parity.md | 2 +- 4 files changed, 67 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/place/doc.rs b/crates/engine/src/cmd/place/doc.rs index 3ae2410bae..41f269c502 100644 --- a/crates/engine/src/cmd/place/doc.rs +++ b/crates/engine/src/cmd/place/doc.rs @@ -10,8 +10,9 @@ //! and ones last saved with fast save (`fComplex`) are refused. //! - Text: the main document's `ccpText` characters, from the pieces the Clx's PlcPcd lists //! (§2.9.38, §2.8.35) in their order, each in 16-bit Unicode or in compressed 8-bit text with the -//! mapping §2.9.73 gives. A paragraph mark (U+000D) ends a paragraph, and so does a page or -//! section break (U+000C) at the end of a paragraph's properties (PapxFkp); a line break +//! mapping §2.9.73 gives; 16-bit text with half of a surrogate pair is refused. A paragraph mark +//! (U+000D) ends a paragraph, and so does a page or section break (U+000C) at the end of a +//! paragraph's properties (PapxFkp); a line break //! (U+000B) starts a new paragraph in the same formatting. A table's cells (cell marks, U+0007) //! are separated by tabs and each row (a table terminating mark) is a paragraph. Tabs are tabs, //! and U+001E and U+001F are the nonbreaking and optional hyphens. Of a field (U+0013, U+0014 and @@ -34,11 +35,11 @@ //! Hidden text, deleted revisions, field instructions, pictures and embedded objects, note and //! comment references and the other stories (footnotes, endnotes, headers, footers, comments and //! text boxes) are left out. The reply's warnings name each kind of content that was left out or -//! changed, once: pictures and objects, fields, the other stories, tracked changes and tables. A -//! stream larger than [`MAX_STREAM`] bytes, a main text longer than [`text::MAX_TEXT`] characters, -//! more than [`MAX_PIECES`] pieces or [`MAX_PAGES`] property pages, and placed type of more than -//! [`MAX_PARAGRAPHS`] paragraphs or [`MAX_RUNS`] runs are refused, and so is a structure that lies -//! outside its stream. +//! changed, once: pictures and objects, fields, fields left out (no result, or nested too deep), the +//! other stories, tracked changes and tables. A stream larger than [`MAX_STREAM`] bytes, a main +//! text longer than [`text::MAX_TEXT`] characters, more than [`MAX_PIECES`] pieces or +//! [`MAX_PAGES`] property pages, and placed type of more than [`MAX_PARAGRAPHS`] paragraphs or +//! [`MAX_RUNS`] runs are refused, and so is a structure that lies outside its stream. use std::io::{Cursor, Read}; @@ -287,27 +288,31 @@ fn main_text(wd: &[u8], pieces: &[Piece], ccp: u32, cmd: &str) -> Result<Vec<Cha return Err(damaged(cmd, "its piece table doesn't cover its text")); } let outside = || damaged(cmd, "a piece of its text lies outside its WordDocument stream"); - let mut out = Vec::with_capacity(ccp as usize); + // Each character position's UTF-16 code unit, file position and byte count, in character + // order; a surrogate pair may be split between two pieces. + let mut units: Vec<(u16, u32, u8)> = Vec::with_capacity(ccp as usize); for p in pieces.iter().take_while(|p| p.cp < ccp) { let n = (p.end.min(ccp) - p.cp) as usize; if p.compressed { let b = bytes_at(wd, p.fc as usize, n).ok_or_else(outside)?; - out.extend(b.iter().zip(p.fc..).map(|(&c, fc)| (compressed(c), fc, 1))); + // Every character compressed text maps to is in the Basic Multilingual Plane. + units.extend(b.iter().zip(p.fc..).map(|(&c, fc)| (u16::try_from(u32::from(compressed(c))).unwrap_or(0xFFFD), fc, 1))); continue; } let b = bytes_at(wd, p.fc as usize, n.checked_mul(2).ok_or_else(outside)?).ok_or_else(outside)?; - let units: Vec<(u16, u32)> = b.as_chunks::<2>().0.iter().zip((p.fc..).step_by(2)).map(|(&u, fc)| (u16::from_le_bytes(u), fc)).collect(); - let mut i = 0; - while let Some(&(u, fc)) = units.get(i) { - let pair = units.get(i + 1).map(|&(low, _)| low).filter(|low| (0xD800..0xDC00).contains(&u) && (0xDC00..0xE000).contains(low)); - let c = match pair { - Some(low) => char::decode_utf16([u, low]).next().and_then(|c| c.ok()), - None => char::from_u32(u32::from(u)), - }; - let width = if pair.is_some() { 4 } else { 2 }; - out.push((c.unwrap_or(char::REPLACEMENT_CHARACTER), fc, width)); - i += usize::from(width / 2); - } + units.extend(b.as_chunks::<2>().0.iter().zip((p.fc..).step_by(2)).map(|(&u, fc)| (u16::from_le_bytes(u), fc, 2))); + } + let mut out = Vec::with_capacity(units.len()); + let mut i = 0; + while let Some(&(u, fc, width)) = units.get(i) { + let low = units.get(i + 1).map(|&(low, _, w)| (low, w)).filter(|(low, _)| (0xD800..0xDC00).contains(&u) && (0xDC00..0xE000).contains(low)); + let c = match low { + Some((low, _)) => char::decode_utf16([u, low]).next().and_then(|c| c.ok()), + None => char::from_u32(u32::from(u)), + }; + let c = c.ok_or_else(|| damaged(cmd, "its text holds half of a UTF-16 surrogate pair"))?; + out.push((c, fc, low.map_or(width, |(_, w)| width + w))); + i += if low.is_some() { 2 } else { 1 }; } Ok(out) } @@ -802,7 +807,10 @@ impl Para { #[derive(Clone, Copy, Default)] struct Seen { pictures: bool, + /// Fields with a result. fields: bool, + /// Fields with no result, or nested past [`MAX_FIELDS`]. + unread_fields: bool, revisions: bool, tables: bool, } @@ -931,10 +939,10 @@ impl<'a> Reader<'a> { } match c { '\u{13}' => { - self.seen.fields = true; if self.fields.len() < MAX_FIELDS && self.field_overflow == 0 { self.fields.push(true); } else { + self.seen.unread_fields = true; self.field_overflow += 1; } return; @@ -942,14 +950,16 @@ impl<'a> Reader<'a> { '\u{14}' if self.field_overflow == 0 => { if let Some(instructions) = self.fields.last_mut() { *instructions = false; + self.seen.fields = true; } return; } '\u{15}' => { if self.field_overflow > 0 { self.field_overflow -= 1; - } else { - self.fields.pop(); + } else if self.fields.pop() == Some(true) { + // A field that ends without a separator has no result. + self.seen.unread_fields = true; } return; } @@ -1052,6 +1062,10 @@ impl<'a> Reader<'a> { if self.seen.fields { out.push("the Word document's fields were placed as the text of their results".to_string()); } + // A field still in its instructions when the text ends has no result either. + if self.seen.unread_fields || self.fields.contains(&true) { + out.push("the Word document's fields without a result that could be read were left out".to_string()); + } if self.seen.revisions { out.push("the Word document's tracked changes were accepted: deleted text was left out and inserted text kept".to_string()); } diff --git a/crates/engine/src/tests/textimport.rs b/crates/engine/src/tests/textimport.rs index 4091191613..b8936d010b 100644 --- a/crates/engine/src/tests/textimport.rs +++ b/crates/engine/src/tests/textimport.rs @@ -547,7 +547,14 @@ impl Word97 { c => u8::try_from(u32::from(c)).unwrap(), })); } else { - wd.extend(text.encode_utf16().flat_map(u16::to_le_bytes)); + // U+FFFF and U+FFFE stand for the high surrogate 0xD800 and the low surrogate 0xDE00 + // on their own. + let unit = |u| match u { + 0xFFFF => 0xD800, + 0xFFFE => 0xDE00, + u => u, + }; + wd.extend(text.encode_utf16().map(unit).flat_map(u16::to_le_bytes)); } } // Each character's file position and size, in character order. @@ -814,9 +821,23 @@ fn malformed_doc_fails_cleanly() { assert!(e.contains("piece table is damaged"), "{e}"); let e = place(&mut s, "a.doc", &Word97 { pieces: vec![("\r\r", true)], ..Word97::default() }.build()).unwrap_err(); assert!(e.contains("no text to place"), "{e}"); + // 16-bit text with half of a surrogate pair is refused rather than placed with a stand-in. + let e = place(&mut s, "a.doc", &Word97 { pieces: vec![("bad \u{FFFF} text\r", false)], ..Word97::default() }.build()).unwrap_err(); + assert!(e.contains("half of a UTF-16 surrogate pair"), "{e}"); + // A surrogate pair split between two pieces is one character. + let r = place(&mut s, "a.doc", &Word97 { pieces: vec![("x\u{FFFF}", false), ("\u{FFFE}y\r", false)], ..Word97::default() }.build()).unwrap(); + assert_eq!(placed(&s, &r).0, "x\u{10200}y"); + // A field that ends without a result is left out, with its own warning. + let r = place(&mut s, "a.doc", &Word97 { pieces: vec![("a\u{13} PAGE \u{15}b\r", true)], ..Word97::default() }.build()).unwrap(); + assert_eq!(placed(&s, &r).0, "ab"); + assert_eq!(r["warnings"], json!(["the Word document's fields without a result that could be read were left out"])); + // So is a field that never ends, with the text after it. + let r = place(&mut s, "a.doc", &Word97 { pieces: vec![("a\rb\u{13} PAGE c\r", true)], ..Word97::default() }.build()).unwrap(); + assert_eq!(placed(&s, &r).0, "a\nb"); + assert_eq!(r["warnings"], json!(["the Word document's fields without a result that could be read were left out"])); let r = place(&mut s, "a.doc", &words().build()).unwrap(); assert_eq!(placed(&s, &r).0, "words"); - assert_eq!(s.doc().unwrap().history.undo.len(), 2, "failed places leave no undo step"); + assert_eq!(s.doc().unwrap().history.undo.len(), 5, "failed places leave no undo step"); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index d9030f9cfa..5905172d33 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3838,10 +3838,11 @@ font, the paragraph style and the character style (and the styles each is based text is read; table cells are separated by tabs and each row is a paragraph, and a field places as its result. Hidden and deleted text, field instructions, pictures and embedded objects, headers, footers, notes, comments and text boxes are left out, and `warnings` names each kind of content left out or changed once (pictures and objects, fields, -tracked changes, tables, and the other stories the document has). Documents saved by Word 6.0 or Word 95, encrypted or -password-protected documents and documents last saved with fast save are refused, and so are a stream larger than -64 MiB, a document with more than 4 MiB of text, 100,000 pieces, 16,384 pages of properties or 100,000 paragraphs or -runs, and one whose structures lie outside their streams. +tracked changes, tables, and the other stories the document has); a field with no result is left out with its own +warning. Documents saved by Word 6.0 or Word 95, encrypted or password-protected documents and documents last saved with +fast save are refused, and so are a stream larger than 64 MiB, a document with more than 4 MiB of text, 100,000 pieces, +16,384 pages of properties or 100,000 paragraphs or runs, one whose 16-bit text holds half of a surrogate pair, and one +whose structures lie outside their streams. `file.place` answers `format: "doc"`. ## PDF presets diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0a5187b947..69b8bd6042 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1093,7 +1093,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - File › Place reads RTF files as area type with their formatting: each run's font, size, bold and italic, underline, strikethrough, caps, superscript or subscript, baseline shift and color, and each paragraph's alignment, indents, space before and after and direction. Table cells are separated by tabs; hidden text, pictures, headers, footers and notes are left out (`file.place`, `crates/engine/src/tests/textimport.rs`). - File › Place reads Word `.docx` documents as area type with the same formatting, taken from the document defaults, the paragraph and character styles (their toggle properties reversing each other) and direct formatting, the theme's fonts included. Table rows are paragraphs with their cells separated by tabs; hidden and deleted text, field instructions, pictures, headers, footers and notes are left out (`file.place`, `crates/engine/src/tests/textimport.rs`). - A Word paragraph justified with a low, medium or high kashida length places justified with Insert Kashidas set to Short, Medium or Long (`file.place`, `crates/engine/src/tests/textimport.rs`). - - File › Place reads Word 97-2003 `.doc` documents as area type with the same formatting, read from the main text's pieces, the style sheet's paragraph and character styles and direct formatting. Table rows are paragraphs with their cells separated by tabs and fields place as their results; hidden and deleted text, pictures, headers, footers, notes, comments and text boxes are left out, and `warnings` names each kind left out or changed. Encrypted documents, documents last saved with fast save and Word 6.0 and Word 95 documents are refused (`file.place`, `crates/engine/src/tests/textimport.rs`). + - File › Place reads Word 97-2003 `.doc` documents as area type with the same formatting, read from the main text's pieces, the style sheet's paragraph and character styles and direct formatting. Table rows are paragraphs with their cells separated by tabs and fields place as their results; fields without a result, hidden and deleted text, pictures, headers, footers, notes, comments and text boxes are left out, and `warnings` names each kind left out or changed. Encrypted documents, documents last saved with fast save and Word 6.0 and Word 95 documents are refused (`file.place`, `crates/engine/src/tests/textimport.rs`). - On the desktop, File › Place reads and decodes files off the UI thread, one at a time, and places each once it is read, with "Placing" in the status bar and the busy spinner until then: the Place dialog's OK, a file dropped on the canvas, a click or drag of the place cursor, and the OK of the PDF, DXF and text import options. The files and thumbnails the place cursor is loaded with are read the same way, and the Place dialog's lines about its files are read on a thread of their own. Files are placed in the order they were started; a file is not placed while a dialog is open or a drag is under way, and a file whose document was closed meanwhile is not placed. `file.place` and `file.place.queue` over MCP and scripts reply as before. - The pixels of a PNG, JPEG, GIF or WebP file that Place decodes to check them are kept in the image store the renderers share, so the canvas's first frame with the placed image draws them without decoding the file again on the UI thread: File › Place, a file dropped on the canvas, a click or drag of the place cursor, `file.place`, and Paste of such an image. A CMYK JPEG is still decoded when it is first drawn (`crates/ui-egui/src/placing.rs`, `crates/render/src/tests.rs`). - A photo whose EXIF orientation turns or flips it (a camera held upright or upside down) is placed and opened upright, as it was taken; the image is stored as it is seen (#4284). From 13628274b72a3161123db493f867547e86f7dbc2 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 15:41:31 -0700 Subject: [PATCH 215/260] OpenType: the panel turns Stylistic and Titling Alternates on and off, and offers Proportional Lining figures The OpenType panel gains Stylistic Alternates (salt) and Titling Alternates (titl) checkboxes after Swash. The Figure menu lists Default Figure, Tabular Lining, Proportional Lining, Proportional Oldstyle and Tabular Oldstyle. Proportional Lining sets pnum and lnum and turns tnum and onum off; Tabular Lining keeps lnum, Proportional Oldstyle keeps pnum, and Default Figure and Tabular Oldstyle turn both off. Every catalog has rows for the three new labels. --- crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/bs.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/panels/opentype.rs | 197 ++++++++++++++++++++++---- docs/target-app-parity.md | 1 + 28 files changed, 252 insertions(+), 24 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index cb018daf7f..9c34a3bff9 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2416,6 +2416,7 @@ digits Tamil Тамилски digits Telugu Телугу digits Kannada Каннада digits Malayalam Малаялам + Proportional Lining Пропорционални подравнени цифри Proportional Oldstyle Пропорционални стари цифри Pucker & Bloat… Свиване и раздуване… Pucker Tool Инструмент „Свиване“ @@ -3203,6 +3204,7 @@ digits Malayalam Малаялам Swap Fill and Stroke (Shift+X) Размяна на запълването и щриха (Shift+X) Swap start and end arrowheads Размяна на началната и крайната стрелка Swap the selected object for the file, keeping its place and transform Замяна на избрания обект с файла, като се запазват мястото и трансформациите му + Stylistic Alternates Стилистични алтернативи Swash Декоративен елемент Swatch Conflict Конфликт на образци Swatch Conflicts Конфликти на образци @@ -3272,6 +3274,7 @@ digits Malayalam Малаялам Tabs Табулатори Tabular Lining Таблични подравнени цифри Tabular Oldstyle Таблични стари цифри + Titling Alternates Алтернативи за заглавия Target Цел Target Contents Целево съдържание Target: Цел: diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index aad1ce608a..d79eeeccaf 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1780,13 +1780,16 @@ digits Malayalam Malajalam Fractions Razlomci Ligatures are off while the text is tracked. Ligature su isključene dok tekst ima razmak slova. Ordinals Redni brojevi + Proportional Lining Proporcionalne brojke Proportional Oldstyle Proporcionalne stare brojke Reset OpenType Features Vrati OpenType mogućnosti na početno Select text to set its OpenType features. Odaberite tekst da postavite njegove OpenType mogućnosti. Standard Ligatures Standardne ligature + Stylistic Alternates Stilske alternative Swash Ukrasni potez Tabular Lining Tabelarne brojke Tabular Oldstyle Tabelarne stare brojke + Titling Alternates Alternative za naslove Every-line Composer Slagač svih redova First-line Left Indent Lijeva uvlaka prvog reda Hyphenation… Rastavljanje riječi… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c874a4e36e..34d1de77f5 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3098,6 +3098,7 @@ digits Malayalam Malaiàlam Proof Setup Configuració de prova Properties Propietats Proportional Metrics Mètriques proporcionals + Proportional Lining Xifres proporcionals alineades Proportional Oldstyle Oldstyle proporcional PRs PRs Public Domain Domini públic @@ -4118,6 +4119,7 @@ digits Malayalam Malaiàlam Swap Fill and Stroke (Shift+X) Intercanvia el farciment i el traç (Maj+X) Swap start and end arrowheads Intercanvia les puntes de fletxa inicial i final Swap the selected object for the file, keeping its place and transform Substitueix l’objecte seleccionat pel fitxer, mantenint-ne la posició i la transformació + Stylistic Alternates Alternatives estilístiques Swash Volada Swatch Conflict Conflicte de mostres Swatch Conflicts Conflictes de mostres @@ -4175,6 +4177,7 @@ digits Malayalam Malaiàlam Tabs Tabulacions Tabular Lining Xifres tabulars alineades Tabular Oldstyle Xifres tabulars antigues + Titling Alternates Alternatives de titulars Tag Etiqueta Tag (open) Etiqueta (oberta) Taper Afusament diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 1d18695532..fc059b4408 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1806,13 +1806,16 @@ digits Malayalam Malajálamské Fractions Zlomky Ligatures are off while the text is tracked. Ligatury jsou vypnuté, když má text prostrkání. Ordinals Řadové číslovky + Proportional Lining Proporcionální verzálkové Proportional Oldstyle Proporcionální minuskové Reset OpenType Features Obnovit funkce OpenType Select text to set its OpenType features. Vyberte text, abyste mohli nastavit jeho funkce OpenType. Standard Ligatures Standardní ligatury + Stylistic Alternates Stylistické alternativy Swash Ozdobné tvary Tabular Lining Tabulkové verzálkové Tabular Oldstyle Tabulkové minuskové + Titling Alternates Titulkové alternativy Every-line Composer Sazba všech řádků First-line Left Indent Odsazení prvního řádku zleva Hyphenation… Dělení slov… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 399c067ad0..690b2699b0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1622,13 +1622,16 @@ digits Malayalam Malayalam Fractions Brøker Ligatures are off while the text is tracked. Ligaturer er slået fra, mens der er sporing på teksten. Ordinals Ordenstal + Proportional Lining Proportionale versalcifre Proportional Oldstyle Proportionale mediævalcifre Reset OpenType Features Nulstil OpenType-funktioner Select text to set its OpenType features. Markér tekst for at angive dens OpenType-funktioner. Standard Ligatures Standardligaturer + Stylistic Alternates Stilistiske alternativer Swash Sving Tabular Lining Tabulære versalcifre Tabular Oldstyle Tabulære mediævalcifre + Titling Alternates Titelalternativer Every-line Composer Hverlinjesætter First-line Left Indent Venstre indrykning af første linje Hyphenation… Orddeling… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 80adbe1171..c6bf0ad760 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2435,6 +2435,7 @@ digits Tamil Tamil digits Telugu Telugu digits Kannada Kannada digits Malayalam Malayalam + Proportional Lining Proportionale Versalziffern Proportional Oldstyle Proportionale Mediävalziffern Pucker & Bloat… Zusammenziehen und aufblasen… Pucker Tool Zusammenziehen-Werkzeug @@ -3241,6 +3242,7 @@ effect Points Punkte Swap Fill and Stroke (Shift+X) Fläche und Kontur vertauschen (Shift+X) Swap start and end arrowheads Pfeilspitzen an Anfang und Ende vertauschen Swap the selected object for the file, keeping its place and transform Das ausgewählte Objekt durch die Datei ersetzen; Position und Transformation bleiben erhalten + Stylistic Alternates Stilistische Varianten Swash Schwungschrift Swatch Conflict Farbfeldkonflikt Swatch Conflicts Farbfeldkonflikte @@ -3293,6 +3295,7 @@ effect Points Punkte Tabs Tabulatoren Tabular Lining Tabellarische Versalziffern Tabular Oldstyle Tabellarische Mediävalziffern + Titling Alternates Titelschriftvarianten Target Ziel Target Contents Inhalt als Ziel auswählen Target: Ziel: diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 535bc98be6..f5c0ccedc0 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1954,6 +1954,7 @@ font-technology Variable Μεταβλητές Subtract Αφαίρεση Superscript Εκθέτης Superscript: Εκθέτης: + Stylistic Alternates Εναλλακτικοί χαρακτήρες στυλ Swash Διακοσμητικά τελειώματα Swatches Δείγματα χρωμάτων New Group Νέα ομάδα @@ -3074,6 +3075,7 @@ digits Tamil Ταμιλικά digits Telugu Τελούγκου digits Kannada Κανάντα digits Malayalam Μαλαγιάλαμ + Proportional Lining Ισοϋψείς αναλογικοί αριθμοί Proportional Oldstyle Αναλογικοί παλαιοτυπικοί αριθμοί Pucker & Bloat… Συρρίκνωση και διόγκωση… Pucker Tool Συρρίκνωση (Pucker Tool) @@ -3694,6 +3696,7 @@ digits Malayalam Μαλαγιάλαμ Tabs Στηλοθέτες Tabular Lining Ισοϋψείς αριθμοί σταθερού πλάτους Tabular Oldstyle Παλαιοτυπικοί αριθμοί σταθερού πλάτους + Titling Alternates Εναλλακτικοί χαρακτήρες τίτλων Target Στόχος Target Contents Περιεχόμενα στόχου Tate-chu-yoko Tate-chu-yoko diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5a56e70b01..8587501613 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2473,6 +2473,7 @@ digits Tamil Tamil digits Telugu Telugu digits Kannada Canarés digits Malayalam Malayálam + Proportional Lining Proporcionales de caja alta Proportional Oldstyle Estilo antiguo proporcional Pucker & Bloat… Fruncir y engordar… Pucker Tool Herramienta Fruncir @@ -3275,6 +3276,7 @@ digits Malayalam Malayálam Swap Fill and Stroke (Shift+X) Intercambiar relleno y trazo (Shift+X) Swap start and end arrowheads Intercambiar puntas de flecha inicial y final Swap the selected object for the file, keeping its place and transform Sustituir el objeto seleccionado por el archivo, conservando su posición y transformación + Stylistic Alternates Alternativas estilísticas Swash Decorativa Swatch Conflict Conflicto de muestras Swatch Conflicts Conflictos de muestras @@ -3344,6 +3346,7 @@ digits Malayalam Malayálam Tabs Tabulaciones Tabular Lining Tabulares de caja alta Tabular Oldstyle Tabulares de estilo antiguo + Titling Alternates Alternativas de titulares Target Destino Target Contents Contenido de destino Target: Destino: diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 2a4564b938..f1aa49a30a 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1767,13 +1767,16 @@ digits Malayalam Malajalam Fractions Murtoluvut Ligatures are off while the text is tracked. Ligatuurit eivät ole käytössä, kun tekstin merkkiväliä on muutettu. Ordinals Järjestysluvut + Proportional Lining Suhteelliset numerot Proportional Oldstyle Suhteelliset vanhanaikaiset numerot Reset OpenType Features Palauta OpenType-ominaisuudet Select text to set its OpenType features. Valitse teksti, jonka OpenType-ominaisuudet haluat asettaa. Standard Ligatures Vakioligatuurit + Stylistic Alternates Tyylivaihtoehdot Swash Koukerot Tabular Lining Taulukkonumerot Tabular Oldstyle Vanhanaikaiset taulukkonumerot + Titling Alternates Otsikkovaihtoehdot Every-line Composer Kaikkien rivien asettelu First-line Left Indent Ensimmäisen rivin vasen sisennys Hyphenation… Tavutus… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index a7a46033a8..fc18c34aac 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2471,6 +2471,7 @@ digits Tamil Tamoul digits Telugu Télougou digits Kannada Kannada digits Malayalam Malayalam + Proportional Lining Chiffres proportionnels alignés Proportional Oldstyle Elzévirien proportionnel Pucker & Bloat… Contraction et dilatation… Pucker Tool Outil Contraction @@ -3273,6 +3274,7 @@ digits Malayalam Malayalam Swap Fill and Stroke (Shift+X) Permuter le fond et le contour (Maj+X) Swap start and end arrowheads Permuter les pointes de flèche de début et de fin Swap the selected object for the file, keeping its place and transform Remplacer l’objet sélectionné par le fichier, en conservant sa position et sa transformation + Stylistic Alternates Variantes stylistiques Swash Lettres ornées Swatch Conflict Conflit de nuances Swatch Conflicts Conflits de nuances @@ -3342,6 +3344,7 @@ digits Malayalam Malayalam Tabs Tabulations Tabular Lining Chiffres tabulaires alignés Tabular Oldstyle Chiffres tabulaires elzéviriens + Titling Alternates Variantes de titrage Target Cible Target Contents Contenu de la cible Target: Cible : diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index eec2461130..9935eaa4af 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3001,6 +3001,7 @@ mark-style Japanese Japán Proof Setup Színpróba beállítása Properties Tulajdonságok Proportional Metrics Arányos metrika + Proportional Lining Arányos modern Proportional Oldstyle Arányos régies Public Domain Közkincs Pucker Összehúzás @@ -3944,6 +3945,7 @@ mark-style Japanese Japán Swap Fill and Stroke (Shift+X) Kitöltés és körvonal cseréje (Shift+X) Swap start and end arrowheads Kezdő és záró nyílhegy cseréje Swap the selected object for the file, keeping its place and transform A kijelölt objektum cseréje a fájlra, a helye és az átalakítása megtartásával + Stylistic Alternates Stilisztikai változatok Swash Cifra változatok Swatch Conflict Színminta-ütközés Swatch Conflicts Színminta-ütközések @@ -3989,6 +3991,7 @@ mark-style Japanese Japán Tabs Tabulátorok Tabular Lining Táblázatos modern Tabular Oldstyle Táblázatos régies + Titling Alternates Címváltozatok Tag Címke Tag (open) Címke (nyitott) Target Célzás diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e5904b11c6..4ecabcc939 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1622,13 +1622,16 @@ digits Malayalam Malayalam Fractions Pecahan Ligatures are off while the text is tracked. Ligatur nonaktif saat teks diberi tracking. Ordinals Ordinal + Proportional Lining Lining proporsional Proportional Oldstyle Oldstyle proporsional Reset OpenType Features Setel ulang fitur OpenType Select text to set its OpenType features. Pilih teks untuk mengatur fitur OpenType-nya. Standard Ligatures Ligatur standar + Stylistic Alternates Alternatif gaya Swash Swash Tabular Lining Lining tabular Tabular Oldstyle Oldstyle tabular + Titling Alternates Alternatif judul Every-line Composer Komposer tiap baris First-line Left Indent Indentasi kiri baris pertama Hyphenation… Pemenggalan kata… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index bf53ef52dc..7c82ec424f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2504,6 +2504,7 @@ digits Tamil Tamil digits Telugu Telugu digits Kannada Kannada digits Malayalam Malayalam + Proportional Lining Proporzionali allineati Proportional Oldstyle Proporzionali stile antico Pucker & Bloat… Contrai e gonfia… Pucker Tool Strumento Contrai @@ -3309,6 +3310,7 @@ digits Malayalam Malayalam Swap Fill and Stroke (Shift+X) Inverti riempimento e traccia (Shift+X) Swap start and end arrowheads Inverti punte di freccia iniziale e finale Swap the selected object for the file, keeping its place and transform Sostituisci l'oggetto selezionato con il file, mantenendone posizione e trasformazione + Stylistic Alternates Alternative stilistiche Swash Ornamentale Swatch Conflict Conflitto campioni Swatch Conflicts Conflitti campioni @@ -3378,6 +3380,7 @@ digits Malayalam Malayalam Tabs Tabulazioni Tabular Lining Tabulari allineati Tabular Oldstyle Tabulari stile antico + Titling Alternates Alternative per titoli Target Destinazione Target Contents Contenuto destinazione Target: Destinazione: diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 718561e266..4d97ac7425 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3041,6 +3041,7 @@ mark-style Japanese 日本式 Superscript: 上付き文字: Swap Fill and Stroke 塗りと線を入れ替え Swap start and end arrowheads 始点と終点の矢印を入れ替え + Stylistic Alternates スタイル代替字 Swash スワッシュ Swatch Conflict スウォッチの競合 Swatch Conflicts スウォッチの競合 @@ -3615,6 +3616,7 @@ file-filter Templates テンプレート Preset {} プリセット {} Preview in Browser needs the desktop app (the web downloads files instead) ブラウザーでプレビューにはデスクトップアプリが必要です (Web アプリではファイルがダウンロードされます) Print presets プリントプリセット + Proportional Lining プロポーショナルライニング Proportional Oldstyle プロポーショナルオールドスタイル Punctuation 句読点 Radius 1 半径 1 @@ -3696,6 +3698,7 @@ file-filter Templates テンプレート System Layout システムレイアウト Tabular Lining 等幅ライニング Tabular Oldstyle 等幅オールドスタイル + Titling Alternates タイトル代替字 Tate-chu-yoko 縦中横 Temperature 色温度 Template テンプレート diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9091ca5099..b10c28a807 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1525,13 +1525,16 @@ digits Malayalam მალაიალამური Fractions წილადები Ligatures are off while the text is tracked. ტექსტზე ტრეკინგის დროს ლიგატურები გამორთულია. Ordinals რიგობითი რიცხვები + Proportional Lining პროპორციული ხაზოვანი Proportional Oldstyle პროპორციული ძველებური Reset OpenType Features OpenType შესაძლებლობების ჩამოყრა Select text to set its OpenType features. OpenType შესაძლებლობების დასაყენებლად მონიშნეთ ტექსტი. Standard Ligatures სტანდარტული ლიგატურები + Stylistic Alternates სტილისტური ალტერნატივები Swash მოხატული ასოები (swash) Tabular Lining ცხრილური ხაზოვანი Tabular Oldstyle ცხრილური ძველებური + Titling Alternates სათაურის ალტერნატივები Every-line Composer აბზაცის მიხედვით აწყობა First-line Left Indent პირველი სტრიქონის მარცხენა შეწევა Hyphenation… სიტყვების გადატანა… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index cdf3b79378..86f82fad40 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3030,6 +3030,7 @@ mark-style Japanese 일본식 Superscript: 위 첨자: Swap Fill and Stroke 칠과 선 바꾸기 Swap start and end arrowheads 시작과 끝 화살촉 바꾸기 + Stylistic Alternates 스타일 대체 글자 Swash 스워시 Swatch Conflict 견본 충돌 Swatch Conflicts 견본 충돌 @@ -3603,6 +3604,7 @@ file-filter Templates 템플릿 Preset {} 프리셋 {} Preview in Browser needs the desktop app (the web downloads files instead) 브라우저에서 미리 보기는 데스크톱 앱이 필요합니다(웹에서는 파일이 다운로드됩니다) Print presets 인쇄 프리셋 + Proportional Lining 비례 라이닝 Proportional Oldstyle 비례 올드스타일 Punctuation 문장 부호 Radius 1 반지름 1 @@ -3684,6 +3686,7 @@ file-filter Templates 템플릿 System Layout 시스템 레이아웃 Tabular Lining 고정폭 라이닝 Tabular Oldstyle 고정폭 올드스타일 + Titling Alternates 제목 대체 글자 Tate-chu-yoko 다테추요코 Temperature 색온도 Template 템플릿 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 1bd09afd91..39d58c856a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1636,13 +1636,16 @@ digits Malayalam Malayalam Fractions Breuken Ligatures are off while the text is tracked. Ligaturen staan uit terwijl de tekst wordt gespatieerd. Ordinals Rangtelwoorden + Proportional Lining Proportionele lining Proportional Oldstyle Proportionele oldstyle Reset OpenType Features OpenType-functies herstellen Select text to set its OpenType features. Selecteer tekst om de OpenType-functies in te stellen. Standard Ligatures Standaardligaturen + Stylistic Alternates Stilistische alternatieven Swash Swash Tabular Lining Tabulaire lining Tabular Oldstyle Tabulaire oldstyle + Titling Alternates Titelalternatieven Every-line Composer Compositie per alinea First-line Left Indent Eerste regel links inspringen Hyphenation… Afbreken… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 9e68943421..6b6141546f 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1725,13 +1725,16 @@ digits Malayalam Malajalam Fractions Ułamki Ligatures are off while the text is tracked. Ligatury są wyłączone, gdy tekst ma zmienione światło. Ordinals Liczebniki porządkowe + Proportional Lining Proporcjonalne nowoczesne Proportional Oldstyle Proporcjonalne nautyczne Reset OpenType Features Resetuj funkcje OpenType Select text to set its OpenType features. Zaznacz tekst, aby ustawić jego funkcje OpenType. Standard Ligatures Ligatury standardowe + Stylistic Alternates Alternatywy stylistyczne Swash Ozdobniki Tabular Lining Tabelaryczne nowoczesne Tabular Oldstyle Tabelaryczne nautyczne + Titling Alternates Alternatywy tytułowe Every-line Composer Kompozytor wielowierszowy First-line Left Indent Wcięcie pierwszego wiersza Hyphenation… Dzielenie wyrazów… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 53bee8c061..9c79f3edb0 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2702,6 +2702,7 @@ digits Malayalam Malaiala Superscript: Sobrescrito: Swap Fill and Stroke Trocar Preenchimento e Traçado Swap start and end arrowheads Trocar pontas de seta inicial e final + Stylistic Alternates Variantes Estilísticas Swash Ornamento Swatch Conflict Conflito de Amostra Swatch Conflicts Conflitos de Amostra @@ -4619,6 +4620,7 @@ axis Both Ambos Preset {} Predefinido {} Preview in Browser needs the desktop app (the web downloads files instead) A visualização no navegador exige o aplicativo para desktop (na web, os arquivos são baixados) Print presets Predefinidos de impressão + Proportional Lining Alinhado Proporcional Proportional Oldstyle Antigo Proporcional Punctuation Pontuação Radius 1 Raio 1 @@ -4722,6 +4724,7 @@ axis Both Ambos System Layout Layout do Sistema Tabular Lining Alinhado Tabular Tabular Oldstyle Antigo Tabular + Titling Alternates Variantes de Titulação Tate-chu-yoko Tate-chu-yoko Temperature Temperatura Templates Modelos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 93b2543dee..de3223891d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2500,6 +2500,7 @@ digits Tamil Тамильские digits Telugu Телугу digits Kannada Каннада digits Malayalam Малаялам + Proportional Lining Пропорциональные цифры Proportional Oldstyle Пропорциональные старого стиля Pucker & Bloat… Сморщивание и раздувание… Pucker Tool Инструмент «Сморщивание» @@ -3305,6 +3306,7 @@ digits Malayalam Малаялам Swap Fill and Stroke (Shift+X) Поменять заливку и обводку (Shift+X) Swap start and end arrowheads Поменять начальную и конечную стрелки Swap the selected object for the file, keeping its place and transform Заменить выделенный объект файлом, сохранив его положение и преобразование + Stylistic Alternates Стилистические альтернативы Swash Росчерк Swatch Conflict Конфликт образцов Swatch Conflicts Конфликты образцов @@ -3374,6 +3376,7 @@ digits Malayalam Малаялам Tabs Табуляции Tabular Lining Табличные цифры Tabular Oldstyle Табличные старого стиля + Titling Alternates Альтернативы для заголовков Target Объект Target Contents Содержимое объекта Target: Объект: diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index ef3a7b65cd..61f1c1f987 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2416,6 +2416,7 @@ digits Tamil Tamil digits Telugu Telugu digits Kannada Kannada digits Malayalam Malayalam + Proportional Lining Proportionella versalsiffror Proportional Oldstyle Proportionella medievalsiffror Pucker & Bloat… Dra ihop och svullna… Pucker Tool Verktyget Dra ihop @@ -3203,6 +3204,7 @@ digits Malayalam Malayalam Swap Fill and Stroke (Shift+X) Byt plats på fyllning och kontur (Shift+X) Swap start and end arrowheads Byt plats på start- och slutpilspets Swap the selected object for the file, keeping its place and transform Ersätt det markerade objektet med filen och behåll dess placering och transformering + Stylistic Alternates Stilistiska alternativ Swash Swash Swatch Conflict Färgrutekonflikt Swatch Conflicts Färgrutekonflikter @@ -3272,6 +3274,7 @@ digits Malayalam Malayalam Tabs Tabbstopp Tabular Lining Tabellsiffror, versala Tabular Oldstyle Medievalsiffror i tabellbredd + Titling Alternates Rubrikalternativ Target Mål Target Contents Målets innehåll Target: Mål: diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 85abd24cca..938c519152 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2293,6 +2293,7 @@ digits Tamil Tamilce digits Telugu Telugu digits Kannada Kannada digits Malayalam Malayalam + Proportional Lining Orantılı Astar Proportional Oldstyle Orantılı Eski Stil Pucker & Bloat… Büzüşme ve Şişkinlik… Pucker Tool Büzme Aracı @@ -3099,6 +3100,7 @@ digits Malayalam Malayalam Swap Fill and Stroke (Shift+X) Dolgu ve Konturu Değiştir (Shift+X) Swap start and end arrowheads Başlangıç ve bitiş ok uçlarını değiştirin Swap the selected object for the file, keeping its place and transform Seçilen nesneyi, yerini koruyarak dosyayla değiştirin ve dönüştürün + Stylistic Alternates Stilistik Alternatifler Swash çalkalama Swatch Conflict Renk Örneği Çatışması Swatch Conflicts Renk Örneği Çatışmaları @@ -3168,6 +3170,7 @@ digits Malayalam Malayalam Tabs Sekmeler Tabular Lining Sekmeli Astar Tabular Oldstyle Tablolu Eski Stil + Titling Alternates Başlık Alternatifleri Target Hedef Target Contents Hedef İçerikler Target: Hedef: diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 686d8c4a15..d9d01c69d8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2496,6 +2496,7 @@ digits Tamil Тамільські digits Telugu Телугу digits Kannada Каннада digits Malayalam Малаялам + Proportional Lining Пропорційні цифри Proportional Oldstyle Пропорційні цифри старого стилю Pucker & Bloat… Зморщування та роздування … Pucker Tool Інструмент «Зморщування» @@ -3302,6 +3303,7 @@ effect Points Точки Swap Fill and Stroke (Shift+X) Змінити заливку та обведення (Shift+X) Swap start and end arrowheads Поміняти початкову та кінцеву стрілки Swap the selected object for the file, keeping its place and transform Замінити виділений об’єкт файлом, зберігши його положення та перетворення + Stylistic Alternates Стилістичні альтернативи Swash Розчерк Swatch Conflict Конфлікт зразків Swatch Conflicts Конфлікти зразків @@ -3371,6 +3373,7 @@ effect Points Точки Tabs Табуляції Tabular Lining Табличні цифри Tabular Oldstyle Табличні цифри старого стилю + Titling Alternates Альтернативи для заголовків Target Об’єкт Target Contents Вміст об’єкта Target: Об’єкт: diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5b5ad327d4..e2bbed903a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2783,6 +2783,7 @@ mark-style Japanese Kiểu Nhật Proof Setup Thiết lập thử nghiệm Properties Thuộc tính Proportional Metrics Số liệu theo tỷ lệ + Proportional Lining Số tỷ lệ đứng Proportional Oldstyle Kiểu cũ theo tỷ lệ Pucker & Bloat… Nhíu & Phồng… Pucker Tool Công cụ Nhíu @@ -3661,6 +3662,7 @@ mark-style Japanese Kiểu Nhật Swap Fill and Stroke (Shift+X) Đổi màu tô và nét (Shift+X) Swap start and end arrowheads Đổi đầu mũi tên bắt đầu và kết thúc Swap the selected object for the file, keeping its place and transform Thay đối tượng đã chọn bằng tệp, giữ nguyên vị trí và biến đổi + Stylistic Alternates Ký tự thay thế theo phong cách Swash Swash Swatch Conflict Xung đột mẫu màu Swatch Conflicts Xung đột mẫu màu @@ -3699,6 +3701,7 @@ mark-style Japanese Kiểu Nhật Tabs Tab Tabular Lining Số bảng đứng Tabular Oldstyle Số bảng kiểu cũ + Titling Alternates Ký tự thay thế cho tiêu đề Taper Thu dần Target Mục tiêu Target Contents Nội dung mục tiêu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f3246d7a47..ae44d95484 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2376,6 +2376,7 @@ digits Tamil 泰米尔数字 digits Telugu 泰卢固数字 digits Kannada 卡纳达数字 digits Malayalam 马拉雅拉姆数字 + Proportional Lining 比例齐线数字 Proportional Oldstyle 比例旧式数字 Pucker & Bloat… 缩拢与膨胀… Pucker Tool 收缩工具 @@ -3141,6 +3142,7 @@ digits Malayalam 马拉雅拉姆数字 Swap Fill and Stroke (Shift+X) 切换填色和描边 (Shift+X) Swap start and end arrowheads 对调起点与终点箭头 Swap the selected object for the file, keeping its place and transform 以文件替换选择的对象,并保留其位置与变形 + Stylistic Alternates 风格替代字 Swash 花饰字 Swatch Conflict 色板冲突 Swatch Conflicts 色板冲突 @@ -3210,6 +3212,7 @@ digits Malayalam 马拉雅拉姆数字 Tabs 制表符 Tabular Lining 等宽齐线数字 Tabular Oldstyle 等宽旧式数字 + Titling Alternates 标题替代字 Target 目标 Target Contents 目标内容 Target: 目标: diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 831924ac25..454747090b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3317,6 +3317,7 @@ digits Tamil 坦米爾數字 digits Telugu 泰盧固數字 digits Kannada 坎那達數字 digits Malayalam 馬來亞拉姆數字 + Proportional Lining 比例齊線數字 Proportional Oldstyle 比例舊式數字 Pucker & Bloat… 縮攏與膨脹… Pucker Tool 縮攏工具 @@ -4120,6 +4121,7 @@ digits Malayalam 馬來亞拉姆數字 Swap Fill and Stroke (Shift+X) 對調填色與筆畫 (Shift+X) Swap start and end arrowheads 對調起點與終點箭頭 Swap the selected object for the file, keeping its place and transform 以檔案取代選取的物件,並保留其位置與變形 + Stylistic Alternates 風格替代字 Swash 花體字 Swatch Conflict 色票衝突 Swatch Conflicts 色票衝突 @@ -4189,6 +4191,7 @@ digits Malayalam 馬來亞拉姆數字 Tabs 定位點 Tabular Lining 等寬齊線數字 Tabular Oldstyle 等寬舊式數字 + Titling Alternates 標題替代字 Target 目標 Target Contents 目標內容 Target: 目標: diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 2be67f8e86..3f3bcb6596 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -3,16 +3,74 @@ use egui::Ui; use serde_json::json; -use vectorcraft_text::OtFeatures; +use vectorcraft_text::{EXTRA_FEATURES, OtFeatures}; use super::character::{text_editing, text_style}; use crate::VectorcraftApp; use crate::widgets::{self, menu_item}; -/// A checkbox row: label and the feature flag it toggles. -type Toggle = (&'static str, fn(&mut OtFeatures) -> &mut bool); +/// The feature a checkbox row toggles: a named flag, or a tag of [`EXTRA_FEATURES`]. +#[derive(Clone, Copy)] +enum Flag { + Field(fn(&mut OtFeatures) -> &mut bool), + Extra(&'static str), +} -const FIGURES: [&str; 4] = ["Default Figure", "Tabular Lining", "Proportional Oldstyle", "Tabular Oldstyle"]; +/// A checkbox row: label and the feature it toggles. +type Toggle = (&'static str, Flag); + +const FIGURES: [&str; 5] = ["Default Figure", "Tabular Lining", "Proportional Lining", "Proportional Oldstyle", "Tabular Oldstyle"]; + +/// The bit of [`OtFeatures::extra`] that turns `tag` on (0 for a tag outside [`EXTRA_FEATURES`]). +fn extra_bit(tag: &str) -> u32 { + EXTRA_FEATURES.iter().position(|t| *t == tag).map_or(0, |i| 1 << i) +} + +impl Flag { + fn get(self, f: &OtFeatures) -> bool { + match self { + Flag::Field(field) => *field(&mut f.clone()), + Flag::Extra(tag) => f.extra & extra_bit(tag) != 0, + } + } + + fn put(self, f: &mut OtFeatures, on: bool) { + match self { + Flag::Field(field) => *field(f) = on, + Flag::Extra(tag) if on => f.extra |= extra_bit(tag), + Flag::Extra(tag) => f.extra &= !extra_bit(tag), + } + } +} + +/// The Figure menu entry `f` shows: Default Figure, Tabular Lining, Proportional Lining +/// (`pnum` and `lnum`), Proportional Oldstyle or Tabular Oldstyle. +fn figure(f: &OtFeatures) -> usize { + let proportional_lining = extra_bit("pnum") | extra_bit("lnum"); + match (f.tabular_figures, f.oldstyle_figures) { + (false, false) if f.extra & proportional_lining == proportional_lining => 2, + (false, false) => 0, + (true, false) => 1, + (false, true) => 3, + (true, true) => 4, + } +} + +/// `f` with Figure menu entry `i` chosen: the entry's features on, the other figure features off. +/// Tabular Lining keeps an `lnum` the type already has and clears `pnum`; Proportional Oldstyle +/// keeps a `pnum` and clears `lnum`; Default Figure and Tabular Oldstyle clear both. +fn set_figure(f: &mut OtFeatures, i: usize) { + f.tabular_figures = i == 1 || i == 4; + f.oldstyle_figures = i >= 3; + f.extra &= !match i { + 1 => extra_bit("pnum"), + 3 => extra_bit("lnum"), + _ => extra_bit("pnum") | extra_bit("lnum"), + }; + if i == 2 { + f.extra |= extra_bit("pnum") | extra_bit("lnum"); + } +} /// Apply `f` to the selection's features (the Type tool range, or whole objects). fn set(app: &mut VectorcraftApp, f: OtFeatures) { @@ -36,31 +94,16 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut next = cur; ui.horizontal(|ui| { widgets::dim_label(ui, tl!("Figure:")); - let fig = match (cur.tabular_figures, cur.oldstyle_figures) { - (false, false) => 0, - (true, false) => 1, - (false, true) => 2, - (true, true) => 3, - }; + let fig = figure(&cur); if let Some(i) = widgets::dropdown(ui, "ot-figure", FIGURES[fig], &FIGURES, 170.0) { - next.tabular_figures = i == 1 || i == 3; - next.oldstyle_figures = i >= 2; + set_figure(&mut next, i); } }); widgets::divider(ui); - let rows: [Toggle; 7] = [ - (tl!("Standard Ligatures"), |f| &mut f.ligatures), - (tl!("Contextual Alternates"), |f| &mut f.contextual), - (tl!("Discretionary Ligatures"), |f| &mut f.discretionary_ligatures), - (tl!("Swash"), |f| &mut f.swash), - (tl!("Small Caps"), |f| &mut f.small_caps), - (tl!("Ordinals"), |f| &mut f.ordinals), - (tl!("Fractions"), |f| &mut f.fractions), - ]; - for (label, field) in rows { - let on = *field(&mut next.clone()); + for (label, flag) in rows() { + let on = flag.get(&next); if widgets::check(ui, label, on, true) { - *field(&mut next) = !on; + flag.put(&mut next, !on); } } if cur.ligatures && vectorcraft_text::ligatures_suppressed_by(st.tracking) && !vectorcraft_text::explicit_ligatures(&st.features) { @@ -71,6 +114,21 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// The panel's checkbox rows, in the order they are drawn. +fn rows() -> [Toggle; 9] { + [ + (tl!("Standard Ligatures"), Flag::Field(|f| &mut f.ligatures)), + (tl!("Contextual Alternates"), Flag::Field(|f| &mut f.contextual)), + (tl!("Discretionary Ligatures"), Flag::Field(|f| &mut f.discretionary_ligatures)), + (tl!("Swash"), Flag::Field(|f| &mut f.swash)), + (tl!("Stylistic Alternates"), Flag::Extra("salt")), + (tl!("Titling Alternates"), Flag::Extra("titl")), + (tl!("Small Caps"), Flag::Field(|f| &mut f.small_caps)), + (tl!("Ordinals"), Flag::Field(|f| &mut f.ordinals)), + (tl!("Fractions"), Flag::Field(|f| &mut f.fractions)), + ] +} + pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Reset OpenType Features"), text_style(app).is_some(), false) { set(app, OtFeatures::default()); @@ -96,4 +154,95 @@ mod tests { set(&mut app, OtFeatures { ligatures: false, fractions: true, ..Default::default() }); assert_eq!(text_style(&app).unwrap().0.features, ["-liga", "frac"]); } + + fn selected_text() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let id = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Ag 12"})).unwrap()["id"].clone(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + app + } + + fn features(app: &VectorcraftApp) -> OtFeatures { + OtFeatures::from_tags(text_style(app).unwrap().0.features.iter().map(String::as_str)) + } + + /// The Stylistic Alternates and Titling Alternates rows turn `salt` and `titl` on and off + /// on the selected type. + #[test] + fn alternates_rows_set_and_clear_their_features() { + for (label, tag) in [("Stylistic Alternates", "salt"), ("Titling Alternates", "titl")] { + let mut app = selected_text(); + let Some((_, flag)) = rows().into_iter().find(|(l, _)| *l == label) else { + panic!("no {label} row"); + }; + let mut f = features(&app); + assert!(!flag.get(&f), "{label} starts off"); + flag.put(&mut f, true); + set(&mut app, f); + assert_eq!(text_style(&app).unwrap().0.features, [tag], "{label} on"); + assert!(flag.get(&features(&app))); + let mut f = features(&app); + flag.put(&mut f, false); + set(&mut app, f); + assert!(text_style(&app).unwrap().0.features.is_empty(), "{label} off"); + } + } + + /// The Figure menu lists its five entries in order; Proportional Lining sets `pnum` and + /// `lnum` and clears `tnum` and `onum`, Tabular Lining clears `pnum`, Proportional Oldstyle + /// clears `lnum`, and Default Figure and Tabular Oldstyle clear `pnum` and `lnum`. + #[test] + fn proportional_lining_figures() { + assert_eq!(FIGURES, ["Default Figure", "Tabular Lining", "Proportional Lining", "Proportional Oldstyle", "Tabular Oldstyle"]); + let mut app = selected_text(); + let mut f = features(&app); + set_figure(&mut f, 4); + set(&mut app, f); + assert_eq!(text_style(&app).unwrap().0.features, ["onum", "tnum"]); + let mut f = features(&app); + set_figure(&mut f, 2); + set(&mut app, f); + assert_eq!(text_style(&app).unwrap().0.features, ["pnum", "lnum"]); + assert_eq!(figure(&features(&app)), 2); + for (i, want) in [(0, vec![]), (1, vec!["tnum", "lnum"]), (3, vec!["onum", "pnum"]), (4, vec!["onum", "tnum"])] { + let mut f = features(&app); + set_figure(&mut f, 2); + set_figure(&mut f, i); + set(&mut app, f); + assert_eq!(text_style(&app).unwrap().0.features, want, "{}", FIGURES[i]); + assert_eq!(figure(&features(&app)), i); + } + // `pnum` alone is not Proportional Lining. + assert_eq!(figure(&OtFeatures::from_tags(["pnum"])), 0); + } + + /// Choosing Proportional Oldstyle on type with `pnum` and `onum` keeps `pnum`. + #[test] + fn proportional_oldstyle_keeps_pnum() { + let mut app = selected_text(); + set(&mut app, OtFeatures::from_tags(["pnum", "onum"])); + let mut f = features(&app); + assert_eq!(figure(&f), 3); + set_figure(&mut f, 3); + set(&mut app, f); + let tags = text_style(&app).unwrap().0.features; + assert!(tags.iter().any(|t| t == "pnum"), "{tags:?}"); + assert!(tags.iter().any(|t| t == "onum"), "{tags:?}"); + assert_eq!(figure(&features(&app)), 3); + } + + /// Choosing Tabular Lining on type with `lnum`, or with `tnum` and `lnum`, keeps `lnum`. + #[test] + fn tabular_lining_keeps_lnum() { + for start in [&["lnum"][..], &["tnum", "lnum"][..]] { + let mut app = selected_text(); + set(&mut app, OtFeatures::from_tags(start.iter().copied())); + let mut f = features(&app); + set_figure(&mut f, 1); + set(&mut app, f); + assert_eq!(text_style(&app).unwrap().0.features, ["tnum", "lnum"], "{start:?}"); + assert_eq!(figure(&features(&app)), 1); + } + } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 69b8bd6042..c1dd457607 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -853,6 +853,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `<use>` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in rectangular area type, rows and columns included. In area type of another shape, or with text wrap, such a paragraph is broken with the Single-line Composer. The Character panel's Small Caps, Superscript and Subscript buttons and the panel menu's items of the same names turn small caps and the superscript or subscript position on and off for the selected type, or for the text the Type tool has selected (`text.setFormat` or `text.setRangeStyle` `{smallCaps, position}`), in Document Setup's proportions. Turning Superscript on turns Subscript off, and turning Subscript on turns Superscript off. A button or item shows as on when the first selected character (at a caret, the character before it) has its attribute. + The OpenType panel's Stylistic Alternates and Titling Alternates checkboxes turn `salt` and `titl` on and off for the selected type, and its Figure menu lists Default Figure, Tabular Lining, Proportional Lining, Proportional Oldstyle and Tabular Oldstyle; Proportional Lining sets `pnum` and `lnum` and turns `tnum` and `onum` off, Tabular Lining turns `pnum` off and keeps `lnum`, Proportional Oldstyle turns `lnum` off and keeps `pnum`, and Default Figure and Tabular Oldstyle turn `pnum` and `lnum` off. Behavior reference: [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) and [Use swashes, titling alternates, or stylistic alternates](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/use-swashes-titling-alternates-or-stylistic-alternates.html) (public documentation). Tests: `panels::opentype::tests`. - **Paragraph alignment:** the shared Paragraph/Properties alignment row leaves every button unselected when the paragraphs it acts on differ. Auto resolves per paragraph; choosing an alignment uses the existing command. Headless paragraph_mixed_alignment_* regressions exercise mixed → Center → Undo, caret/uniform states, Unicode range boundaries, Auto/direction, split runs and grouped text. These regressions and full integration CI pass. Original captures confirm mixed → Center → Undo in the existing alignment-button layout. The [public Paragraph panel guide](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/paragraph-panel-overview.html) lists the seven controls, but does not specify mixed-state rendering. Other paragraph fields remain outside this change; scores and hours unchanged. For Auto Size area type in columns, the bisection for the frame's height runs on the lines of the one-column layout, and its result is checked with at most two layouts of the columns. When the text wraps around objects or does not fit the one-column layout, or when the check fails, the columns are laid out at every step of the bisection, as before. Typing at the start of a story of 50,000 characters in 2 columns took 1,670 ms a keystroke and now takes 292 ms (release build, `auto_height_in_columns_typing_timing`). Exports to PDF, EPS, SVG, EMF, WMF and the raster formats warn about the area type and type on a path that they draw without the text that doesn't fit, and give their ids, as Print and Print Preview do. From 7410b7233e761a03c8386f56e9401e95c71d8d58 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 15:12:39 -0700 Subject: [PATCH 216/260] i18n: link, font and export status messages use real plural forms instead of "(s)" The status bar's messages for relinked, replaced, updated and embedded images, broken links, linked files that can't be read or changed on disk, images that can't be decoded, added and unavailable fonts, copied CSS, downloads and exports with notes read "1 image(s)" and similar. They now say "1 image" and "2 images", and every catalog translates both through @msgplural rows in the language's plural forms, as the Package status does. - i18n::msg_n writes such a message in English and fills its placeholders in one pass; the status bar's translation fills them in one pass too, so a path or name that holds "{n}" text stays whole. - The old "(s)" @msg rows are replaced in all 26 catalogs, with new rows for Replaced and Break Link. - Sites: dialogs/missing_links.rs, dialogs/missing_fonts.rs, app/links.rs, panels/css_properties.rs, dialogs/find_links.rs, panels/links.rs, place.rs, canvas.rs, io/export.rs and dialogs/save_for_web.rs. --- crates/ui-egui/src/app/links.rs | 9 ++- crates/ui-egui/src/canvas.rs | 7 ++- crates/ui-egui/src/canvas/tests.rs | 2 +- crates/ui-egui/src/dialogs/find_links.rs | 9 ++- .../ui-egui/src/dialogs/find_links/tests.rs | 4 +- crates/ui-egui/src/dialogs/missing_fonts.rs | 18 +++++- .../src/dialogs/missing_fonts/tests.rs | 2 +- crates/ui-egui/src/dialogs/missing_links.rs | 19 ++++++- crates/ui-egui/src/dialogs/save_for_web.rs | 2 +- crates/ui-egui/src/dialogs/tests_screens.rs | 4 +- crates/ui-egui/src/i18n.rs | 39 ++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 38 +++++++------ crates/ui-egui/src/i18n/bs.tsv | 38 +++++++------ crates/ui-egui/src/i18n/ca.tsv | 38 +++++++------ crates/ui-egui/src/i18n/cs.tsv | 38 +++++++------ crates/ui-egui/src/i18n/da.tsv | 37 ++++++------ crates/ui-egui/src/i18n/de.tsv | 38 +++++++------ crates/ui-egui/src/i18n/el.tsv | 38 +++++++------ crates/ui-egui/src/i18n/es.tsv | 38 +++++++------ crates/ui-egui/src/i18n/fi.tsv | 38 +++++++------ crates/ui-egui/src/i18n/fr.tsv | 38 +++++++------ crates/ui-egui/src/i18n/hu.tsv | 38 +++++++------ crates/ui-egui/src/i18n/id.tsv | 37 ++++++------ crates/ui-egui/src/i18n/it.tsv | 38 +++++++------ crates/ui-egui/src/i18n/ja.tsv | 38 +++++++------ crates/ui-egui/src/i18n/ka.tsv | 38 +++++++------ crates/ui-egui/src/i18n/ko.tsv | 38 +++++++------ crates/ui-egui/src/i18n/nl.tsv | 37 ++++++------ crates/ui-egui/src/i18n/pl.tsv | 38 +++++++------ crates/ui-egui/src/i18n/pt-br.tsv | 38 +++++++------ crates/ui-egui/src/i18n/ru.tsv | 38 +++++++------ crates/ui-egui/src/i18n/sv.tsv | 38 +++++++------ crates/ui-egui/src/i18n/tests.rs | 57 +++++++++++++++++++ crates/ui-egui/src/i18n/tr.tsv | 38 +++++++------ crates/ui-egui/src/i18n/uk.tsv | 38 +++++++------ crates/ui-egui/src/i18n/vi.tsv | 38 +++++++------ crates/ui-egui/src/i18n/zh-hans.tsv | 38 +++++++------ crates/ui-egui/src/i18n/zh-hant.tsv | 38 +++++++------ crates/ui-egui/src/io.rs | 2 +- crates/ui-egui/src/io/export.rs | 10 +++- crates/ui-egui/src/panels/css_properties.rs | 4 +- crates/ui-egui/src/panels/links.rs | 47 ++++++++++++--- .../src/panels/tests_css_properties.rs | 2 +- crates/ui-egui/src/place.rs | 2 +- docs/target-app-parity.md | 1 + 45 files changed, 727 insertions(+), 498 deletions(-) diff --git a/crates/ui-egui/src/app/links.rs b/crates/ui-egui/src/app/links.rs index 7c8c4abd61..7d91162908 100644 --- a/crates/ui-egui/src/app/links.rs +++ b/crates/ui-egui/src/app/links.rs @@ -52,13 +52,18 @@ impl VectorcraftApp { Ok(r) => { let n = |k: &str| r[k].as_array().map_or(0, Vec::len); if n("updated") > 0 { - self.status(format!("Updated {} linked file(s) changed on disk", n("updated"))); + self.status(crate::i18n::msg_n( + n("updated") as u64, + "Updated {n} linked file changed on disk", + "Updated {n} linked files changed on disk", + &[], + )); } if n("ask") > 0 { dialogs::missing_links::ask_update_changed(self, r["ask"].as_array().cloned().unwrap_or_default()); } if n("modified") > 0 { - self.status(format!("{} linked image(s) changed on disk: Update Links shows the new versions", n("modified"))); + self.status(dialogs::missing_links::changed_on_disk_status(n("modified"))); } } Err(e) => self.status(e.to_string()), diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index cd2a142be3..4850b9e259 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -293,7 +293,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // decode, once per image in the process. let undecoded = vectorcraft_render::newly_undecodable(doc.images.values()); if undecoded > 0 { - app.status(format!("{undecoded} image(s) couldn't be decoded and show as crossed boxes")); + app.status(crate::i18n::msg_n( + undecoded as u64, + "{n} image couldn't be decoded and shows as a crossed box", + "{n} images couldn't be decoded and show as crossed boxes", + &[], + )); } fill_uncovered(app, ui.ctx(), &painter, &key, &doc, rect, &xf); reproject_frame(app, &painter, &xf, rect, (key.doc, v.rotation)); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 1bcc164a36..4b59bdb8f6 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2015,7 +2015,7 @@ fn undecodable_images_are_marked_and_reported_once() { app.status(""); frame(&mut app, &ctx, vec![]); assert!(app.canvas.shown.as_ref().is_some_and(|(_, o)| o.mark_undecoded_images), "the canvas marks them"); - assert_eq!(app.ui.status, "2 image(s) couldn't be decoded and show as crossed boxes"); + assert_eq!(app.ui.status, "2 images couldn't be decoded and show as crossed boxes"); app.status(""); app.session.doc_mut().unwrap().revision += 1; frame(&mut app, &ctx, vec![]); diff --git a/crates/ui-egui/src/dialogs/find_links.rs b/crates/ui-egui/src/dialogs/find_links.rs index 6543816ec7..f6b482f190 100644 --- a/crates/ui-egui/src/dialogs/find_links.rs +++ b/crates/ui-egui/src/dialogs/find_links.rs @@ -372,9 +372,14 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { match failed.first() { Some(f) => { let (name, reason) = (f["name"].as_str().unwrap_or_default(), f["error"].as_str().unwrap_or_default()); - app.status(format!("Relinked {n} image(s); {name} couldn't be relinked: {reason}")); + app.status(crate::i18n::msg_n( + n as u64, + "Relinked {n} image; {name} couldn't be relinked: {reason}", + "Relinked {n} images; {name} couldn't be relinked: {reason}", + &[("name", name), ("reason", reason)], + )); } - None if n > 0 => app.status(format!("Relinked {n} image(s)")), + None if n > 0 => app.status(crate::panels::links::relinked_status(n)), None => {} } if d.bool("back") { diff --git a/crates/ui-egui/src/dialogs/find_links/tests.rs b/crates/ui-egui/src/dialogs/find_links/tests.rs index b85b67634f..0c7f5d2e8c 100644 --- a/crates/ui-egui/src/dialogs/find_links/tests.rs +++ b/crates/ui-egui/src/dialogs/find_links/tests.rs @@ -119,7 +119,7 @@ fn find_in_folder_relinks_the_missing_files_to_the_files_found() { } super::super::confirm(&mut app).unwrap(); assert!(app.ui.dialog.is_none()); - assert_eq!(app.ui.status, "Relinked 2 image(s)"); + assert_eq!(app.ui.status, "Relinked 2 images"); assert_eq!(app.run("links.check", json!({})).unwrap()["missing"], 0); } @@ -140,7 +140,7 @@ fn files_not_relinked_go_back_to_linked_file_not_found() { assert_eq!((pick(d, "b.png"), pick(d, "c.png")), (&json!(at(&root, "found/b.png")), &Value::Null)); assert!(frame(&mut app).contains("Not found")); super::super::confirm(&mut app).unwrap(); - assert!(app.ui.status.starts_with("Relinked 1 image(s); b.png couldn't be relinked: "), "{}", app.ui.status); + assert!(app.ui.status.starts_with("Relinked 1 image; b.png couldn't be relinked: "), "{}", app.ui.status); let d = app.ui.dialog.as_ref().expect("Linked File Not Found again"); let names: Vec<&str> = d.fields["missing"].as_array().unwrap().iter().map(|r| r["name"].as_str().unwrap()).collect(); assert_eq!((d.kind.as_str(), names.len()), (super::super::missing_links::KIND, 2)); diff --git a/crates/ui-egui/src/dialogs/missing_fonts.rs b/crates/ui-egui/src/dialogs/missing_fonts.rs index 205e4fa98e..e95a3302fc 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts.rs @@ -54,7 +54,12 @@ fn after_open_for(app: &mut VectorcraftApp, r: &Value, web: bool) { if web { let n = vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).len(); if n > 0 && r["warnings"].as_array().is_none_or(Vec::is_empty) { - app.status(format!("{n} font(s) aren't available here: their text shows in another font")); + app.status(crate::i18n::msg_n( + n as u64, + "{n} font isn't available here: its text shows in another font", + "{n} fonts aren't available here: their text shows in another font", + &[], + )); } return; } @@ -399,13 +404,20 @@ fn add_fonts(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { let n = len("copied") + len("kept"); let folder = r["folder"].as_str().unwrap_or_default(); match r["skipped"].as_array().and_then(|s| s.first()) { - None => app.status(format!("{n} font file(s) are now in {folder}")), + None => { + app.status(crate::i18n::msg_n(n as u64, "{n} font file is now in {folder}", "{n} font files are now in {folder}", &[("folder", folder)])) + } Some(first) => { let failed = len("skipped"); let file = first["file"].as_str().map(std::path::Path::new).and_then(std::path::Path::file_name).map(|f| f.to_string_lossy().into_owned()); let reason = format!("{}: {}", file.unwrap_or_default(), first["reason"].as_str().unwrap_or_default()); - app.status(format!("{n} font file(s) are now in {folder}; {failed} couldn't be added: {reason}")); + app.status(crate::i18n::msg_n( + n as u64, + "{n} font file is now in {folder}; {failed} couldn't be added: {reason}", + "{n} font files are now in {folder}; {failed} couldn't be added: {reason}", + &[("failed", &failed.to_string()), ("folder", folder), ("reason", &reason)], + )); } } Ok(r) diff --git a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs index c2b2a4e6c8..1c6cc18cac 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs @@ -357,7 +357,7 @@ fn the_web_says_how_many_fonts_are_missing() { app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); app.run("text.create", json!({"x": 10, "y": 40, "text": "Gone", "font": "No Such Font Family"})).unwrap(); after_open_for(&mut app, &json!({}), true); - assert_eq!(app.ui.status, "1 font(s) aren't available here: their text shows in another font"); + assert_eq!(app.ui.status, "1 font isn't available here: its text shows in another font"); assert!(app.ui.pending_fonts.is_empty()); // The open's notes stay on show. app.ui.status = "Opened with 1 note(s): fonts".into(); diff --git a/crates/ui-egui/src/dialogs/missing_links.rs b/crates/ui-egui/src/dialogs/missing_links.rs index fe6a804860..78affd3c24 100644 --- a/crates/ui-egui/src/dialogs/missing_links.rs +++ b/crates/ui-egui/src/dialogs/missing_links.rs @@ -49,7 +49,12 @@ pub fn after_open(app: &mut VectorcraftApp, r: &Value) { let (missing, modified) = (rows("missingLinks"), ids(&rows("modifiedLinks"))); if missing.is_empty() || cfg!(target_arch = "wasm32") { if !missing.is_empty() { - app.status(format!("{} linked file(s) can't be read here: their previews show", missing.len())); + app.status(crate::i18n::msg_n( + missing.len() as u64, + "{n} linked file can't be read here: its preview shows", + "{n} linked files can't be read here: their previews show", + &[], + )); } ask_update(app, modified); } else { @@ -96,13 +101,23 @@ fn ask(app: &mut VectorcraftApp, ids: Vec<Value>, one: &str, other: &str) { return; } if app.session.prefs.update_links != "askWhenModified" { - app.status(format!("{} linked image(s) changed on disk: Update Links shows the new versions", ids.len())); + app.status(changed_on_disk_status(ids.len())); return; } let detail = crate::i18n::tn(ids.len() as u64, one, other); super::confirm::ask(app, tl!("Update Modified Links"), &detail, "links.update", json!({ "ids": ids })); } +/// The status bar's line for `n` linked images that changed on disk while Update Links doesn't ask. +pub(crate) fn changed_on_disk_status(n: usize) -> String { + crate::i18n::msg_n( + n as u64, + "{n} linked image changed on disk: Update Links shows the new version", + "{n} linked images changed on disk: Update Links shows the new versions", + &[], + ) +} + fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let t = Tokens::get(ui.ctx()); let missing = d.fields.get("missing").and_then(Value::as_array).map_or(&[][..], Vec::as_slice); diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index b31bfa308e..26c01f052d 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -150,7 +150,7 @@ pub(crate) fn save(app: &mut VectorcraftApp, mut p: Value) -> Result<Value, Stri } match names.first().and_then(Value::as_str).filter(|_| has_warnings(&r)) { Some(first) => io::report_saved(app, first, &r), - None => app.status(format!("Downloaded {} file(s)", names.len())), + None => app.status(crate::i18n::msg_n(names.len() as u64, "Downloaded {n} file", "Downloaded {n} files", &[])), } return Ok(json!({ "files": names, "bytes": r["bytes"], "warnings": r["warnings"] })); } diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index 5e2891f5c3..946f840f68 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -388,7 +388,7 @@ fn an_export_made_at_once_waits_for_one_in_the_background() { release.join().unwrap(); let file = format!("{folder}/Artboard-1.svg"); assert_eq!((written(&files), r["files"].clone()), (vec![file.clone()], json!([file]))); - assert_eq!(app.ui.status, format!("Exported 1 file(s) to {folder}")); + assert_eq!(app.ui.status, format!("Exported 1 file to {folder}")); let _ = std::fs::remove_dir_all(&dir); } @@ -489,7 +489,7 @@ fn the_status_bar_says_when_an_image_could_not_be_decoded() { let folder = dir.to_string_lossy().replace('\\', "/"); let (mut desktop, log) = app(1, false); desktop.run("file.exportForScreens", json!({"folder": folder, "formats": rows})).unwrap(); - assert_eq!(desktop.ui.status, format!("Exported 2 file(s) to {folder}")); + assert_eq!(desktop.ui.status, format!("Exported 2 files to {folder}")); place(&mut desktop); desktop.run("file.exportForScreens", json!({"folder": folder, "formats": rows, "openLocation": true})).unwrap(); assert_eq!(desktop.ui.status, format!("Saved {folder} {NOTE}")); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index dee009b768..689eb2015f 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -24,7 +24,8 @@ //! rows hold whole messages or templates such as `Couldn't open {name}: {e}`, and the values in //! the placeholders are translated in turn (the reason after `: {e}` is often a message too). //! A `@msgplural` row is a template with a count: its source holds the English `one|other` -//! forms, its translation the language's plural forms, and the `{n}` value picks the form. +//! forms, its translation the language's plural forms, and the `{n}` value picks the form; +//! [`msg_n`] writes such a message in English. mod catalog; @@ -660,7 +661,31 @@ fn message_at(lang: Lang, s: &str, depth: usize) -> String { let values: Vec<(&str, String)> = caps.into_iter().map(|(k, v)| (k, if depth > 1 { message_at(lang, v, depth - 1) } else { v.to_string() })).collect(); let args: Vec<(&str, &str)> = values.iter().map(|(k, v)| (*k, v.as_str())).collect(); - fmt(template, &args) + fill_once(template, &args) +} + +/// Fill `{name}` placeholders in one pass: a value that holds `{name}` text stays as it is. +/// Unknown placeholders are left as written. +fn fill_once(template: &str, args: &[(&str, &str)]) -> String { + let mut rest = template; + let mut out = String::with_capacity(rest.len()); + while let Some(open) = rest.find('{') { + out.push_str(&rest[..open]); + let after = &rest[open + 1..]; + let filled = after.find('}').and_then(|close| args.iter().find(|(k, _)| *k == &after[..close]).map(|(_, v)| (*v, close))); + match filled { + Some((value, close)) => { + out.push_str(value); + rest = &after[close + 1..]; + } + None => { + out.push('{'); + rest = after; + } + } + } + out.push_str(rest); + out } /// [`message`] in the current language, remembering the last answer: the status bar asks for the @@ -685,6 +710,16 @@ pub fn tn(n: u64, one: &str, other: &str) -> String { trn(current(), n, one, other) } +/// A status or error message with a count, in English: `one` for a count of 1, else `other`, with +/// `{n}` and the `args` placeholders filled in one pass, so a value that holds `{name}` text stays +/// as it is. Unknown placeholders are left as written. The message stays English, and [`msg`] +/// shows it in the interface language through the catalogs' `@msgplural` rows. +pub fn msg_n(n: u64, one: &str, other: &str, args: &[(&str, &str)]) -> String { + let count = n.to_string(); + let all: Vec<(&str, &str)> = std::iter::once(("n", count.as_str())).chain(args.iter().copied()).collect(); + fill_once(if n == 1 { one } else { other }, &all) +} + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 9c34a3bff9..8f93990a02 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3805,7 +3805,6 @@ axis Both И двете @msg Combine Slices: the slices have no bounds Обединяване на парчета: парчетата нямат граници @msg Convert to Artboards: selection has no area Преобразуване в работни области: селекцията няма площ @msg Convert to Shape: no rectangles or ellipses selected Преобразуване в фигура: няма избрани правоъгълници или елипси -@msg Copied the CSS of {rules} object(s) Копиран е CSS кодът на {rules} обект(а) @msg Copied the script report Копиран е отчетът за скрипта @msg Corners edits the corners of a path Ъглите редактират ъглите на пътя @msg Couldn't copy to the system clipboard: {e} Неуспешно копиране в системния клипборд: {e} @@ -3822,13 +3821,11 @@ axis Both И двете @msg direct-select anchor points to cut at (not the end points of open paths) директно избиране на опорни точки за рязане (не крайните точки на отворени пътища) @msg Divide Objects Below: select a path Разделяне на обектите отдолу: изберете път @msg Divide Objects Below: select exactly one path Разделяне на обектите отдолу: изберете точно един път -@msg Downloaded {_1} file(s) Изтеглени файлове: {_1} @msg Downloaded {what} Изтеглено: {what} @msg Expand Appearance: the selection has a basic appearance Разширяване на облика: селекцията има основен облик @msg Expand: no brush strokes selected Разширяване: няма избрани щрихи на четка @msg Expand: no gradient fills Разширяване: няма запълвания с градиент @msg Expand: nothing to expand Разширяване: няма нищо за разширяване -@msg Exported {count} file(s) to {folder} Експортирани са {count} файла в {folder} @msg Exported {path} Експортирано: {path} @msg Flatten Transparency: select objects to flatten Сплескване на прозрачността: изберете обекти за сплескване @msg Flatten Transparency: {e} Сплескване на прозрачността: {e} @@ -4354,10 +4351,6 @@ axis Both И двете @msg {_1} is a live effect (Effect › Plug-ins) {_1} е динамичен ефект (Ефект › Добавки) @msg {_1} is already used by {_2} {_1} вече се използва от {_2} @msg {_1} is reserved by the system {_1} е запазено от системата -@msg {_1} linked file(s) can't be read here: their previews show свързаните файлове {_1} не могат да бъдат прочетени тук: показват се техните прегледи -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes изображенията ({undecoded}) не могат да бъдат декодирани: показват се като зачеркнати рамки -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions свързаните изображения {_1} са променени на диска: „Обновяване на връзките“ показва новите версии -@msg Updated {_1} linked file(s) changed on disk Обновени са свързани файлове {_1}, променени на диска @msg {_1}: not saved, so not closed {_1}: не е запазен, затова не е затворен @msg {bpp}-bit bitmaps can't be read {bpp}-битови битови масиви не могат да бъдат прочетени @msg {command} didn't create an object {command} не създаде обект @@ -4377,7 +4370,6 @@ axis Both И двете @msg Couldn't place {name}: {e} Неуспешно поставяне на {name}: {e} @msg Couldn't paste from the clipboard: {e} Неуспешно поставяне от клипборда: {e} @msg Saved {path} with {_1} note(s): {first} {path} е запазен с {_1} бележка/и: {first} -@msg Exported {what} with {_1} note(s): {first} {what} е експортиран с {_1} бележка/и: {first} @msg Exported {what} Експортирано: {what} @msg Saved {n} files beside {path} Записани са {n} файла до {path} @msg Saving Запазване @@ -4388,12 +4380,26 @@ axis Both И двете @msg Saving recovery data for {_1} Записване на данни за възстановяване на {_1} @msg Discarded {_1} recovered document(s) Изхвърлени са {_1} възстановени документ(и) @msg Restored {_1} recovered document(s): save them to keep them Възстановени са {_1} документ(и): запазете ги, за да ги съхраните -@msg Embedded {n} image(s); {missing} missing: relink them first Вградени са {n} изображения; {missing} липсват: първо ги свържете наново -@msg Embedded {n} image(s) Вградени са {n} изображения -@msg Relinked {_1} image(s) Презакачени са {_1} изображения -@msg Relinked {n} image(s) Свързани наново {n} изображения -@msg Relinked {n} image(s); not in that folder: {_1} Презакачени са {n} изображения; липсват в тази папка: {_1} -@msg Updated {_1} image(s) Обновени са {_1} изображения +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Вградено е {n} изображение; {missing} липсват: първо ги свържете наново|Вградени са {n} изображения; {missing} липсват: първо ги свържете наново +@msgplural Embedded {n} image|Embedded {n} images Вградено е {n} изображение|Вградени са {n} изображения +@msgplural Relinked {n} image|Relinked {n} images Свързано наново е {n} изображение|Свързани наново са {n} изображения +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} Свързано наново е {n} изображение; липсват в тази папка: {names}|Свързани наново са {n} изображения; липсват в тази папка: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} Свързано наново е {n} изображение; {name} не можа да бъде свързан наново: {reason}|Свързани наново са {n} изображения; {name} не можа да бъде свързан наново: {reason} +@msgplural Updated {n} image|Updated {n} images Обновено е {n} изображение|Обновени са {n} изображения +@msgplural Replaced {n} image|Replaced {n} images Заменено е {n} изображение|Заменени са {n} изображения +@msgplural Broke {n} link|Broke {n} links Разкъсана е {n} връзка|Разкъсани са {n} връзки +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first Разкъсана е {n} връзка; {missing} не могат да бъдат прочетени: първо ги свържете наново или ги обновете|Разкъсани са {n} връзки; {missing} не могат да бъдат прочетени: първо ги свържете наново или ги обновете +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} свързан файл не може да бъде прочетен тук: показва се неговият преглед|{n} свързани файла не могат да бъдат прочетени тук: показват се техните прегледи +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes {n} изображение не може да бъде декодирано: показва се като зачеркната рамка|{n} изображения не могат да бъдат декодирани: показват се като зачеркнати рамки +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} свързано изображение е променено на диска: „Обновяване на връзките“ показва новата версия|{n} свързани изображения са променени на диска: „Обновяване на връзките“ показва новите версии +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Обновен е {n} свързан файл, променен на диска|Обновени са {n} свързани файла, променени на диска +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} {what} е експортиран с {n} бележка: {first}|{what} е експортиран с {n} бележки: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} шрифтов файл вече е в {folder}|{n} шрифтови файла вече са в {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} шрифтов файл вече е в {folder}; {failed} не можаха да бъдат добавени: {reason}|{n} шрифтови файла вече са в {folder}; {failed} не можаха да бъдат добавени: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} шрифт не е достъпен тук: текстът му се показва в друг шрифт|{n} шрифта не са достъпни тук: техният текст се показва в друг шрифт +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Копиран е CSS кодът на {n} обект|Копиран е CSS кодът на {n} обекта +@msgplural Downloaded {n} file|Downloaded {n} files Изтеглен е {n} файл|Изтеглени са {n} файла +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Експортиран е {n} файл в {folder}|Експортирани са {n} файла в {folder} @msg Unembedded to {_1} Извадено от вграждане в {_1} @msg Reset {_1} Нулирано: {_1} @msg Sent to {_1} Изпратено към {_1} @@ -4445,9 +4451,6 @@ axis Both И двете @msg every search thread stopped on an internal error (please report this bug) всяка нишка за търсене спря поради вътрешна грешка (моля, докладвайте този бъг) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it Папката със шрифтове на VectorCraft не е зададена тук: десктоп приложението и vectorcraft-cli я задават @msg choose the font files to add изберете шрифтовите файлове за добавяне -@msg {n} font file(s) are now in {folder} {n} шрифтов(и) файл(а) вече са в {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} шрифтов(и) файл(а) вече са в {folder}; {failed} не можаха да бъдат добавени: {reason} -@msg {n} font(s) aren't available here: their text shows in another font {n} шрифт(а) не са достъпни тук: техният текст се показва в друг шрифт @msg not a file не е файл @msg not a font file не е шрифтов файл @msg that document is no longer open този документ вече не е отворен @@ -4456,7 +4459,6 @@ axis Both И двете @msg every numbered name for it is taken in the Fonts folder всяко номерирано име за него е заето в папката със шрифтове @msg every numbered name for {name} is taken in the document's folder всяко номерирано име за {name} е заето в папката на документа @msg No linked files to look for Няма свързани файлове за търсене -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} Превързани са {n} изображения; {name} не можа да бъде превързан: {reason} Services Услуги Hide VectorCraft Скриване на VectorCraft Zoom Мащабиране diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d79eeeccaf..943a73609a 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -664,7 +664,6 @@ Links Veze @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? Povezanih slika promijenjenih na disku: {n}. Prikazati nove verzije?|Povezanih slika promijenjenih na disku: {n}. Prikazati nove verzije?|Povezanih slika promijenjenih na disku: {n}. Prikazati nove verzije? Update Changed Links Ažuriraj promijenjene veze -@msg Updated {_1} linked file(s) changed on disk Ažurirano povezanih datoteka promijenjenih na disku: {_1} Magic Wand Čarobni štapić Navigator Navigator Pattern Options Opcije uzorka @@ -4171,7 +4170,6 @@ imageTrace Outline Obris @msg Combine Slices: the slices have no bounds Kombinuj isječke: isječci nemaju granice @msg Convert to Artboards: selection has no area Pretvori u radne ploče: odabir nema površinu @msg Convert to Shape: no rectangles or ellipses selected Pretvori u oblik: nisu odabrani pravougaonici ni elipse -@msg Copied the CSS of {rules} object(s) Kopiran CSS objekata: {rules} @msg Copied the script report Izvještaj skripte kopiran @msg Corners edits the corners of a path Uglovi uređuje uglove putanje @msg Couldn't copy to the system clipboard: {e} Nije moguće kopirati u sistemski međuspremnik: {e} @@ -4188,13 +4186,11 @@ imageTrace Outline Obris @msg direct-select anchor points to cut at (not the end points of open paths) direktno odaberite sidrene tačke za presijecanje (ne krajnje tačke otvorenih putanja) @msg Divide Objects Below: select a path Podijeli objekte ispod: odaberite putanju @msg Divide Objects Below: select exactly one path Podijeli objekte ispod: odaberite tačno jednu putanju -@msg Downloaded {_1} file(s) Preuzeto datoteka: {_1} @msg Downloaded {what} Preuzeto: {what} @msg Expand Appearance: the selection has a basic appearance Proširi izgled: odabir ima osnovni izgled @msg Expand: no brush strokes selected Proširi: nisu odabrani potezi četkicom @msg Expand: no gradient fills Proširi: nema gradijentnih ispuna @msg Expand: nothing to expand Proširi: nema ničeg za proširivanje -@msg Exported {count} file(s) to {folder} Izvezeno datoteka u {folder}: {count} @msg Exported {path} Izvezeno: {path} @msg Flatten Transparency: select objects to flatten Spljošti prozirnost: odaberite objekte za spljoštavanje @msg Flatten Transparency: {e} Spljošti prozirnost: {e} @@ -4751,9 +4747,6 @@ imageTrace Outline Obris @msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` ima {size} bajtova (ograničenje {MAX_DOCUMENT_DATA}) @msg {_1} is already used by {_2} {_1} već koristi {_2} @msg {_1} is reserved by the system {_1} je rezervisano od strane sistema -@msg {_1} linked file(s) can't be read here: their previews show Povezane datoteke koje se ovdje ne mogu pročitati: {_1}; prikazuju se njihovi pregledi -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes Slike koje nije moguće dekodirati prikazuju se kao prekriženi okviri ({undecoded}) -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions Povezane slike promijenjene na disku: {_1}; Ažuriraj veze prikazuje nove verzije @msg {_1}: not saved, so not closed {_1}: nije sačuvano, pa nije zatvoreno @msg {bpp}-bit bitmaps can't be read {bpp}-bitne bitmape ne mogu se pročitati @msg {command} didn't create an object {command} nije kreirala objekat @@ -4773,7 +4766,6 @@ imageTrace Outline Obris @msg Couldn't place {name}: {e} Nije moguće postaviti {name}: {e} @msg Couldn't paste from the clipboard: {e} Nije moguće zalijepiti iz međuspremnika: {e} @msg Saved {path} with {_1} note(s): {first} Sačuvano {path} s bilješkama ({_1}): {first} -@msg Exported {what} with {_1} note(s): {first} Izvezeno {what} s bilješkama ({_1}): {first} @msg Exported {what} Izvezeno: {what} @msg Saved {n} files beside {path} Sačuvano datoteka pored {path}: {n} @msg Saving Čuvanje @@ -4784,12 +4776,26 @@ imageTrace Outline Obris @msg Saving recovery data for {_1} Čuvanje podataka za oporavak za {_1} @msg Discarded {_1} recovered document(s) Odbačeno oporavljenih dokumenata: {_1} @msg Restored {_1} recovered document(s): save them to keep them Vraćeno oporavljenih dokumenata: {_1}; sačuvajte ih da ih zadržite -@msg Embedded {n} image(s); {missing} missing: relink them first Ugrađeno slika: {n}; nedostaje {missing}: prvo ih ponovo povežite -@msg Embedded {n} image(s) Ugrađeno slika: {n} -@msg Relinked {_1} image(s) Ponovo povezano slika: {_1} -@msg Relinked {n} image(s) Ponovo povezano slika: {n} -@msg Relinked {n} image(s); not in that folder: {_1} Ponovo povezano slika: {n}; nisu u tom folderu: {_1} -@msg Updated {_1} image(s) Ažurirano slika: {_1} +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Ugrađena je {n} slika; nedostaje {missing}: prvo ih ponovo povežite|Ugrađene su {n} slike; nedostaje {missing}: prvo ih ponovo povežite|Ugrađeno je {n} slika; nedostaje {missing}: prvo ih ponovo povežite +@msgplural Embedded {n} image|Embedded {n} images Ugrađena je {n} slika|Ugrađene su {n} slike|Ugrađeno je {n} slika +@msgplural Relinked {n} image|Relinked {n} images Ponovo je povezana {n} slika|Ponovo su povezane {n} slike|Ponovo je povezano {n} slika +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} Ponovo je povezana {n} slika; nisu u tom folderu: {names}|Ponovo su povezane {n} slike; nisu u tom folderu: {names}|Ponovo je povezano {n} slika; nisu u tom folderu: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} Ponovo je povezana {n} slika; {name} nije moguće ponovo povezati: {reason}|Ponovo su povezane {n} slike; {name} nije moguće ponovo povezati: {reason}|Ponovo je povezano {n} slika; {name} nije moguće ponovo povezati: {reason} +@msgplural Updated {n} image|Updated {n} images Ažurirana je {n} slika|Ažurirane su {n} slike|Ažurirano je {n} slika +@msgplural Replaced {n} image|Replaced {n} images Zamijenjena je {n} slika|Zamijenjene su {n} slike|Zamijenjeno je {n} slika +@msgplural Broke {n} link|Broke {n} links Prekinuta je {n} veza|Prekinute su {n} veze|Prekinuto je {n} veza +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first Prekinuta je {n} veza; {missing} nije moguće pročitati: prvo ih ponovo povežite ili ažurirajte|Prekinute su {n} veze; {missing} nije moguće pročitati: prvo ih ponovo povežite ili ažurirajte|Prekinuto je {n} veza; {missing} nije moguće pročitati: prvo ih ponovo povežite ili ažurirajte +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} povezana datoteka se ovdje ne može pročitati: prikazuje se njen pregled|{n} povezane datoteke se ovdje ne mogu pročitati: prikazuju se njihovi pregledi|{n} povezanih datoteka se ovdje ne može pročitati: prikazuju se njihovi pregledi +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes {n} sliku nije moguće dekodirati: prikazuje se kao prekriženi okvir|{n} slike nije moguće dekodirati: prikazuju se kao prekriženi okviri|{n} slika nije moguće dekodirati: prikazuju se kao prekriženi okviri +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} povezana slika promijenjena je na disku: Ažuriraj veze prikazuje novu verziju|{n} povezane slike promijenjene su na disku: Ažuriraj veze prikazuje nove verzije|{n} povezanih slika promijenjeno je na disku: Ažuriraj veze prikazuje nove verzije +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Ažurirana je {n} povezana datoteka promijenjena na disku|Ažurirane su {n} povezane datoteke promijenjene na disku|Ažurirano je {n} povezanih datoteka promijenjenih na disku +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Izvezeno {what} s {n} bilješkom: {first}|Izvezeno {what} s {n} bilješke: {first}|Izvezeno {what} s {n} bilješki: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} datoteka fonta sada je u {folder}|{n} datoteke fontova sada su u {folder}|{n} datoteka fontova sada je u {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} datoteka fonta sada je u {folder}; {failed} nije moguće dodati: {reason}|{n} datoteke fontova sada su u {folder}; {failed} nije moguće dodati: {reason}|{n} datoteka fontova sada je u {folder}; {failed} nije moguće dodati: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} font ovdje nije dostupan: njegov tekst se prikazuje drugim fontom|{n} fonta ovdje nisu dostupna: njihov tekst se prikazuje drugim fontom|{n} fontova ovdje nije dostupno: njihov tekst se prikazuje drugim fontom +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Kopiran je CSS {n} objekta|Kopiran je CSS {n} objekta|Kopiran je CSS {n} objekata +@msgplural Downloaded {n} file|Downloaded {n} files Preuzeta je {n} datoteka|Preuzete su {n} datoteke|Preuzeto je {n} datoteka +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Izvezena je {n} datoteka u {folder}|Izvezene su {n} datoteke u {folder}|Izvezeno je {n} datoteka u {folder} @msg Unembedded to {_1} Ugrađivanje poništeno u {_1} @msg Reset {_1} Vrati na početno: {_1} @msg Sent to {_1} Poslano na {_1} @@ -4841,9 +4847,6 @@ imageTrace Outline Obris @msg every search thread stopped on an internal error (please report this bug) sve niti pretrage su se zaustavile zbog interne greške (molimo prijavite ovu grešku) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it Folder Fontovi VectorCrafta ovdje nije postavljen: postavljaju ga desktop aplikacija i vectorcraft-cli @msg choose the font files to add odaberite datoteke fontova za dodavanje -@msg {n} font file(s) are now in {folder} Datoteke fontova ({n}) sada su u {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} Datoteke fontova ({n}) sada su u {folder}; {failed} nije moguće dodati: {reason} -@msg {n} font(s) aren't available here: their text shows in another font Fontovi koji ovdje nisu dostupni: {n}; njihov tekst se prikazuje drugim fontom @msg not a file nije datoteka @msg not a font file nije datoteka fonta @msg that document is no longer open taj dokument više nije otvoren @@ -4852,7 +4855,6 @@ imageTrace Outline Obris @msg every numbered name for it is taken in the Fonts folder svi numerisani nazivi za njega su zauzeti u folderu Fontovi @msg every numbered name for {name} is taken in the document's folder svi numerisani nazivi za {name} su zauzeti u folderu dokumenta @msg No linked files to look for Nema povezanih datoteka za traženje -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} Ponovo povezano slika: {n}; {name} nije moguće ponovo povezati: {reason} @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` je referenca na korak {r}, koju razrješavaju samo `run` i `command_batch` @msg `ids` must be an array of object ids, not {v} `ids` mora biti niz ID-ova objekata, a ne {v} @msg `corners` must be an array of anchor indices, not {v} `corners` mora biti niz indeksa sidara, a ne {v} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 34d1de77f5..de41f9166f 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4947,7 +4947,6 @@ digits Malayalam Malaiàlam @msg control must be fillStroke, coloring, drawMode or screenMode control ha de ser fillStroke, coloring, drawMode o screenMode @msg Convert to Artboards: selection has no area Converteix en taulers: la selecció no té àrea @msg Convert to Shape: no rectangles or ellipses selected Converteix en forma: no s’ha seleccionat cap rectangle ni el·lipse -@msg Copied the CSS of {rules} object(s) S’ha copiat el CSS de {rules} objecte(s) @msg Copied the script report S’ha copiat l’informe de l’script @msg Corners edits the corners of a path Cantonades edita les cantonades d’un traçat @msg could not decode image: {0} no s’ha pogut descodificar la imatge: {0} @@ -4975,12 +4974,9 @@ digits Malayalam Malaiàlam @msg Divide Objects Below: select a path Divideix els objectes de sota: seleccioneu un traçat @msg Divide Objects Below: select exactly one path Divideix els objectes de sota: seleccioneu exactament un traçat @msg docking action contains an unknown panel or an excessive split path l’acció d’acoblament conté un panell desconegut o un camí de divisió excessiu -@msg Downloaded {_1} file(s) S’han baixat {_1} fitxer(s) @msg Downloaded {what} S’ha baixat {what} @msg Edit Original opens image and document files only; “{name}” is not one Edita l’original només obre fitxers d’imatge i de document; “{name}” no ho és @msg effect {k} is `{_1}`, not `{id}` l’efecte {k} és `{_1}`, no `{id}` -@msg Embedded {n} image(s) S’han incrustat {n} imatge(s) -@msg Embedded {n} image(s); {missing} missing: relink them first S’han incrustat {n} imatge(s); en falten {missing}: torneu-los a enllaçar primer @msg empty brush stroke traç de pinzell buit @msg empty cutter tallador buit @msg empty path traçat buit @@ -4992,10 +4988,8 @@ digits Malayalam Malaiàlam @msg Expand: no gradient fills Expandeix: no hi ha farciments de degradat @msg Expand: nothing to expand Expandeix: no hi ha res per expandir @msg Export cancelled Exportació cancel·lada -@msg Exported {count} file(s) to {folder} S’han exportat {count} fitxer(s) a {folder} @msg Exported {path} S’ha exportat {path} @msg Exported {what} S’ha exportat {what} -@msg Exported {what} with {_1} note(s): {first} S’ha exportat {what} amb {_1} nota(es): {first} @msg Exporting {_1} S’està exportant {_1} @msg file version {0} is newer than this VectorCraft supports ({VERSION}) la versió de fitxer {0} és més nova que la que admet aquest VectorCraft ({VERSION}) @msg First measured segment no longer exists El primer segment mesurat ja no existeix @@ -5320,10 +5314,26 @@ digits Malayalam Malaiàlam @msg recovery copy `{file}`: {e} còpia de recuperació `{file}`: {e} @msg Release Guides: no guides Allibera les guies: no hi ha guies @msg Release: no layer to put the rectangle in Allibera: no hi ha capa on posar el rectangle -@msg Relinked {_1} image(s) S’han tornat a enllaçar {_1} imatge(s) -@msg Relinked {n} image(s) S’han tornat a enllaçar {n} imatge(s) -@msg Relinked {n} image(s); not in that folder: {_1} S’han tornat a enllaçar {n} imatge(s); no són en aquesta carpeta: {_1} -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} S’han tornat a enllaçar {n} imatge(s); no s’ha pogut tornar a enllaçar {name}: {reason} +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first S’ha incrustat {n} imatge; en falten {missing}: torneu-los a enllaçar primer|S’han incrustat {n} imatges; en falten {missing}: torneu-los a enllaçar primer +@msgplural Embedded {n} image|Embedded {n} images S’ha incrustat {n} imatge|S’han incrustat {n} imatges +@msgplural Relinked {n} image|Relinked {n} images S’ha tornat a enllaçar {n} imatge|S’han tornat a enllaçar {n} imatges +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} S’ha tornat a enllaçar {n} imatge; no són en aquesta carpeta: {names}|S’han tornat a enllaçar {n} imatges; no són en aquesta carpeta: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} S’ha tornat a enllaçar {n} imatge; no s’ha pogut tornar a enllaçar {name}: {reason}|S’han tornat a enllaçar {n} imatges; no s’ha pogut tornar a enllaçar {name}: {reason} +@msgplural Updated {n} image|Updated {n} images S’ha actualitzat {n} imatge|S’han actualitzat {n} imatges +@msgplural Replaced {n} image|Replaced {n} images S’ha reemplaçat {n} imatge|S’han reemplaçat {n} imatges +@msgplural Broke {n} link|Broke {n} links S’ha trencat {n} enllaç|S’han trencat {n} enllaços +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first S’ha trencat {n} enllaç; no es poden llegir {missing}: torneu-los a enllaçar o actualitzeu-los primer|S’han trencat {n} enllaços; no es poden llegir {missing}: torneu-los a enllaçar o actualitzeu-los primer +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show aquí no es pot llegir {n} fitxer enllaçat: es mostra la seva previsualització|aquí no es poden llegir {n} fitxers enllaçats: es mostren les seves previsualitzacions +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes no s’ha pogut descodificar {n} imatge i es mostra com a caixa creuada|no s’han pogut descodificar {n} imatges i es mostren com a caixes creuades +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} imatge enllaçada ha canviat al disc: Actualitza els enllaços mostra la versió nova|{n} imatges enllaçades han canviat al disc: Actualitza els enllaços mostra les versions noves +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk S’ha actualitzat {n} fitxer enllaçat que ha canviat al disc|S’han actualitzat {n} fitxers enllaçats que han canviat al disc +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} S’ha exportat {what} amb {n} nota: {first}|S’ha exportat {what} amb {n} notes: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} fitxer de tipus de lletra ja és a {folder}|{n} fitxers de tipus de lletra ja són a {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} fitxer de tipus de lletra ja és a {folder}; {failed} no s’han pogut afegir: {reason}|{n} fitxers de tipus de lletra ja són a {folder}; {failed} no s’han pogut afegir: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font aquí no hi ha disponible {n} tipus de lletra: el seu text es mostra amb un altre tipus de lletra|aquí no hi ha disponibles {n} tipus de lletra: el seu text es mostra amb un altre tipus de lletra +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects S’ha copiat el CSS de {n} objecte|S’ha copiat el CSS de {n} objectes +@msgplural Downloaded {n} file|Downloaded {n} files S’ha baixat {n} fitxer|S’han baixat {n} fitxers +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} S’ha exportat {n} fitxer a {folder}|S’han exportat {n} fitxers a {folder} @msg Reload the page to go on (changes not saved yet may be lost). Recarrega la pàgina per continuar (els canvis encara no desats es poden perdre). @msg Replace Spine: select a blend and a path Substitueix l’espina: selecciona una fusió i un traçat @msg replace: the object to replace was changed or deleted replace: l’objecte que s’havia de substituir s’ha canviat o suprimit @@ -5576,8 +5586,6 @@ digits Malayalam Malaiàlam @msg unknown workspace (one of {_1}) espai de treball desconegut (un de {_1}) @msg unsupported native docking operation operació d’acoblament nadiua no compatible @msg unsupported: {0} no compatible: {0} -@msg Updated {_1} image(s) S’han actualitzat {_1} imatge(s) -@msg Updated {_1} linked file(s) changed on disk S’han actualitzat {_1} fitxer(s) enllaçat(s) que han canviat al disc @msg variables are locked les variables estan blocades @msg variables that aren't text were left out: {kinds} les variables que no són text s’han omès: {kinds} @msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft no cerca a les carpetes d’altres aplicacions ni del sistema: {path} @@ -5606,8 +5614,6 @@ digits Malayalam Malaiàlam @msg {_1} is already used by {_2} {_1} ja el fa servir {_2} @msg {_1} is an exporter (File › Export › Export As…) {_1} és un exportador (Fitxer › Exporta › Exporta com a…) @msg {_1} is reserved by the system {_1} està reservat pel sistema -@msg {_1} linked file(s) can't be read here: their previews show aquí no es poden llegir {_1} fitxer(s) enllaçat(s): es mostren les seves previsualitzacions -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} imatge(s) enllaçada(es) han canviat al disc: Actualitza els enllaços mostra les versions noves @msg {_1}: not saved, so not closed {_1}: no s’ha desat, així que no s’ha tancat @msg {bpp}-bit bitmaps can't be read els mapes de bits de {bpp} bits no es poden llegir @msg {command} didn't create an object {command} no ha creat cap objecte @@ -5629,9 +5635,6 @@ digits Malayalam Malaiàlam @msg {name}: CRC mismatch {name}: CRC no coincideix @msg {name}: no local header {name}: no hi ha capçalera local @msg {name}: no such recovery entry {name}: no hi ha cap entrada de recuperació d’aquest tipus -@msg {n} font file(s) are now in {folder} {n} fitxer(s) de tipus de lletra ja són a {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} fitxer(s) de tipus de lletra ja són a {folder}; {failed} no s’han pogut afegir: {reason} -@msg {n} font(s) aren't available here: their text shows in another font aquí no hi ha disponibles {n} tipus de lletra: el seu text es mostra amb un altre tipus de lletra @msg {path} can't be found: relink it first no es pot trobar {path}: torna a enllaçar-lo primer @msg {path} is not a folder {path} no és una carpeta @msg {path}: no file system here (pass dataBase64 to open; omit the path to get dataBase64) {path}: aquí no hi ha cap sistema de fitxers (passa dataBase64 per obrir; omet el camí per obtenir dataBase64) @@ -5639,7 +5642,6 @@ digits Malayalam Malaiàlam @msg {path}: {e} {path}: {e} @msg {status} ({e}) {status} ({e}) @msg {tool} isn't in a toolbar group of several tools {tool} no forma part d’un grup de diverses eines a la barra d’eines -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes no s’han pogut descodificar {undecoded} imatge(s) i es mostren com a caixes creuades @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees «{_1}» demana un pressupost elevat (cada execució fins a {minutes} minuts i {times} vegades les instruccions habituals): instal·la’l amb `allowHeavy: true` quan l’usuari hi estigui d’acord @msg “{name}” is not a file «{name}» no és un fitxer axis Both Tots dos diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index fc059b4408..9f5b98c5e3 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -674,7 +674,6 @@ Links Propojení @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? Na disku se změnil {n} propojený obrázek. Zobrazit novou verzi?|Na disku se změnily {n} propojené obrázky. Zobrazit nové verze?|Na disku se změnilo {n} propojených obrázků. Zobrazit nové verze? Update Changed Links Aktualizovat změněná propojení -@msg Updated {_1} linked file(s) changed on disk Aktualizováno propojených souborů změněných na disku: {_1} Magic Wand Kouzelná hůlka Navigator Navigátor Pattern Options Možnosti vzorku @@ -4209,7 +4208,6 @@ imageTrace Outline Obrys @msg Combine Slices: the slices have no bounds Spojit řezy: řezy nemají hranice @msg Convert to Artboards: selection has no area Převést na pracovní plochy: výběr nemá žádnou plochu @msg Convert to Shape: no rectangles or ellipses selected Převést na tvar: nejsou vybrány žádné obdélníky ani elipsy -@msg Copied the CSS of {rules} object(s) Zkopírováno CSS objektů: {rules} @msg Copied the script report Zpráva o skriptu zkopírována @msg Corners edits the corners of a path Rohy upravuje rohy cesty @msg Couldn't copy to the system clipboard: {e} Nelze kopírovat do systémové schránky: {e} @@ -4226,13 +4224,11 @@ imageTrace Outline Obrys @msg direct-select anchor points to cut at (not the end points of open paths) nástrojem Přímý výběr vyberte kotevní body, kde se má cesta rozdělit (ne koncové body otevřených cest) @msg Divide Objects Below: select a path Rozdělit objekty pod: vyberte cestu @msg Divide Objects Below: select exactly one path Rozdělit objekty pod: vyberte právě jednu cestu -@msg Downloaded {_1} file(s) Staženo souborů: {_1} @msg Downloaded {what} Staženo: {what} @msg Expand Appearance: the selection has a basic appearance Rozložit vzhled: výběr má základní vzhled @msg Expand: no brush strokes selected Rozložit: nejsou vybrány žádné tahy štětcem @msg Expand: no gradient fills Rozložit: žádné přechodové výplně @msg Expand: nothing to expand Rozložit: není co rozložit -@msg Exported {count} file(s) to {folder} Exportováno souborů: {count} do {folder} @msg Exported {path} Exportováno: {path} @msg Flatten Transparency: select objects to flatten Sloučit průhlednost: vyberte objekty ke sloučení @msg Flatten Transparency: {e} Sloučit průhlednost: {e} @@ -4790,9 +4786,6 @@ imageTrace Outline Obrys @msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` má {size} bajtů (limit {MAX_DOCUMENT_DATA}) @msg {_1} is already used by {_2} {_1} už používá {_2} @msg {_1} is reserved by the system Zkratku {_1} si vyhrazuje systém -@msg {_1} linked file(s) can't be read here: their previews show propojené soubory ({_1}) zde nelze přečíst: zobrazují se jejich náhledy -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes obrázky ({undecoded}) nelze dekódovat: zobrazují se jako přeškrtnuté rámečky -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions propojené obrázky ({_1}) se na disku změnily: nové verze zobrazí Aktualizovat propojení @msg {_1}: not saved, so not closed {_1}: neuloženo, proto nezavřeno @msg {bpp}-bit bitmaps can't be read {bpp}bitové bitmapy nelze přečíst @msg {command} didn't create an object {command} nevytvořil žádný objekt @@ -4812,7 +4805,6 @@ imageTrace Outline Obrys @msg Couldn't place {name}: {e} {name} nelze umístit: {e} @msg Couldn't paste from the clipboard: {e} Nelze vložit ze schránky: {e} @msg Saved {path} with {_1} note(s): {first} Uloženo: {path}, poznámky ({_1}): {first} -@msg Exported {what} with {_1} note(s): {first} Exportováno: {what}, poznámky ({_1}): {first} @msg Exported {what} Exportováno: {what} @msg Saved {n} files beside {path} Uloženo souborů: {n} vedle {path} @msg Saving Ukládání @@ -4823,12 +4815,26 @@ imageTrace Outline Obrys @msg Saving recovery data for {_1} Ukládání dat pro obnovení pro {_1} @msg Discarded {_1} recovered document(s) Zahozeno obnovených dokumentů: {_1} @msg Restored {_1} recovered document(s): save them to keep them Obnoveno dokumentů: {_1}; pokud je chcete zachovat, uložte je -@msg Embedded {n} image(s); {missing} missing: relink them first Vloženo obrázků: {n}; chybí {missing}: nejprve je znovu propojte -@msg Embedded {n} image(s) Vloženo obrázků: {n} -@msg Relinked {_1} image(s) Znovu propojeno obrázků: {_1} -@msg Relinked {n} image(s) Znovu propojeno obrázků: {n} -@msg Relinked {n} image(s); not in that folder: {_1} Znovu propojeno obrázků: {n}; nejsou v dané složce: {_1} -@msg Updated {_1} image(s) Aktualizováno obrázků: {_1} +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Vložen {n} obrázek; chybí {missing}: nejprve je znovu propojte|Vloženy {n} obrázky; chybí {missing}: nejprve je znovu propojte|Vloženo {n} obrázků; chybí {missing}: nejprve je znovu propojte +@msgplural Embedded {n} image|Embedded {n} images Vložen {n} obrázek|Vloženy {n} obrázky|Vloženo {n} obrázků +@msgplural Relinked {n} image|Relinked {n} images Znovu propojen {n} obrázek|Znovu propojeny {n} obrázky|Znovu propojeno {n} obrázků +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} Znovu propojen {n} obrázek; nejsou v dané složce: {names}|Znovu propojeny {n} obrázky; nejsou v dané složce: {names}|Znovu propojeno {n} obrázků; nejsou v dané složce: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} Znovu propojen {n} obrázek; nepodařilo se znovu propojit {name}: {reason}|Znovu propojeny {n} obrázky; nepodařilo se znovu propojit {name}: {reason}|Znovu propojeno {n} obrázků; nepodařilo se znovu propojit {name}: {reason} +@msgplural Updated {n} image|Updated {n} images Aktualizován {n} obrázek|Aktualizovány {n} obrázky|Aktualizováno {n} obrázků +@msgplural Replaced {n} image|Replaced {n} images Nahrazen {n} obrázek|Nahrazeny {n} obrázky|Nahrazeno {n} obrázků +@msgplural Broke {n} link|Broke {n} links Zrušeno {n} propojení|Zrušena {n} propojení|Zrušeno {n} propojení +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first Zrušeno {n} propojení; {missing} nelze přečíst: nejprve je znovu propojte nebo aktualizujte|Zrušena {n} propojení; {missing} nelze přečíst: nejprve je znovu propojte nebo aktualizujte|Zrušeno {n} propojení; {missing} nelze přečíst: nejprve je znovu propojte nebo aktualizujte +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} propojený soubor zde nelze přečíst: zobrazuje se jeho náhled|{n} propojené soubory zde nelze přečíst: zobrazují se jejich náhledy|{n} propojených souborů zde nelze přečíst: zobrazují se jejich náhledy +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes {n} obrázek nelze dekódovat: zobrazuje se jako přeškrtnutý rámeček|{n} obrázky nelze dekódovat: zobrazují se jako přeškrtnuté rámečky|{n} obrázků nelze dekódovat: zobrazují se jako přeškrtnuté rámečky +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions Na disku se změnil {n} propojený obrázek: novou verzi zobrazí Aktualizovat propojení|Na disku se změnily {n} propojené obrázky: nové verze zobrazí Aktualizovat propojení|Na disku se změnilo {n} propojených obrázků: nové verze zobrazí Aktualizovat propojení +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Aktualizován {n} propojený soubor změněný na disku|Aktualizovány {n} propojené soubory změněné na disku|Aktualizováno {n} propojených souborů změněných na disku +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Exportováno: {what}, {n} poznámka: {first}|Exportováno: {what}, {n} poznámky: {first}|Exportováno: {what}, {n} poznámek: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} soubor písma je nyní ve složce {folder}|{n} soubory písem jsou nyní ve složce {folder}|{n} souborů písem je nyní ve složce {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} soubor písma je nyní ve složce {folder}; nepodařilo se přidat {failed}: {reason}|{n} soubory písem jsou nyní ve složce {folder}; nepodařilo se přidat {failed}: {reason}|{n} souborů písem je nyní ve složce {folder}; nepodařilo se přidat {failed}: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} písmo zde není k dispozici: jeho text se zobrazuje jiným písmem|{n} písma zde nejsou k dispozici: jejich text se zobrazuje jiným písmem|{n} písem zde není k dispozici: jejich text se zobrazuje jiným písmem +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Zkopírováno CSS {n} objektu|Zkopírováno CSS {n} objektů|Zkopírováno CSS {n} objektů +@msgplural Downloaded {n} file|Downloaded {n} files Stažen {n} soubor|Staženy {n} soubory|Staženo {n} souborů +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Exportován {n} soubor do {folder}|Exportovány {n} soubory do {folder}|Exportováno {n} souborů do {folder} @msg Unembedded to {_1} Vložení zrušeno, uloženo do: {_1} @msg Reset {_1} Obnoveno: {_1} @msg Sent to {_1} Odesláno do {_1} @@ -4880,9 +4886,6 @@ imageTrace Outline Obrys @msg every search thread stopped on an internal error (please report this bug) všechna vlákna hledání se zastavila na vnitřní chybě (nahlaste prosím tuto chybu) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it složka Fonts VectorCraftu zde není nastavena: nastavuje ji desktopová aplikace a vectorcraft-cli @msg choose the font files to add vyberte soubory písem, které chcete přidat -@msg {n} font file(s) are now in {folder} soubory písem ({n}) jsou nyní ve složce {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} soubory písem ({n}) jsou nyní ve složce {folder}; nepodařilo se přidat {failed}: {reason} -@msg {n} font(s) aren't available here: their text shows in another font písma ({n}) zde nejsou k dispozici: jejich text se zobrazuje jiným písmem @msg not a file nejde o soubor @msg not a font file nejde o soubor písma @msg that document is no longer open tento dokument už není otevřen @@ -4891,7 +4894,6 @@ imageTrace Outline Obrys @msg every numbered name for it is taken in the Fonts folder ve složce Fonts jsou obsazena všechna číslovaná jména pro tento soubor @msg every numbered name for {name} is taken in the document's folder ve složce dokumentu jsou obsazena všechna číslovaná jména pro {name} @msg No linked files to look for Žádné propojené soubory k vyhledání -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} Znovu propojeno obrázků: {n}; nepodařilo se znovu propojit {name}: {reason} @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` je odkaz na krok {r}, který vyhodnocují jen `run` a `command_batch` @msg `ids` must be an array of object ids, not {v} `ids` musí být pole ID objektů, ne {v} @msg `corners` must be an array of anchor indices, not {v} `corners` musí být pole indexů kotevních bodů, ne {v} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 690b2699b0..3d74e590bd 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -626,7 +626,6 @@ Links Links @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} linket billede er ændret på disken. Vis den nye version?|{n} linkede billeder er ændret på disken. Vis de nye versioner? Update Changed Links Opdatér ændrede links -@msg Updated {_1} linked file(s) changed on disk Opdaterede {_1} linket fil(er) ændret på disken Magic Wand Magisk tryllestav Navigator Navigator Pattern Options Mønsterindstillinger @@ -3923,7 +3922,6 @@ imageTrace Outline Kontur @msg Combine Slices: the slices have no bounds Kombinér udsnit: udsnittene har ingen grænser @msg Convert to Artboards: selection has no area Konvertér til tegneflader: markeringen har intet areal @msg Convert to Shape: no rectangles or ellipses selected Konvertér til figur: ingen rektangler eller ellipser er markeret -@msg Copied the CSS of {rules} object(s) Kopierede CSS fra {rules} objekt(er) @msg Copied the script report Kopierede scriptrapporten @msg Corners edits the corners of a path Hjørner redigerer hjørnerne på en kurve @msg Couldn't copy to the system clipboard: {e} Kunne ikke kopiere til systemets udklipsholder: {e} @@ -3940,13 +3938,11 @@ imageTrace Outline Kontur @msg direct-select anchor points to cut at (not the end points of open paths) direkte-markér ankerpunkter, der skal skæres i (ikke endepunkterne på åbne kurver) @msg Divide Objects Below: select a path Opdel objekter nedenunder: markér en kurve @msg Divide Objects Below: select exactly one path Opdel objekter nedenunder: markér præcis én kurve -@msg Downloaded {_1} file(s) Downloadede {_1} fil(er) @msg Downloaded {what} Downloadede {what} @msg Expand Appearance: the selection has a basic appearance Udvid udseende: markeringen har et grundlæggende udseende @msg Expand: no brush strokes selected Udvid: ingen penselstrøg er markeret @msg Expand: no gradient fills Udvid: ingen gradientfyld @msg Expand: nothing to expand Udvid: intet at udvide -@msg Exported {count} file(s) to {folder} Eksporterede {count} fil(er) til {folder} @msg Exported {path} Eksporterede {path} @msg Flatten Transparency: select objects to flatten Fladgør gennemsigtighed: markér objekter, der skal fladgøres @msg Flatten Transparency: {e} Fladgør gennemsigtighed: {e} @@ -4448,8 +4444,6 @@ imageTrace Outline Kontur @msg {_1} is a live effect (Effect › Plug-ins) {_1} er en live-effekt (Effekt › Plug-ins) @msg {_1} is already used by {_2} {_1} bruges allerede af {_2} @msg {_1} is reserved by the system {_1} er reserveret af systemet -@msg {_1} linked file(s) can't be read here: their previews show {_1} linket(e) fil(er) kan ikke læses her: deres forhåndsvisninger vises -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} linket(e) billede(r) er ændret på disken: Opdatér links viser de nye versioner @msg {_1}: not saved, so not closed {_1}: ikke gemt, derfor ikke lukket @msg {bpp}-bit bitmaps can't be read {bpp}-bit bitmaps kan ikke læses @msg {command} didn't create an object {command} oprettede ikke et objekt @@ -4469,7 +4463,6 @@ imageTrace Outline Kontur @msg Couldn't place {name}: {e} Kunne ikke placere {name}: {e} @msg Couldn't paste from the clipboard: {e} Kunne ikke indsætte fra udklipsholderen: {e} @msg Saved {path} with {_1} note(s): {first} Gemte {path} med {_1} note(r): {first} -@msg Exported {what} with {_1} note(s): {first} Eksporterede {what} med {_1} note(r): {first} @msg Exported {what} Eksporterede {what} @msg Saved {n} files beside {path} Gemte {n} filer ved siden af {path} @msg Saving Gemmer @@ -4480,12 +4473,26 @@ imageTrace Outline Kontur @msg Saving recovery data for {_1} Gemmer gendannelsesdata for {_1} @msg Discarded {_1} recovered document(s) Forkastede {_1} gendannet(e) dokument(er) @msg Restored {_1} recovered document(s): save them to keep them Genvandt {_1} gendannet(e) dokument(er): gem dem for at beholde dem -@msg Embedded {n} image(s); {missing} missing: relink them first Indlejrede {n} billede(r); {missing} mangler: link dem igen først -@msg Embedded {n} image(s) Indlejrede {n} billede(r) -@msg Relinked {_1} image(s) Linkede {_1} billede(r) igen -@msg Relinked {n} image(s) Linkede {n} billede(r) igen -@msg Relinked {n} image(s); not in that folder: {_1} Linkede {n} billede(r) igen; ikke i den mappe: {_1} -@msg Updated {_1} image(s) Opdaterede {_1} billede(r) +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Indlejrede {n} billede; {missing} mangler: link dem igen først|Indlejrede {n} billeder; {missing} mangler: link dem igen først +@msgplural Embedded {n} image|Embedded {n} images Indlejrede {n} billede|Indlejrede {n} billeder +@msgplural Relinked {n} image|Relinked {n} images Linkede {n} billede igen|Linkede {n} billeder igen +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} Linkede {n} billede igen; ikke i den mappe: {names}|Linkede {n} billeder igen; ikke i den mappe: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} Linkede {n} billede igen; {name} kunne ikke linkes igen: {reason}|Linkede {n} billeder igen; {name} kunne ikke linkes igen: {reason} +@msgplural Updated {n} image|Updated {n} images Opdaterede {n} billede|Opdaterede {n} billeder +@msgplural Replaced {n} image|Replaced {n} images Erstattede {n} billede|Erstattede {n} billeder +@msgplural Broke {n} link|Broke {n} links Brød {n} sammenkædning|Brød {n} sammenkædninger +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first Brød {n} sammenkædning; {missing} kan ikke læses: link dem igen eller opdatér dem først|Brød {n} sammenkædninger; {missing} kan ikke læses: link dem igen eller opdatér dem først +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} linket fil kan ikke læses her: dens forhåndsvisning vises|{n} linkede filer kan ikke læses her: deres forhåndsvisninger vises +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes {n} billede kunne ikke afkodes og vises som en overkrydset boks|{n} billeder kunne ikke afkodes og vises som overkrydsede bokse +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} linket billede er ændret på disken: Opdatér links viser den nye version|{n} linkede billeder er ændret på disken: Opdatér links viser de nye versioner +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Opdaterede {n} linket fil ændret på disken|Opdaterede {n} linkede filer ændret på disken +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Eksporterede {what} med {n} note: {first}|Eksporterede {what} med {n} noter: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} skrifttypefil er nu i {folder}|{n} skrifttypefiler er nu i {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} skrifttypefil er nu i {folder}; {failed} kunne ikke tilføjes: {reason}|{n} skrifttypefiler er nu i {folder}; {failed} kunne ikke tilføjes: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} skrifttype er ikke tilgængelig her: teksten vises i en anden skrifttype|{n} skrifttyper er ikke tilgængelige her: teksten vises i en anden skrifttype +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Kopierede CSS fra {n} objekt|Kopierede CSS fra {n} objekter +@msgplural Downloaded {n} file|Downloaded {n} files Downloadede {n} fil|Downloadede {n} filer +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Eksporterede {n} fil til {folder}|Eksporterede {n} filer til {folder} @msg Unembedded to {_1} Fjernede indlejring til {_1} @msg Reset {_1} Nulstillede {_1} @msg Sent to {_1} Sendte til {_1} @@ -4535,9 +4542,6 @@ imageTrace Outline Kontur @msg every search thread stopped on an internal error (please report this bug) alle søgetråde stoppede ved en intern fejl (rapportér venligst denne programfejl) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it VectorCrafts Fonts-mappe er ikke angivet her: skrivebordsprogrammet og vectorcraft-cli angiver den @msg choose the font files to add vælg de skrifttypefiler, der skal tilføjes -@msg {n} font file(s) are now in {folder} {n} skrifttypefil(er) er nu i {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} skrifttypefil(er) er nu i {folder}; {failed} kunne ikke tilføjes: {reason} -@msg {n} font(s) aren't available here: their text shows in another font {n} skrifttype(r) er ikke tilgængelig(e) her: teksten vises i en anden skrifttype @msg not a file ikke en fil @msg not a font file ikke en skrifttypefil @msg that document is no longer open dokumentet er ikke længere åbent @@ -4546,7 +4550,6 @@ imageTrace Outline Kontur @msg every numbered name for it is taken in the Fonts folder alle nummererede navne til den er optaget i Fonts-mappen @msg every numbered name for {name} is taken in the document's folder alle nummererede navne til {name} er optaget i dokumentets mappe @msg No linked files to look for Ingen linkede filer at lede efter -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} Linkede {n} billede(r) igen; {name} kunne ikke linkes igen: {reason} @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` er trinreferencen {r}, som kun `run` og `command_batch` fortolker @msg `ids` must be an array of object ids, not {v} `ids` skal være et array af objekt-id'er, ikke {v} @msg `corners` must be an array of anchor indices, not {v} `corners` skal være et array af ankerindekser, ikke {v} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c6bf0ad760..c07cd79adc 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3820,7 +3820,6 @@ theme Appearance Erscheinungsbild @msg Combine Slices: the slices have no bounds Slices kombinieren: Die Slices haben keine Begrenzung @msg Convert to Artboards: selection has no area In Zeichenflächen umwandeln: Die Auswahl hat keine Fläche @msg Convert to Shape: no rectangles or ellipses selected In Form umwandeln: keine Rechtecke oder Ellipsen ausgewählt -@msg Copied the CSS of {rules} object(s) CSS von {rules} Objekt(en) kopiert @msg Copied the script report Skriptbericht kopiert @msg Corners edits the corners of a path „Ecken“ bearbeitet die Ecken eines Pfads @msg Couldn't copy to the system clipboard: {e} In die Systemzwischenablage konnte nicht kopiert werden: {e} @@ -3837,13 +3836,11 @@ theme Appearance Erscheinungsbild @msg direct-select anchor points to cut at (not the end points of open paths) wählen Sie mit der Direktauswahl die Ankerpunkte aus, an denen geschnitten werden soll (nicht die Endpunkte offener Pfade) @msg Divide Objects Below: select a path Darunterliegende Objekte aufteilen: Wählen Sie einen Pfad aus @msg Divide Objects Below: select exactly one path Darunterliegende Objekte aufteilen: Wählen Sie genau einen Pfad aus -@msg Downloaded {_1} file(s) {_1} Datei(en) heruntergeladen @msg Downloaded {what} {what} heruntergeladen @msg Expand Appearance: the selection has a basic appearance Aussehen umwandeln: Die Auswahl hat ein einfaches Aussehen @msg Expand: no brush strokes selected Umwandeln: keine Pinselkonturen ausgewählt @msg Expand: no gradient fills Umwandeln: keine Verlaufsflächen @msg Expand: nothing to expand Umwandeln: nichts umzuwandeln -@msg Exported {count} file(s) to {folder} {count} Datei(en) nach {folder} exportiert @msg Exported {path} {path} exportiert @msg Flatten Transparency: select objects to flatten Transparenz reduzieren: Wählen Sie die zu reduzierenden Objekte aus @msg Flatten Transparency: {e} Transparenz reduzieren: {e} @@ -4404,9 +4401,6 @@ theme Appearance Erscheinungsbild @msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` ist {size} Byte groß (Grenze {MAX_DOCUMENT_DATA}) @msg {_1} is already used by {_2} {_1} wird bereits von {_2} verwendet @msg {_1} is reserved by the system {_1} ist vom System reserviert -@msg {_1} linked file(s) can't be read here: their previews show {_1} verknüpfte Datei(en) können hier nicht gelesen werden: Ihre Vorschauen werden angezeigt -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes {undecoded} Bild(er) konnten nicht dekodiert werden und werden als durchgekreuzte Rahmen angezeigt -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} verknüpfte(s) Bild(er) wurde(n) auf dem Datenträger geändert: „Verknüpfungen aktualisieren“ zeigt die neuen Versionen @msg {_1}: not saved, so not closed {_1}: nicht gespeichert, daher nicht geschlossen @msg {bpp}-bit bitmaps can't be read {bpp}-Bit-Bitmaps können nicht gelesen werden @msg {command} didn't create an object {command} hat kein Objekt erstellt @@ -4426,7 +4420,6 @@ theme Appearance Erscheinungsbild @msg Couldn't place {name}: {e} {name} konnte nicht platziert werden: {e} @msg Couldn't paste from the clipboard: {e} Aus der Zwischenablage konnte nicht eingefügt werden: {e} @msg Saved {path} with {_1} note(s): {first} {path} mit {_1} Hinweis(en) gespeichert: {first} -@msg Exported {what} with {_1} note(s): {first} {what} mit {_1} Hinweis(en) exportiert: {first} @msg Exported {what} {what} exportiert @msg Saved {n} files beside {path} {n} Dateien neben {path} gespeichert @msg Saving Wird gespeichert @@ -4437,12 +4430,26 @@ theme Appearance Erscheinungsbild @msg Saving recovery data for {_1} Wiederherstellungsdaten für {_1} werden gespeichert @msg Discarded {_1} recovered document(s) {_1} wiederhergestellte(s) Dokument(e) verworfen @msg Restored {_1} recovered document(s): save them to keep them {_1} wiederhergestellte(s) Dokument(e) geöffnet: Speichern Sie sie, um sie zu behalten -@msg Embedded {n} image(s); {missing} missing: relink them first {n} Bild(er) eingebettet; {missing} fehlen: Verknüpfen Sie sie zuerst neu -@msg Embedded {n} image(s) {n} Bild(er) eingebettet -@msg Relinked {_1} image(s) {_1} Bild(er) neu verknüpft -@msg Relinked {n} image(s) {n} Bild(er) neu verknüpft -@msg Relinked {n} image(s); not in that folder: {_1} {n} Bild(er) neu verknüpft; nicht in diesem Ordner: {_1} -@msg Updated {_1} image(s) {_1} Bild(er) aktualisiert +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} Bild eingebettet; {missing} fehlen: Verknüpfen Sie sie zuerst neu|{n} Bilder eingebettet; {missing} fehlen: Verknüpfen Sie sie zuerst neu +@msgplural Embedded {n} image|Embedded {n} images {n} Bild eingebettet|{n} Bilder eingebettet +@msgplural Relinked {n} image|Relinked {n} images {n} Bild neu verknüpft|{n} Bilder neu verknüpft +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} {n} Bild neu verknüpft; nicht in diesem Ordner: {names}|{n} Bilder neu verknüpft; nicht in diesem Ordner: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} {n} Bild neu verknüpft; {name} konnte nicht neu verknüpft werden: {reason}|{n} Bilder neu verknüpft; {name} konnte nicht neu verknüpft werden: {reason} +@msgplural Updated {n} image|Updated {n} images {n} Bild aktualisiert|{n} Bilder aktualisiert +@msgplural Replaced {n} image|Replaced {n} images {n} Bild ersetzt|{n} Bilder ersetzt +@msgplural Broke {n} link|Broke {n} links {n} Verknüpfung aufgehoben|{n} Verknüpfungen aufgehoben +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first {n} Verknüpfung aufgehoben; {missing} können nicht gelesen werden: Verknüpfen oder aktualisieren Sie sie zuerst|{n} Verknüpfungen aufgehoben; {missing} können nicht gelesen werden: Verknüpfen oder aktualisieren Sie sie zuerst +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} verknüpfte Datei kann hier nicht gelesen werden: Ihre Vorschau wird angezeigt|{n} verknüpfte Dateien können hier nicht gelesen werden: Ihre Vorschauen werden angezeigt +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes {n} Bild konnte nicht dekodiert werden und wird als durchgekreuzter Rahmen angezeigt|{n} Bilder konnten nicht dekodiert werden und werden als durchgekreuzte Rahmen angezeigt +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} verknüpftes Bild wurde auf dem Datenträger geändert: „Verknüpfungen aktualisieren“ zeigt die neue Version|{n} verknüpfte Bilder wurden auf dem Datenträger geändert: „Verknüpfungen aktualisieren“ zeigt die neuen Versionen +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk {n} auf dem Datenträger geänderte verknüpfte Datei aktualisiert|{n} auf dem Datenträger geänderte verknüpfte Dateien aktualisiert +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} {what} mit {n} Hinweis exportiert: {first}|{what} mit {n} Hinweisen exportiert: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} Schriftdatei liegt jetzt in {folder}|{n} Schriftdateien liegen jetzt in {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} Schriftdatei liegt jetzt in {folder}; {failed} konnten nicht hinzugefügt werden: {reason}|{n} Schriftdateien liegen jetzt in {folder}; {failed} konnten nicht hinzugefügt werden: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} Schrift ist hier nicht verfügbar: Ihr Text wird in einer anderen Schrift angezeigt|{n} Schriften sind hier nicht verfügbar: Ihr Text wird in einer anderen Schrift angezeigt +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects CSS von {n} Objekt kopiert|CSS von {n} Objekten kopiert +@msgplural Downloaded {n} file|Downloaded {n} files {n} Datei heruntergeladen|{n} Dateien heruntergeladen +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} Datei nach {folder} exportiert|{n} Dateien nach {folder} exportiert @msg Unembedded to {_1} Einbettung aufgehoben, gespeichert unter {_1} @msg Reset {_1} {_1} zurückgesetzt @msg Sent to {_1} An {_1} gesendet @@ -4494,9 +4501,6 @@ theme Appearance Erscheinungsbild @msg every search thread stopped on an internal error (please report this bug) alle Such-Threads wurden mit einem internen Fehler beendet (bitte melden Sie diesen Fehler) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it der Schriftenordner von VectorCraft ist hier nicht festgelegt: Die Desktop-App und vectorcraft-cli legen ihn fest @msg choose the font files to add wählen Sie die Schriftdateien aus, die hinzugefügt werden sollen -@msg {n} font file(s) are now in {folder} {n} Schriftdatei(en) liegen jetzt in {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} Schriftdatei(en) liegen jetzt in {folder}; {failed} konnten nicht hinzugefügt werden: {reason} -@msg {n} font(s) aren't available here: their text shows in another font {n} Schrift(en) sind hier nicht verfügbar: Ihr Text wird in einer anderen Schrift angezeigt @msg not a file keine Datei @msg not a font file keine Schriftdatei @msg that document is no longer open dieses Dokument ist nicht mehr geöffnet @@ -4505,7 +4509,6 @@ theme Appearance Erscheinungsbild @msg every numbered name for it is taken in the Fonts folder alle nummerierten Namen dafür sind im Schriftenordner bereits vergeben @msg every numbered name for {name} is taken in the document's folder alle nummerierten Namen für {name} sind im Ordner des Dokuments bereits vergeben @msg No linked files to look for Keine verknüpften Dateien zum Suchen -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} {n} Bild(er) neu verknüpft; {name} konnte nicht neu verknüpft werden: {reason} # The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages. Services Dienste @@ -4601,7 +4604,6 @@ theme Appearance Erscheinungsbild # Linked files changed on disk. Update Changed Links Geänderte Verknüpfungen aktualisieren @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} verknüpftes Bild wurde auf dem Datenträger geändert. Neue Version anzeigen?|{n} verknüpfte Bilder wurden auf dem Datenträger geändert. Neue Versionen anzeigen? -@msg Updated {_1} linked file(s) changed on disk {_1} auf dem Datenträger geänderte verknüpfte Datei(en) aktualisiert # Window: the system's title bar (Windows, Linux). System Title Bar Systemtitelleiste # Brush Options: Scatter, Art and Pattern brushes. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index f5c0ccedc0..61d187c200 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2122,7 +2122,6 @@ axis Both Και τα δύο @msg Combine Slices: the slices have no bounds Συνδυασμός τομών: οι τομές δεν έχουν όρια @msg Convert to Artboards: selection has no area Μετατροπή σε πίνακες σχεδίασης: η επιλογή δεν έχει επιφάνεια @msg Convert to Shape: no rectangles or ellipses selected Μετατροπή σε σχήμα: δεν έχουν επιλεγεί ορθογώνια ή ελλείψεις -@msg Copied the CSS of {rules} object(s) Αντιγράφηκαν οι κανόνες CSS από {rules} αντικείμενα @msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε @msg Corners edits the corners of a path Η εντολή Γωνίες επεξεργάζεται τις γωνίες μιας διαδρομής @msg Couldn't copy to the system clipboard: {e} Δεν ήταν δυνατή η αντιγραφή στο πρόχειρο συστήματος: {e} @@ -2139,13 +2138,11 @@ axis Both Και τα δύο @msg direct-select anchor points to cut at (not the end points of open paths) Επιλέξτε άμεσα τα σημεία αγκύρωσης όπου θα γίνει η αποκοπή (όχι τα τελικά σημεία ανοιχτών διαδρομών) @msg Divide Objects Below: select a path Διαίρεση αντικειμένων από κάτω: επιλέξτε μια διαδρομή @msg Divide Objects Below: select exactly one path Διαίρεση αντικειμένων από κάτω: επιλέξτε ακριβώς μία διαδρομή -@msg Downloaded {_1} file(s) Έγινε λήψη {_1} αρχείων @msg Downloaded {what} Έγινε λήψη του {what} @msg Expand Appearance: the selection has a basic appearance Επέκταση εμφάνισης: η επιλογή έχει βασική εμφάνιση @msg Expand: no brush strokes selected Επέκταση: δεν επιλέχθηκαν πινελιές @msg Expand: no gradient fills Επέκταση: δεν υπάρχουν γεμίσματα ντεγκραντέ @msg Expand: nothing to expand Επέκταση: δεν υπάρχει περιεχόμενο προς επέκταση -@msg Exported {count} file(s) to {folder} Εξήχθησαν {count} αρχεία στον φάκελο {folder} @msg Exported {path} Εξήχθη το {path} @msg Flatten Transparency: select objects to flatten Ισοπέδωση διαφάνειας: επιλέξτε αντικείμενα προς ισοπέδωση @msg Flatten Transparency: {e} Ισοπέδωση διαφάνειας: {e} @@ -4437,10 +4434,6 @@ digits Malayalam Μαλαγιάλαμ @msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) το `documentData` έχει {size} byte (όριο {MAX_DOCUMENT_DATA}) @msg {_1} is already used by {_2} το {_1} χρησιμοποιείται ήδη από το {_2} @msg {_1} is reserved by the system Το {_1} είναι δεσμευμένο από το σύστημα -@msg {_1} linked file(s) can't be read here: their previews show {_1} συνδεδεμένα αρχεία δεν μπορούν να διαβαστούν εδώ: εμφανίζονται οι προεπισκοπήσεις τους -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes {undecoded} εικόνες δεν ήταν δυνατό να αποκωδικοποιηθούν: εμφανίζονται ως πλαίσια με σταυρό -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} συνδεδεμένες εικόνες άλλαξαν στον δίσκο: η Ενημέρωση συνδέσμων εμφανίζει τις νέες εκδόσεις -@msg Updated {_1} linked file(s) changed on disk Ενημερώθηκαν {_1} συνδεδεμένα αρχεία που άλλαξαν στον δίσκο @msg {_1}: not saved, so not closed {_1}: δεν αποθηκεύτηκε και επομένως δεν έκλεισε @msg {bpp}-bit bitmaps can't be read δεν μπορούν να διαβαστούν bitmap {bpp} bit @msg {command} didn't create an object η εντολή {command} δεν δημιούργησε αντικείμενο @@ -4460,7 +4453,6 @@ digits Malayalam Μαλαγιάλαμ @msg Couldn't place {name}: {e} Δεν ήταν δυνατή η τοποθέτηση του {name}: {e} @msg Couldn't paste from the clipboard: {e} Δεν ήταν δυνατή η επικόλληση από το πρόχειρο: {e} @msg Saved {path} with {_1} note(s): {first} Αποθηκεύτηκε το {path} με {_1} σημειώσεις: {first} -@msg Exported {what} with {_1} note(s): {first} Εξήχθη το {what} με {_1} σημειώσεις: {first} @msg Exported {what} Εξήχθη: {what} @msg Saved {n} files beside {path} Αποθηκεύτηκαν {n} αρχεία δίπλα στο {path} @msg Saving Αποθήκευση σε εξέλιξη @@ -4471,12 +4463,26 @@ digits Malayalam Μαλαγιάλαμ @msg Saving recovery data for {_1} Αποθήκευση δεδομένων ανάκτησης για {_1} @msg Discarded {_1} recovered document(s) Απορρίφθηκαν {_1} ανακτημένα έγγραφα @msg Restored {_1} recovered document(s): save them to keep them Επαναφέρθηκαν {_1} ανακτημένα έγγραφα: αποθηκεύστε τα για να διατηρηθούν -@msg Embedded {n} image(s); {missing} missing: relink them first Ενσωματώθηκαν {n} εικόνες· λείπουν {missing}: επανασυνδέστε τις πρώτα -@msg Embedded {n} image(s) Ενσωματώθηκαν {n} εικόνες -@msg Relinked {_1} image(s) Επανασυνδέθηκαν {_1} εικόνες -@msg Relinked {n} image(s) Επανασυνδέθηκαν {n} εικόνες -@msg Relinked {n} image(s); not in that folder: {_1} Επανασυνδέθηκαν {n} εικόνες· δεν βρέθηκαν στον φάκελο: {_1} -@msg Updated {_1} image(s) Ενημερώθηκαν {_1} εικόνες +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Ενσωματώθηκε {n} εικόνα· λείπουν {missing}: επανασυνδέστε τις πρώτα|Ενσωματώθηκαν {n} εικόνες· λείπουν {missing}: επανασυνδέστε τις πρώτα +@msgplural Embedded {n} image|Embedded {n} images Ενσωματώθηκε {n} εικόνα|Ενσωματώθηκαν {n} εικόνες +@msgplural Relinked {n} image|Relinked {n} images Επανασυνδέθηκε {n} εικόνα|Επανασυνδέθηκαν {n} εικόνες +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} Επανασυνδέθηκε {n} εικόνα· δεν βρέθηκαν στον φάκελο: {names}|Επανασυνδέθηκαν {n} εικόνες· δεν βρέθηκαν στον φάκελο: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} Επανασυνδέθηκε {n} εικόνα· δεν ήταν δυνατή η επανασύνδεση της {name}: {reason}|Επανασυνδέθηκαν {n} εικόνες· δεν ήταν δυνατή η επανασύνδεση της {name}: {reason} +@msgplural Updated {n} image|Updated {n} images Ενημερώθηκε {n} εικόνα|Ενημερώθηκαν {n} εικόνες +@msgplural Replaced {n} image|Replaced {n} images Αντικαταστάθηκε {n} εικόνα|Αντικαταστάθηκαν {n} εικόνες +@msgplural Broke {n} link|Broke {n} links Καταργήθηκε {n} σύνδεση|Καταργήθηκαν {n} συνδέσεις +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first Καταργήθηκε {n} σύνδεση· δεν είναι δυνατή η ανάγνωση {missing}: επανασυνδέστε ή ενημερώστε τες πρώτα|Καταργήθηκαν {n} συνδέσεις· δεν είναι δυνατή η ανάγνωση {missing}: επανασυνδέστε ή ενημερώστε τες πρώτα +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} συνδεδεμένο αρχείο δεν μπορεί να διαβαστεί εδώ: εμφανίζεται η προεπισκόπησή του|{n} συνδεδεμένα αρχεία δεν μπορούν να διαβαστούν εδώ: εμφανίζονται οι προεπισκοπήσεις τους +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes {n} εικόνα δεν ήταν δυνατό να αποκωδικοποιηθεί: εμφανίζεται ως πλαίσιο με σταυρό|{n} εικόνες δεν ήταν δυνατό να αποκωδικοποιηθούν: εμφανίζονται ως πλαίσια με σταυρό +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} συνδεδεμένη εικόνα άλλαξε στον δίσκο: η Ενημέρωση συνδέσμων εμφανίζει τη νέα έκδοση|{n} συνδεδεμένες εικόνες άλλαξαν στον δίσκο: η Ενημέρωση συνδέσμων εμφανίζει τις νέες εκδόσεις +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Ενημερώθηκε {n} συνδεδεμένο αρχείο που άλλαξε στον δίσκο|Ενημερώθηκαν {n} συνδεδεμένα αρχεία που άλλαξαν στον δίσκο +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Εξήχθη το {what} με {n} σημείωση: {first}|Εξήχθη το {what} με {n} σημειώσεις: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} αρχείο γραμματοσειράς βρίσκεται πλέον στον φάκελο {folder}|{n} αρχεία γραμματοσειρών βρίσκονται πλέον στον φάκελο {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} αρχείο γραμματοσειράς βρίσκεται πλέον στον φάκελο {folder}· δεν ήταν δυνατή η προσθήκη {failed}: {reason}|{n} αρχεία γραμματοσειρών βρίσκονται πλέον στον φάκελο {folder}· δεν ήταν δυνατή η προσθήκη {failed}: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} γραμματοσειρά δεν είναι διαθέσιμη εδώ: το κείμενό της εμφανίζεται με άλλη γραμματοσειρά|{n} γραμματοσειρές δεν είναι διαθέσιμες εδώ: το κείμενό τους εμφανίζεται με άλλη γραμματοσειρά +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Αντιγράφηκαν οι κανόνες CSS από {n} αντικείμενο|Αντιγράφηκαν οι κανόνες CSS από {n} αντικείμενα +@msgplural Downloaded {n} file|Downloaded {n} files Έγινε λήψη {n} αρχείου|Έγινε λήψη {n} αρχείων +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Εξήχθη {n} αρχείο στον φάκελο {folder}|Εξήχθησαν {n} αρχεία στον φάκελο {folder} @msg Unembedded to {_1} Καταργήθηκε η ενσωμάτωση στο {_1} @msg Reset {_1} Επαναφορά {_1} @msg Sent to {_1} Στάλθηκε στο {_1} @@ -4528,9 +4534,6 @@ digits Malayalam Μαλαγιάλαμ @msg every search thread stopped on an internal error (please report this bug) όλα τα νήματα αναζήτησης σταμάτησαν λόγω εσωτερικού σφάλματος (αναφέρετε το πρόβλημα) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it ο φάκελος γραμματοσειρών του VectorCraft δεν έχει καθοριστεί εδώ: τον ορίζουν η εφαρμογή υπολογιστή και το vectorcraft-cli @msg choose the font files to add επιλέξτε τα αρχεία γραμματοσειρών που θέλετε να προσθέσετε -@msg {n} font file(s) are now in {folder} {n} αρχεία γραμματοσειρών βρίσκονται πλέον στον φάκελο {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} αρχεία γραμματοσειρών βρίσκονται πλέον στον φάκελο {folder}· δεν ήταν δυνατή η προσθήκη {failed}: {reason} -@msg {n} font(s) aren't available here: their text shows in another font {n} γραμματοσειρές δεν είναι διαθέσιμες εδώ: το κείμενό τους εμφανίζεται με άλλη γραμματοσειρά @msg not a file δεν είναι αρχείο @msg not a font file δεν είναι αρχείο γραμματοσειράς @msg that document is no longer open αυτό το έγγραφο δεν είναι πλέον ανοιχτό @@ -4539,7 +4542,6 @@ digits Malayalam Μαλαγιάλαμ @msg every numbered name for it is taken in the Fonts folder όλα τα αριθμημένα ονόματά του χρησιμοποιούνται ήδη στον φάκελο γραμματοσειρών @msg every numbered name for {name} is taken in the document's folder όλα τα αριθμημένα ονόματα για το {name} χρησιμοποιούνται ήδη στον φάκελο εγγράφου @msg No linked files to look for Δεν υπάρχουν συνδεδεμένα αρχεία για αναζήτηση -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} Επανασυνδέθηκαν {n} εικόνες· δεν ήταν δυνατή η επανασύνδεση της {name}: {reason} Hide VectorCraft Απόκρυψη VectorCraft Bring All to Front Μεταφορά όλων στο προσκήνιο Break Link Κατάργηση σύνδεσης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 8587501613..2884b973cc 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3900,7 +3900,6 @@ axis Both Ambos @msg Combine Slices: the slices have no bounds Combinar sectores: los sectores no tienen límites @msg Convert to Artboards: selection has no area Convertir en mesas de trabajo: la selección no tiene área @msg Convert to Shape: no rectangles or ellipses selected Convertir en forma: no hay rectángulos ni elipses seleccionados -@msg Copied the CSS of {rules} object(s) Se copió el CSS de {rules} objeto(s) @msg Copied the script report Se copió el informe del script @msg Corners edits the corners of a path Esquinas edita las esquinas de un trazado @msg Couldn't copy to the system clipboard: {e} No se pudo copiar al portapapeles del sistema: {e} @@ -3917,13 +3916,11 @@ axis Both Ambos @msg direct-select anchor points to cut at (not the end points of open paths) selecciona con Selección directa los puntos de ancla en los que cortar (no los puntos finales de trazados abiertos) @msg Divide Objects Below: select a path Dividir objetos inferiores: selecciona un trazado @msg Divide Objects Below: select exactly one path Dividir objetos inferiores: selecciona exactamente un trazado -@msg Downloaded {_1} file(s) Se descargaron {_1} archivo(s) @msg Downloaded {what} Se descargó {what} @msg Expand Appearance: the selection has a basic appearance Expandir apariencia: la selección tiene una apariencia básica @msg Expand: no brush strokes selected Expandir: no hay trazos de pincel seleccionados @msg Expand: no gradient fills Expandir: no hay rellenos de degradado @msg Expand: nothing to expand Expandir: no hay nada que expandir -@msg Exported {count} file(s) to {folder} Se exportaron {count} archivo(s) a {folder} @msg Exported {path} Se exportó {path} @msg Flatten Transparency: select objects to flatten Acoplar transparencia: selecciona los objetos que quieres acoplar @msg Flatten Transparency: {e} Acoplar transparencia: {e} @@ -4483,10 +4480,6 @@ axis Both Ambos @msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` ocupa {size} bytes (límite {MAX_DOCUMENT_DATA}) @msg {_1} is already used by {_2} {_1} ya lo usa {_2} @msg {_1} is reserved by the system {_1} está reservado por el sistema -@msg {_1} linked file(s) can't be read here: their previews show aquí no se pueden leer {_1} archivo(s) vinculado(s): se muestran sus previsualizaciones -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes no se pudieron descodificar {undecoded} imagen(es): se muestran como recuadros tachados -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} imagen(es) vinculada(s) cambiaron en el disco: Actualizar vínculos muestra las versiones nuevas -@msg Updated {_1} linked file(s) changed on disk Se actualizaron {_1} archivo(s) vinculado(s) que cambiaron en el disco @msg {_1}: not saved, so not closed {_1}: no se guardó, así que no se cerró @msg {bpp}-bit bitmaps can't be read no se pueden leer mapas de bits de {bpp} bits @msg {command} didn't create an object {command} no creó ningún objeto @@ -4506,7 +4499,6 @@ axis Both Ambos @msg Couldn't place {name}: {e} No se pudo colocar {name}: {e} @msg Couldn't paste from the clipboard: {e} No se pudo pegar desde el portapapeles: {e} @msg Saved {path} with {_1} note(s): {first} Se guardó {path} con {_1} nota(s): {first} -@msg Exported {what} with {_1} note(s): {first} Se exportó {what} con {_1} nota(s): {first} @msg Exported {what} Se exportó {what} @msg Saved {n} files beside {path} Se guardaron {n} archivos junto a {path} @msg Saving Guardando @@ -4517,12 +4509,26 @@ axis Both Ambos @msg Saving recovery data for {_1} Guardando datos de recuperación de {_1} @msg Discarded {_1} recovered document(s) Se descartaron {_1} documento(s) recuperado(s) @msg Restored {_1} recovered document(s): save them to keep them Se restauraron {_1} documento(s) recuperado(s): guárdalos para conservarlos -@msg Embedded {n} image(s); {missing} missing: relink them first Se incrustaron {n} imagen(es); faltan {missing}: vuelve a vincularlas primero -@msg Embedded {n} image(s) Se incrustaron {n} imagen(es) -@msg Relinked {_1} image(s) Se volvieron a vincular {_1} imagen(es) -@msg Relinked {n} image(s) Se volvieron a vincular {n} imagen(es) -@msg Relinked {n} image(s); not in that folder: {_1} Se volvieron a vincular {n} imagen(es); no están en esa carpeta: {_1} -@msg Updated {_1} image(s) Se actualizaron {_1} imagen(es) +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Se incrustó {n} imagen; faltan {missing}: vuelve a vincularlas primero|Se incrustaron {n} imágenes; faltan {missing}: vuelve a vincularlas primero +@msgplural Embedded {n} image|Embedded {n} images Se incrustó {n} imagen|Se incrustaron {n} imágenes +@msgplural Relinked {n} image|Relinked {n} images Se volvió a vincular {n} imagen|Se volvieron a vincular {n} imágenes +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} Se volvió a vincular {n} imagen; no están en esa carpeta: {names}|Se volvieron a vincular {n} imágenes; no están en esa carpeta: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} Se volvió a vincular {n} imagen; no se pudo volver a vincular {name}: {reason}|Se volvieron a vincular {n} imágenes; no se pudo volver a vincular {name}: {reason} +@msgplural Updated {n} image|Updated {n} images Se actualizó {n} imagen|Se actualizaron {n} imágenes +@msgplural Replaced {n} image|Replaced {n} images Se reemplazó {n} imagen|Se reemplazaron {n} imágenes +@msgplural Broke {n} link|Broke {n} links Se rompió {n} vínculo|Se rompieron {n} vínculos +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first Se rompió {n} vínculo; no se pueden leer {missing}: vuelve a vincularlos o actualízalos primero|Se rompieron {n} vínculos; no se pueden leer {missing}: vuelve a vincularlos o actualízalos primero +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show aquí no se puede leer {n} archivo vinculado: se muestra su previsualización|aquí no se pueden leer {n} archivos vinculados: se muestran sus previsualizaciones +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes no se pudo descodificar {n} imagen: se muestra como un recuadro tachado|no se pudieron descodificar {n} imágenes: se muestran como recuadros tachados +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} imagen vinculada cambió en el disco: Actualizar vínculos muestra la versión nueva|{n} imágenes vinculadas cambiaron en el disco: Actualizar vínculos muestra las versiones nuevas +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Se actualizó {n} archivo vinculado que cambió en el disco|Se actualizaron {n} archivos vinculados que cambiaron en el disco +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Se exportó {what} con {n} nota: {first}|Se exportó {what} con {n} notas: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} archivo de fuentes ahora está en {folder}|{n} archivos de fuentes ahora están en {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} archivo de fuentes ahora está en {folder}; no se pudieron agregar {failed}: {reason}|{n} archivos de fuentes ahora están en {folder}; no se pudieron agregar {failed}: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font aquí no está disponible {n} fuente: su texto se muestra con otra fuente|aquí no están disponibles {n} fuentes: su texto se muestra con otra fuente +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Se copió el CSS de {n} objeto|Se copió el CSS de {n} objetos +@msgplural Downloaded {n} file|Downloaded {n} files Se descargó {n} archivo|Se descargaron {n} archivos +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Se exportó {n} archivo a {folder}|Se exportaron {n} archivos a {folder} @msg Unembedded to {_1} Se desincrustó en {_1} @msg Reset {_1} Se restableció {_1} @msg Sent to {_1} Se envió a {_1} @@ -4574,9 +4580,6 @@ axis Both Ambos @msg every search thread stopped on an internal error (please report this bug) todos los hilos de búsqueda se detuvieron por un error interno (informa de este error) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it La carpeta Fonts de VectorCraft no está configurada aquí: la configuran la aplicación de escritorio y vectorcraft-cli @msg choose the font files to add elige los archivos de fuentes que quieres agregar -@msg {n} font file(s) are now in {folder} {n} archivo(s) de fuentes ahora están en {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} archivo(s) de fuentes ahora están en {folder}; no se pudieron agregar {failed}: {reason} -@msg {n} font(s) aren't available here: their text shows in another font aquí no están disponibles {n} fuente(s): su texto se muestra con otra fuente @msg not a file no es un archivo @msg not a font file no es un archivo de fuente @msg that document is no longer open ese documento ya no está abierto @@ -4585,7 +4588,6 @@ axis Both Ambos @msg every numbered name for it is taken in the Fonts folder todos los nombres numerados para él ya existen en la carpeta Fonts @msg every numbered name for {name} is taken in the document's folder todos los nombres numerados para {name} ya existen en la carpeta del documento @msg No linked files to look for No hay archivos vinculados que buscar -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} Se volvieron a vincular {n} imagen(es); no se pudo volver a vincular {name}: {reason} # The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages. Services Servicios diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index f1aa49a30a..0cfe70c464 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -665,7 +665,6 @@ Links Linkit @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} linkitetty kuva muuttui levyllä. Näytetäänkö uusi versio?|{n} linkitettyä kuvaa muuttui levyllä. Näytetäänkö uudet versiot? Update Changed Links Päivitä muuttuneet linkit -@msg Updated {_1} linked file(s) changed on disk Päivitettiin {_1} levyllä muuttunutta linkitettyä tiedostoa Magic Wand Taikasauva Navigator Navigaattori Pattern Options Kuvion asetukset @@ -4123,7 +4122,6 @@ imageTrace Outline Ääriviiva @msg Combine Slices: the slices have no bounds Yhdistä viipaleet: viipaleilla ei ole rajoja @msg Convert to Artboards: selection has no area Muunna piirtoalustoiksi: valinnalla ei ole pinta-alaa @msg Convert to Shape: no rectangles or ellipses selected Muunna muodoksi: suorakulmioita tai ellipsejä ei ole valittu -@msg Copied the CSS of {rules} object(s) Kopioitiin {rules} objektin CSS @msg Copied the script report Komentosarjan raportti kopioitiin @msg Corners edits the corners of a path Kulmat-toiminto muokkaa polun kulmia @msg Couldn't copy to the system clipboard: {e} Järjestelmän leikepöydälle ei voitu kopioida: {e} @@ -4140,13 +4138,11 @@ imageTrace Outline Ääriviiva @msg direct-select anchor points to cut at (not the end points of open paths) valitse suoravalinnalla ankkuripisteet, joista leikataan (ei avoimien polkujen päätepisteitä) @msg Divide Objects Below: select a path Jaa alla olevat objektit: valitse polku @msg Divide Objects Below: select exactly one path Jaa alla olevat objektit: valitse tasan yksi polku -@msg Downloaded {_1} file(s) Ladattiin {_1} tiedosto(a) @msg Downloaded {what} Ladattiin {what} @msg Expand Appearance: the selection has a basic appearance Laajenna ulkoasu: valinnalla on perusulkoasu @msg Expand: no brush strokes selected Laajenna: sivellinviivoja ei ole valittu @msg Expand: no gradient fills Laajenna: ei liukuväritäyttöjä @msg Expand: nothing to expand Laajenna: ei laajennettavaa -@msg Exported {count} file(s) to {folder} Vietiin {count} tiedosto(a) kansioon {folder} @msg Exported {path} Vietiin {path} @msg Flatten Transparency: select objects to flatten Litistä läpinäkyvyys: valitse litistettävät objektit @msg Flatten Transparency: {e} Litistä läpinäkyvyys: {e} @@ -4692,9 +4688,6 @@ imageTrace Outline Ääriviiva @msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` on {size} tavua (raja {MAX_DOCUMENT_DATA}) @msg {_1} is already used by {_2} {_1} on jo käytössä kohteella {_2} @msg {_1} is reserved by the system {_1} on järjestelmän varaama -@msg {_1} linked file(s) can't be read here: their previews show {_1} linkitettyä tiedostoa ei voi lukea täällä: niiden esikatselut näytetään -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes {undecoded} kuvaa ei voitu purkaa: ne näkyvät ristillä merkittyinä ruutuina -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} linkitettyä kuvaa muuttui levyllä: Päivitä linkit näyttää uudet versiot @msg {_1}: not saved, so not closed {_1}: ei tallennettu, joten ei suljettu @msg {bpp}-bit bitmaps can't be read {bpp}-bittisiä bittikarttoja ei voi lukea @msg {command} didn't create an object {command} ei luonut objektia @@ -4714,7 +4707,6 @@ imageTrace Outline Ääriviiva @msg Couldn't place {name}: {e} Kohdetta {name} ei voitu sijoittaa: {e} @msg Couldn't paste from the clipboard: {e} Leikepöydältä ei voitu liittää: {e} @msg Saved {path} with {_1} note(s): {first} Tallennettiin {path}, {_1} huomautus(ta): {first} -@msg Exported {what} with {_1} note(s): {first} Vietiin {what}, {_1} huomautus(ta): {first} @msg Exported {what} Vietiin {what} @msg Saved {n} files beside {path} Tallennettiin {n} tiedostoa kohteen {path} viereen @msg Saving Tallennetaan @@ -4725,12 +4717,26 @@ imageTrace Outline Ääriviiva @msg Saving recovery data for {_1} Tallennetaan palautustietoja: {_1} @msg Discarded {_1} recovered document(s) Hylättiin {_1} palautettu(a) asiakirja(a) @msg Restored {_1} recovered document(s): save them to keep them Palautettiin {_1} asiakirja(a): tallenna ne säilyttääksesi ne -@msg Embedded {n} image(s); {missing} missing: relink them first Upotettiin {n} kuva(a); {missing} puuttuu: linkitä ne ensin uudelleen -@msg Embedded {n} image(s) Upotettiin {n} kuva(a) -@msg Relinked {_1} image(s) Linkitettiin uudelleen {_1} kuva(a) -@msg Relinked {n} image(s) Linkitettiin uudelleen {n} kuva(a) -@msg Relinked {n} image(s); not in that folder: {_1} Linkitettiin uudelleen {n} kuva(a); ei kyseisessä kansiossa: {_1} -@msg Updated {_1} image(s) Päivitettiin {_1} kuva(a) +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Upotettiin {n} kuva; {missing} puuttuu: linkitä ne ensin uudelleen|Upotettiin {n} kuvaa; {missing} puuttuu: linkitä ne ensin uudelleen +@msgplural Embedded {n} image|Embedded {n} images Upotettiin {n} kuva|Upotettiin {n} kuvaa +@msgplural Relinked {n} image|Relinked {n} images Linkitettiin uudelleen {n} kuva|Linkitettiin uudelleen {n} kuvaa +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} Linkitettiin uudelleen {n} kuva; ei kyseisessä kansiossa: {names}|Linkitettiin uudelleen {n} kuvaa; ei kyseisessä kansiossa: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} Linkitettiin uudelleen {n} kuva; kohdetta {name} ei voitu linkittää uudelleen: {reason}|Linkitettiin uudelleen {n} kuvaa; kohdetta {name} ei voitu linkittää uudelleen: {reason} +@msgplural Updated {n} image|Updated {n} images Päivitettiin {n} kuva|Päivitettiin {n} kuvaa +@msgplural Replaced {n} image|Replaced {n} images Korvattiin {n} kuva|Korvattiin {n} kuvaa +@msgplural Broke {n} link|Broke {n} links Katkaistiin {n} linkki|Katkaistiin {n} linkkiä +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first Katkaistiin {n} linkki; {missing} ei voi lukea: linkitä ne uudelleen tai päivitä ne ensin|Katkaistiin {n} linkkiä; {missing} ei voi lukea: linkitä ne uudelleen tai päivitä ne ensin +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} linkitetty tiedosto ei ole luettavissa täällä: sen esikatselu näytetään|{n} linkitettyä tiedostoa ei voi lukea täällä: niiden esikatselut näytetään +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes {n} kuvaa ei voitu purkaa: se näkyy ristillä merkittynä ruutuna|{n} kuvaa ei voitu purkaa: ne näkyvät ristillä merkittyinä ruutuina +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} linkitetty kuva muuttui levyllä: Päivitä linkit näyttää uuden version|{n} linkitettyä kuvaa muuttui levyllä: Päivitä linkit näyttää uudet versiot +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Päivitettiin {n} levyllä muuttunut linkitetty tiedosto|Päivitettiin {n} levyllä muuttunutta linkitettyä tiedostoa +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Vietiin {what}, {n} huomautus: {first}|Vietiin {what}, {n} huomautusta: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} fonttitiedosto on nyt kansiossa {folder}|{n} fonttitiedostoa on nyt kansiossa {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} fonttitiedosto on nyt kansiossa {folder}; {failed} ei voitu lisätä: {reason}|{n} fonttitiedostoa on nyt kansiossa {folder}; {failed} ei voitu lisätä: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} fontti ei ole käytettävissä täällä: sen teksti näytetään toisella fontilla|{n} fonttia ei ole käytettävissä täällä: niiden teksti näytetään toisella fontilla +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Kopioitiin {n} objektin CSS|Kopioitiin {n} objektin CSS +@msgplural Downloaded {n} file|Downloaded {n} files Ladattiin {n} tiedosto|Ladattiin {n} tiedostoa +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Vietiin {n} tiedosto kansioon {folder}|Vietiin {n} tiedostoa kansioon {folder} @msg Unembedded to {_1} Upotus purettiin kohteeseen {_1} @msg Reset {_1} Palautettiin oletukseksi {_1} @msg Sent to {_1} Lähetettiin kohteeseen {_1} @@ -4782,9 +4788,6 @@ imageTrace Outline Ääriviiva @msg every search thread stopped on an internal error (please report this bug) jokainen hakusäie pysähtyi sisäiseen virheeseen (ilmoita tästä virheestä) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it VectorCraftin Fonts-kansiota ei ole määritetty täällä: työpöytäsovellus ja vectorcraft-cli määrittävät sen @msg choose the font files to add valitse lisättävät fonttitiedostot -@msg {n} font file(s) are now in {folder} {n} fonttitiedosto(a) on nyt kansiossa {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} fonttitiedosto(a) on nyt kansiossa {folder}; {failed} ei voitu lisätä: {reason} -@msg {n} font(s) aren't available here: their text shows in another font {n} fontti(a) ei ole käytettävissä täällä: niiden teksti näytetään toisella fontilla @msg not a file ei tiedosto @msg not a font file ei fonttitiedosto @msg that document is no longer open kyseinen asiakirja ei ole enää auki @@ -4793,7 +4796,6 @@ imageTrace Outline Ääriviiva @msg every numbered name for it is taken in the Fonts folder kaikki sen numeroidut nimet ovat jo käytössä Fonts-kansiossa @msg every numbered name for {name} is taken in the document's folder kaikki kohteen {name} numeroidut nimet ovat jo käytössä asiakirjan kansiossa @msg No linked files to look for Ei etsittäviä linkitettyjä tiedostoja -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} Linkitettiin uudelleen {n} kuva(a); kohdetta {name} ei voitu linkittää uudelleen: {reason} @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` on vaiheviittaus {r}, jonka vain `run` ja `command_batch` ratkaisevat @msg `ids` must be an array of object ids, not {v} `ids` on oltava objektitunnusten taulukko, ei {v} @msg `corners` must be an array of anchor indices, not {v} `corners` on oltava ankkuri-indeksien taulukko, ei {v} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index fc18c34aac..9ea315ee73 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3896,7 +3896,6 @@ axis Both Les deux @msg Combine Slices: the slices have no bounds Combiner les tranches : les tranches n’ont pas de limites @msg Convert to Artboards: selection has no area Convertir en plans de travail : la sélection n’a pas de surface @msg Convert to Shape: no rectangles or ellipses selected Convertir en forme : aucun rectangle ni aucune ellipse sélectionné -@msg Copied the CSS of {rules} object(s) CSS de {rules} objet(s) copié @msg Copied the script report Rapport du script copié @msg Corners edits the corners of a path Angles modifie les angles d’un tracé @msg Couldn't copy to the system clipboard: {e} Impossible de copier dans le presse-papiers du système : {e} @@ -3913,13 +3912,11 @@ axis Both Les deux @msg direct-select anchor points to cut at (not the end points of open paths) sélectionnez avec l’outil Sélection directe les points d’ancrage où couper (pas les extrémités des tracés ouverts) @msg Divide Objects Below: select a path Diviser les objets inférieurs : sélectionnez un tracé @msg Divide Objects Below: select exactly one path Diviser les objets inférieurs : sélectionnez exactement un tracé -@msg Downloaded {_1} file(s) {_1} fichier(s) téléchargé(s) @msg Downloaded {what} {what} téléchargé @msg Expand Appearance: the selection has a basic appearance Décomposer l’aspect : la sélection a un aspect de base @msg Expand: no brush strokes selected Décomposer : aucun contour de forme sélectionné @msg Expand: no gradient fills Décomposer : aucun fond en dégradé @msg Expand: nothing to expand Décomposer : rien à décomposer -@msg Exported {count} file(s) to {folder} {count} fichier(s) exporté(s) vers {folder} @msg Exported {path} {path} exporté @msg Flatten Transparency: select objects to flatten Aplatir la transparence : sélectionnez les objets à aplatir @msg Flatten Transparency: {e} Aplatir la transparence : {e} @@ -4479,10 +4476,6 @@ axis Both Les deux @msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` fait {size} octets (limite {MAX_DOCUMENT_DATA}) @msg {_1} is already used by {_2} {_1} est déjà utilisé par {_2} @msg {_1} is reserved by the system {_1} est réservé par le système -@msg {_1} linked file(s) can't be read here: their previews show {_1} fichier(s) lié(s) illisible(s) ici : leurs aperçus sont affichés -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes {undecoded} image(s) impossible(s) à décoder, affichée(s) sous forme de cadres barrés d’une croix -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} image(s) liée(s) modifiée(s) sur le disque : Mettre à jour les liens affiche les nouvelles versions -@msg Updated {_1} linked file(s) changed on disk {_1} fichier(s) lié(s) modifié(s) sur le disque mis à jour @msg {_1}: not saved, so not closed {_1} : non enregistré, donc non fermé @msg {bpp}-bit bitmaps can't be read impossible de lire les images bitmap en {bpp} bits @msg {command} didn't create an object {command} n’a créé aucun objet @@ -4502,7 +4495,6 @@ axis Both Les deux @msg Couldn't place {name}: {e} Impossible d’importer {name} : {e} @msg Couldn't paste from the clipboard: {e} Impossible de coller depuis le presse-papiers : {e} @msg Saved {path} with {_1} note(s): {first} {path} enregistré avec {_1} remarque(s) : {first} -@msg Exported {what} with {_1} note(s): {first} {what} exporté avec {_1} remarque(s) : {first} @msg Exported {what} {what} exporté @msg Saved {n} files beside {path} {n} fichiers enregistrés à côté de {path} @msg Saving Enregistrement @@ -4513,12 +4505,26 @@ axis Both Les deux @msg Saving recovery data for {_1} Enregistrement des données de récupération de {_1} @msg Discarded {_1} recovered document(s) {_1} document(s) récupéré(s) supprimé(s) @msg Restored {_1} recovered document(s): save them to keep them {_1} document(s) récupéré(s) restauré(s) : enregistrez-les pour les conserver -@msg Embedded {n} image(s); {missing} missing: relink them first {n} image(s) incorporée(s) ; {missing} manquante(s) : rétablissez d’abord leurs liens -@msg Embedded {n} image(s) {n} image(s) incorporée(s) -@msg Relinked {_1} image(s) Lien rétabli pour {_1} image(s) -@msg Relinked {n} image(s) Lien rétabli pour {n} image(s) -@msg Relinked {n} image(s); not in that folder: {_1} Lien rétabli pour {n} image(s) ; absentes de ce dossier : {_1} -@msg Updated {_1} image(s) {_1} image(s) mise(s) à jour +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} image incorporée ; il en manque {missing} : rétablissez d’abord leurs liens|{n} images incorporées ; il en manque {missing} : rétablissez d’abord leurs liens +@msgplural Embedded {n} image|Embedded {n} images {n} image incorporée|{n} images incorporées +@msgplural Relinked {n} image|Relinked {n} images Lien rétabli pour {n} image|Lien rétabli pour {n} images +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} Lien rétabli pour {n} image ; absentes de ce dossier : {names}|Lien rétabli pour {n} images ; absentes de ce dossier : {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} Lien rétabli pour {n} image, mais impossible de lier à nouveau {name} ({reason})|Lien rétabli pour {n} images, mais impossible de lier à nouveau {name} ({reason}) +@msgplural Updated {n} image|Updated {n} images {n} image mise à jour|{n} images mises à jour +@msgplural Replaced {n} image|Replaced {n} images {n} image remplacée|{n} images remplacées +@msgplural Broke {n} link|Broke {n} links {n} lien rompu|{n} liens rompus +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first {n} lien rompu ; lecture impossible pour {missing} : rétablissez ou mettez d’abord à jour leurs liens|{n} liens rompus ; lecture impossible pour {missing} : rétablissez ou mettez d’abord à jour leurs liens +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} fichier lié illisible ici : son aperçu est affiché|{n} fichiers liés illisibles ici : leurs aperçus sont affichés +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes {n} image impossible à décoder, affichée sous forme de cadre barré d’une croix|{n} images impossibles à décoder, affichées sous forme de cadres barrés d’une croix +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} image liée modifiée sur le disque : Mettre à jour les liens affiche la nouvelle version|{n} images liées modifiées sur le disque : Mettre à jour les liens affiche les nouvelles versions +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk {n} fichier lié modifié sur le disque mis à jour|{n} fichiers liés modifiés sur le disque mis à jour +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} {what} exporté avec {n} remarque : {first}|{what} exporté avec {n} remarques : {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} fichier de polices se trouve maintenant dans {folder}|{n} fichiers de polices se trouvent maintenant dans {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} fichier de polices se trouve maintenant dans {folder} ; {failed} n’ont pas pu être ajoutés : {reason}|{n} fichiers de polices se trouvent maintenant dans {folder} ; {failed} n’ont pas pu être ajoutés : {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} police indisponible ici : son texte s’affiche dans une autre police|{n} polices indisponibles ici : leur texte s’affiche dans une autre police +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects CSS de {n} objet copié|CSS de {n} objets copié +@msgplural Downloaded {n} file|Downloaded {n} files {n} fichier téléchargé|{n} fichiers téléchargés +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} fichier exporté vers {folder}|{n} fichiers exportés vers {folder} @msg Unembedded to {_1} Incorporation annulée vers {_1} @msg Reset {_1} {_1} réinitialisé @msg Sent to {_1} Envoyé à {_1} @@ -4570,9 +4576,6 @@ axis Both Les deux @msg every search thread stopped on an internal error (please report this bug) tous les fils de recherche se sont arrêtés sur une erreur interne (veuillez signaler ce bogue) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it Le dossier Fonts de VectorCraft n’est pas défini ici : l’application de bureau et vectorcraft-cli le définissent @msg choose the font files to add choisissez les fichiers de polices à ajouter -@msg {n} font file(s) are now in {folder} {n} fichier(s) de polices se trouvent maintenant dans {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} fichier(s) de polices se trouvent maintenant dans {folder} ; {failed} n’ont pas pu être ajoutés : {reason} -@msg {n} font(s) aren't available here: their text shows in another font {n} police(s) indisponible(s) ici : leur texte s’affiche dans une autre police @msg not a file n’est pas un fichier @msg not a font file n’est pas un fichier de police @msg that document is no longer open ce document n’est plus ouvert @@ -4581,7 +4584,6 @@ axis Both Les deux @msg every numbered name for it is taken in the Fonts folder tous les noms numérotés pour ce fichier sont déjà pris dans le dossier Fonts @msg every numbered name for {name} is taken in the document's folder tous les noms numérotés pour {name} sont déjà pris dans le dossier du document @msg No linked files to look for Aucun fichier lié à rechercher -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} Lien rétabli pour {n} image(s), mais impossible de lier à nouveau {name} ({reason}) # The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages. Services Services diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9935eaa4af..cbc4ebf1ff 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4679,7 +4679,6 @@ imageTrace Outline Körvonal @msg compressed (RLE) bitmaps can't be read yet a tömörített (RLE) bitképek még nem olvashatók @msg Convert to Artboards: selection has no area Átalakítás rajztáblákká: a kijelölésnek nincs területe @msg Convert to Shape: no rectangles or ellipses selected Átalakítás alakzattá: nincs kijelölt téglalap vagy ellipszis -@msg Copied the CSS of {rules} object(s) CSS másolva, objektumok: {rules} @msg Copied the script report Szkriptjelentés másolva @msg Corners edits the corners of a path a Sarkok parancs egy útvonal sarkait szerkeszti @msg could not decode image: {0} a kép nem dekódolható: {0} @@ -4704,27 +4703,21 @@ imageTrace Outline Körvonal @msg Divide Objects Below: select a path Alatta lévő objektumok felosztása: jelölj ki egy útvonalat @msg Divide Objects Below: select exactly one path Alatta lévő objektumok felosztása: pontosan egy útvonalat jelölj ki @msg docking action contains an unknown panel or an excessive split path a dokkolási művelet ismeretlen panelt vagy túl hosszú felosztási útvonalat tartalmaz -@msg Downloaded {_1} file(s) Letöltött fájlok: {_1} @msg Downloaded {what} Letöltve: {what} @msg effect {k} is `{_1}`, not `{id}` az effektus ({k}) ez: `{_1}`, nem ez: `{id}` -@msg Embedded {n} image(s) Beágyazott képek: {n} -@msg Embedded {n} image(s); {missing} missing: relink them first Beágyazott képek: {n}; hiányzik: {missing}, ezeket előbb csatold újra @msg empty brush stroke üres ecsetvonás @msg empty cutter üres vágóobjektum @msg empty path üres útvonal @msg every numbered name for it is taken in the Fonts folder a Fonts mappában minden sorszámozott név foglalt hozzá @msg every numbered name for {name} is taken in the document's folder a dokumentum mappájában minden sorszámozott név foglalt: {name} @msg No linked files to look for Nincs keresendő csatolt fájl -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} Újracsatolt képek: {n}; nem sikerült újracsatolni: {name}: {reason} @msg every search thread stopped on an internal error (please report this bug) minden keresési szál belső hibával leállt (kérjük, jelentsd ezt a hibát) @msg Expand Appearance: the selection has a basic appearance Megjelenés kibontása: a kijelölésnek alapmegjelenése van @msg Expand: no brush strokes selected Kibontás: nincs kijelölt ecsetvonás @msg Expand: no gradient fills Kibontás: nincs színátmenetes kitöltés @msg Expand: nothing to expand Kibontás: nincs mit kibontani -@msg Exported {count} file(s) to {folder} Exportált fájlok: {count}, mappa: {folder} @msg Exported {path} Exportálva: {path} @msg Exported {what} Exportálva: {what} -@msg Exported {what} with {_1} note(s): {first} Exportálva: {what}; megjegyzések: {_1}, az első: {first} @msg Exporting {_1} Exportálás: {_1} @msg Packaging {_1} Csomagolás: {_1} @msg Placing {_1} Elhelyezés: {_1} @@ -5010,9 +5003,26 @@ imageTrace Outline Körvonal @msg recovery copy `{file}`: {e} helyreállítási másolat (`{file}`): {e} @msg Release Guides: no guides Segédvonalak visszaalakítása: nincs segédvonal @msg Release: no layer to put the rectangle in Megszüntetés: nincs réteg, amelybe a téglalap kerülhetne -@msg Relinked {_1} image(s) Újracsatolt képek: {_1} -@msg Relinked {n} image(s) Újracsatolt képek: {n} -@msg Relinked {n} image(s); not in that folder: {_1} Újracsatolt képek: {n}; nincs a mappában: {_1} +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Beágyazott képek: {n}; hiányzik: {missing}, ezeket előbb csatold újra +@msgplural Embedded {n} image|Embedded {n} images Beágyazott képek: {n} +@msgplural Relinked {n} image|Relinked {n} images Újracsatolt képek: {n} +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} Újracsatolt képek: {n}; nincs a mappában: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} Újracsatolt képek: {n}; nem sikerült újracsatolni: {name}: {reason} +@msgplural Updated {n} image|Updated {n} images Frissített képek: {n} +@msgplural Replaced {n} image|Replaced {n} images Lecserélt képek: {n} +@msgplural Broke {n} link|Broke {n} links Bontott csatolások: {n} +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first Bontott csatolások: {n}; nem olvasható: {missing}, ezeket előbb csatold újra vagy frissítsd +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show Itt nem olvasható csatolt fájlok: {n}; az előnézetük látszik +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes Nem dekódolható képek: {n}; áthúzott keretként látszanak +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions A lemezen módosult csatolt képek: {n}; a Csatolások frissítése az új változatokat mutatja +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Frissített, a lemezen módosult csatolt fájlok: {n} +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Exportálva: {what}; megjegyzések: {n}, az első: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} Betűtípusfájlok száma: {n}, mappa: {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} Betűtípusfájlok száma: {n}, mappa: {folder}; nem sikerült hozzáadni: {failed} ({reason}) +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font Nem elérhető betűtípusok: {n}; a szövegük más betűtípussal jelenik meg +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects CSS másolva, objektumok: {n} +@msgplural Downloaded {n} file|Downloaded {n} files Letöltött fájlok: {n} +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Exportált fájlok: {n}, mappa: {folder} @msg Reload the page to go on (changes not saved yet may be lost). A folytatáshoz töltsd újra az oldalt (a még nem mentett módosítások elveszhetnek). @msg Replace Spine: select a blend and a path Gerinc cseréje: jelölj ki egy összemosást és egy útvonalat @msg Reset {_1} Visszaállítva: {_1} @@ -5223,8 +5233,6 @@ imageTrace Outline Körvonal @msg unknown workspace (one of {_1}) ismeretlen munkaterület (ezek egyike lehet: {_1}) @msg unsupported native docking operation nem támogatott natív dokkolási művelet @msg unsupported: {0} nem támogatott: {0} -@msg Updated {_1} image(s) Frissített képek: {_1} -@msg Updated {_1} linked file(s) changed on disk Frissített, a lemezen módosult csatolt fájlok: {_1} @msg variables are locked a változók zárolva vannak @msg variables that aren't text were left out: {kinds} a nem szöveges változók kimaradtak: {kinds} @msg VectorCraft doesn't search other apps' or the system's folders: {path} a VectorCraft nem keres más alkalmazások és a rendszer mappáiban: {path} @@ -5253,9 +5261,6 @@ imageTrace Outline Körvonal @msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) a `documentData` mérete {size} bájt (korlát: {MAX_DOCUMENT_DATA}) @msg {_1} is already used by {_2} már foglalt: {_1} (használja: {_2}) @msg {_1} is reserved by the system A(z) {_1} a rendszer számára foglalt -@msg {_1} linked file(s) can't be read here: their previews show Itt nem olvasható csatolt fájlok: {_1}; az előnézetük látszik -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes Nem dekódolható képek: {undecoded}; áthúzott keretként látszanak -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions A lemezen módosult csatolt képek: {_1}; a Csatolások frissítése az új változatokat mutatja @msg {_1}: not saved, so not closed {_1}: nincs mentve, ezért nem záródott be @msg {bpp}-bit bitmaps can't be read ilyen bitmélységű bitkép nem olvasható: {bpp} @msg {command} didn't create an object a parancs nem hozott létre objektumot: {command} @@ -5270,9 +5275,6 @@ imageTrace Outline Körvonal @msg {name}: CRC mismatch {name}: CRC-eltérés @msg {name}: no local header {name}: nincs helyi fejléc @msg {name}: no such recovery entry {name}: nincs ilyen helyreállítási bejegyzés -@msg {n} font file(s) are now in {folder} Betűtípusfájlok száma: {n}, mappa: {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} Betűtípusfájlok száma: {n}, mappa: {folder}; nem sikerült hozzáadni: {failed} ({reason}) -@msg {n} font(s) aren't available here: their text shows in another font Nem elérhető betűtípusok: {n}; a szövegük más betűtípussal jelenik meg @msg {path} can't be found: relink it first nem található: {path}; előbb csatold újra @msg {path} is not a folder nem mappa: {path} @msg {path}: no file system here (pass dataBase64 to open; omit the path to get dataBase64) {path}: itt nincs fájlrendszer (megnyitáshoz add meg a dataBase64-et; az útvonal elhagyásával dataBase64-et kapsz) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 4ecabcc939..c960dd6ae5 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -626,7 +626,6 @@ Links Tautan @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} gambar tertaut di disk telah berubah. Tampilkan versi baru? Update Changed Links Perbarui tautan yang berubah -@msg Updated {_1} linked file(s) changed on disk Telah memperbarui {_1} berkas tertaut yang berubah di disk Magic Wand Tongkat ajaib Navigator Navigator Pattern Options Opsi pola @@ -3923,7 +3922,6 @@ imageTrace Outline Kontur @msg Combine Slices: the slices have no bounds Gabungkan irisan: irisan tidak memiliki batas @msg Convert to Artboards: selection has no area Konversi ke artboard: seleksi tidak memiliki area @msg Convert to Shape: no rectangles or ellipses selected Konversi ke bentuk: tidak ada persegi panjang atau elips yang dipilih -@msg Copied the CSS of {rules} object(s) Berhasil menyalin CSS dari {rules} objek @msg Copied the script report Berhasil menyalin laporan skrip @msg Corners edits the corners of a path Corners menyunting sudut jalur @msg Couldn't copy to the system clipboard: {e} Tidak dapat menyalin ke papan klip sistem: {e} @@ -3940,13 +3938,11 @@ imageTrace Outline Kontur @msg direct-select anchor points to cut at (not the end points of open paths) pilih langsung titik jangkar yang akan dipotong (bukan titik ujung jalur terbuka) @msg Divide Objects Below: select a path Bagi objek di bawah: pilih satu jalur @msg Divide Objects Below: select exactly one path Bagi objek di bawah: pilih tepat satu jalur -@msg Downloaded {_1} file(s) Berhasil mengunduh {_1} file @msg Downloaded {what} Berhasil mengunduh {what} @msg Expand Appearance: the selection has a basic appearance Perluas tampilan: seleksi memiliki tampilan dasar @msg Expand: no brush strokes selected Perluas: tidak ada sapuan kuas yang dipilih @msg Expand: no gradient fills Perluas: tidak ada isian gradien @msg Expand: nothing to expand Perluas: tidak ada yang dapat diperluas -@msg Exported {count} file(s) to {folder} Berhasil mengekspor {count} file ke {folder} @msg Exported {path} Berhasil mengekspor {path} @msg Flatten Transparency: select objects to flatten Ratakan transparansi: pilih objek yang akan diratakan @msg Flatten Transparency: {e} Ratakan transparansi: {e} @@ -4448,8 +4444,6 @@ imageTrace Outline Kontur @msg {_1} is a live effect (Effect › Plug-ins) {_1} adalah efek langsung (Efek › Plug-in) @msg {_1} is already used by {_2} {_1} sudah digunakan oleh {_2} @msg {_1} is reserved by the system {_1} dicadangkan oleh sistem -@msg {_1} linked file(s) can't be read here: their previews show {_1} berkas tertaut tidak dapat dibaca di sini: yang ditampilkan adalah pratinjaunya -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} gambar tertaut di disk telah berubah: Perbarui Tautan menampilkan versi barunya @msg {_1}: not saved, so not closed {_1}: tidak disimpan, sehingga tidak ditutup @msg {bpp}-bit bitmaps can't be read bitmap {bpp}-bit tidak dapat dibaca @msg {command} didn't create an object {command} tidak membuat objek @@ -4469,7 +4463,6 @@ imageTrace Outline Kontur @msg Couldn't place {name}: {e} Tidak dapat menempatkan {name}: {e} @msg Couldn't paste from the clipboard: {e} Tidak dapat menempel dari papan klip: {e} @msg Saved {path} with {_1} note(s): {first} {path} disimpan dengan {_1} catatan: {first} -@msg Exported {what} with {_1} note(s): {first} {what} diekspor dengan {_1} catatan: {first} @msg Exported {what} {what} diekspor @msg Saved {n} files beside {path} {n} berkas disimpan di sebelah {path} @msg Saving Menyimpan @@ -4480,12 +4473,26 @@ imageTrace Outline Kontur @msg Saving recovery data for {_1} Menyimpan data pemulihan untuk {_1} @msg Discarded {_1} recovered document(s) {_1} dokumen hasil pemulihan dibuang @msg Restored {_1} recovered document(s): save them to keep them {_1} dokumen hasil pemulihan dipulihkan: simpan agar tidak hilang -@msg Embedded {n} image(s); {missing} missing: relink them first {n} gambar tersemat; {missing} hilang: tautkan ulang dulu -@msg Embedded {n} image(s) {n} gambar tersemat -@msg Relinked {_1} image(s) {_1} gambar ditautkan ulang -@msg Relinked {n} image(s) {n} gambar ditautkan ulang -@msg Relinked {n} image(s); not in that folder: {_1} {n} gambar ditautkan ulang; tidak ada di folder tersebut: {_1} -@msg Updated {_1} image(s) {_1} gambar diperbarui +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} gambar tersemat; {missing} hilang: tautkan ulang dulu +@msgplural Embedded {n} image|Embedded {n} images {n} gambar tersemat +@msgplural Relinked {n} image|Relinked {n} images {n} gambar ditautkan ulang +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} {n} gambar ditautkan ulang; tidak ada di folder tersebut: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} {n} gambar ditautkan ulang; {name} tidak dapat ditautkan ulang: {reason} +@msgplural Updated {n} image|Updated {n} images {n} gambar diperbarui +@msgplural Replaced {n} image|Replaced {n} images {n} gambar diganti +@msgplural Broke {n} link|Broke {n} links {n} tautan diputus +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first {n} tautan diputus; {missing} tidak dapat dibaca: tautkan ulang atau perbarui dulu +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} berkas tertaut tidak dapat dibaca di sini: yang ditampilkan adalah pratinjaunya +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes {n} gambar tidak dapat didekode dan ditampilkan sebagai kotak bersilang +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} gambar tertaut di disk telah berubah: Perbarui Tautan menampilkan versi barunya +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Telah memperbarui {n} berkas tertaut yang berubah di disk +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} {what} diekspor dengan {n} catatan: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} berkas font kini berada di {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} berkas font kini berada di {folder}; {failed} tidak dapat ditambahkan: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} font tidak tersedia di sini: teksnya ditampilkan dalam font lain +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Berhasil menyalin CSS dari {n} objek +@msgplural Downloaded {n} file|Downloaded {n} files Berhasil mengunduh {n} file +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Berhasil mengekspor {n} file ke {folder} @msg Unembedded to {_1} Gambar tersemat dilepas ke {_1} @msg Reset {_1} {_1} diatur ulang @msg Sent to {_1} Dikirim ke {_1} @@ -4535,9 +4542,6 @@ imageTrace Outline Kontur @msg every search thread stopped on an internal error (please report this bug) semua utas pencarian berhenti karena kesalahan internal (mohon laporkan bug ini) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it folder Fonts VectorCraft tidak diatur di sini: aplikasi desktop dan vectorcraft-cli yang mengaturnya @msg choose the font files to add pilih berkas font yang akan ditambahkan -@msg {n} font file(s) are now in {folder} {n} berkas font kini berada di {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} berkas font kini berada di {folder}; {failed} tidak dapat ditambahkan: {reason} -@msg {n} font(s) aren't available here: their text shows in another font {n} font tidak tersedia di sini: teksnya ditampilkan dalam font lain @msg not a file bukan berkas @msg not a font file bukan berkas font @msg that document is no longer open dokumen tersebut tidak lagi terbuka @@ -4546,7 +4550,6 @@ imageTrace Outline Kontur @msg every numbered name for it is taken in the Fonts folder semua nama bernomor untuk font tersebut sudah dipakai di folder Fonts @msg every numbered name for {name} is taken in the document's folder semua nama bernomor untuk {name} sudah dipakai di folder dokumen @msg No linked files to look for Tidak ada berkas tertaut untuk dicari -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} {n} gambar ditautkan ulang; {name} tidak dapat ditautkan ulang: {reason} @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` adalah referensi langkah {r}, yang hanya diselesaikan oleh `run` dan `command_batch` @msg `ids` must be an array of object ids, not {v} `ids` harus berupa array id objek, bukan {v} @msg `corners` must be an array of anchor indices, not {v} `corners` harus berupa array indeks jangkar, bukan {v} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 7c82ec424f..b3bd272581 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3940,7 +3940,6 @@ axis Both Entrambi @msg Combine Slices: the slices have no bounds Combina sezioni: le sezioni non hanno limiti @msg Convert to Artboards: selection has no area Converti in tavole da disegno: la selezione non ha area @msg Convert to Shape: no rectangles or ellipses selected Converti in forma: nessun rettangolo o ellisse selezionato -@msg Copied the CSS of {rules} object(s) Copiato il CSS di {rules} oggetto/i @msg Copied the script report Rapporto dello script copiato @msg Corners edits the corners of a path Angoli modifica gli angoli di un tracciato @msg Couldn't copy to the system clipboard: {e} Impossibile copiare negli appunti di sistema: {e} @@ -3957,13 +3956,11 @@ axis Both Entrambi @msg direct-select anchor points to cut at (not the end points of open paths) seleziona con Selezione diretta i punti di ancoraggio in cui tagliare (non i punti finali dei tracciati aperti) @msg Divide Objects Below: select a path Dividi oggetti sottostanti: seleziona un tracciato @msg Divide Objects Below: select exactly one path Dividi oggetti sottostanti: seleziona esattamente un tracciato -@msg Downloaded {_1} file(s) File scaricati: {_1} @msg Downloaded {what} Scaricato {what} @msg Expand Appearance: the selection has a basic appearance Espandi aspetto: la selezione ha un aspetto di base @msg Expand: no brush strokes selected Espandi: nessuna traccia di pennello selezionata @msg Expand: no gradient fills Espandi: nessun riempimento con sfumatura @msg Expand: nothing to expand Espandi: niente da espandere -@msg Exported {count} file(s) to {folder} File esportati in {folder}: {count} @msg Exported {path} Esportato {path} @msg Flatten Transparency: select objects to flatten Appiattisci trasparenza: seleziona gli oggetti da appiattire @msg Flatten Transparency: {e} Appiattisci trasparenza: {e} @@ -4523,10 +4520,6 @@ axis Both Entrambi @msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` occupa {size} byte (limite {MAX_DOCUMENT_DATA}) @msg {_1} is already used by {_2} {_1} è già usato da {_2} @msg {_1} is reserved by the system {_1} è riservato dal sistema -@msg {_1} linked file(s) can't be read here: their previews show file collegati non leggibili qui: {_1}; vengono mostrate le loro anteprime -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes immagini non decodificabili: {undecoded}; vengono mostrate come riquadri barrati da una croce -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions immagini collegate modificate su disco: {_1}; Aggiorna collegamenti mostra le nuove versioni -@msg Updated {_1} linked file(s) changed on disk File collegati modificati su disco aggiornati: {_1} @msg {_1}: not saved, so not closed {_1}: non salvato, quindi non chiuso @msg {bpp}-bit bitmaps can't be read impossibile leggere bitmap a {bpp} bit @msg {command} didn't create an object {command} non ha creato alcun oggetto @@ -4546,7 +4539,6 @@ axis Both Entrambi @msg Couldn't place {name}: {e} Impossibile inserire {name}: {e} @msg Couldn't paste from the clipboard: {e} Impossibile incollare dagli appunti: {e} @msg Saved {path} with {_1} note(s): {first} Salvato {path} con {_1} nota/e: {first} -@msg Exported {what} with {_1} note(s): {first} Esportato {what} con {_1} nota/e: {first} @msg Exported {what} Esportato {what} @msg Saved {n} files beside {path} Salvati {n} file accanto a {path} @msg Saving Salvataggio @@ -4557,12 +4549,26 @@ axis Both Entrambi @msg Saving recovery data for {_1} Salvataggio dei dati di recupero per {_1} @msg Discarded {_1} recovered document(s) Documenti recuperati scartati: {_1} @msg Restored {_1} recovered document(s): save them to keep them Documenti recuperati ripristinati: {_1}. Salvali per conservarli -@msg Embedded {n} image(s); {missing} missing: relink them first Immagini incorporate: {n}; mancanti: {missing} (ricollegale prima) -@msg Embedded {n} image(s) Immagini incorporate: {n} -@msg Relinked {_1} image(s) Immagini ricollegate: {_1} -@msg Relinked {n} image(s) Immagini ricollegate: {n} -@msg Relinked {n} image(s); not in that folder: {_1} Immagini ricollegate: {n}; non presenti in quella cartella: {_1} -@msg Updated {_1} image(s) Immagini aggiornate: {_1} +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Incorporata {n} immagine; mancanti: {missing} (ricollegale prima)|Incorporate {n} immagini; mancanti: {missing} (ricollegale prima) +@msgplural Embedded {n} image|Embedded {n} images Incorporata {n} immagine|Incorporate {n} immagini +@msgplural Relinked {n} image|Relinked {n} images Ricollegata {n} immagine|Ricollegate {n} immagini +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} Ricollegata {n} immagine; non presenti in quella cartella: {names}|Ricollegate {n} immagini; non presenti in quella cartella: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} Ricollegata {n} immagine; impossibile ricollegare {name}: {reason}|Ricollegate {n} immagini; impossibile ricollegare {name}: {reason} +@msgplural Updated {n} image|Updated {n} images Aggiornata {n} immagine|Aggiornate {n} immagini +@msgplural Replaced {n} image|Replaced {n} images Sostituita {n} immagine|Sostituite {n} immagini +@msgplural Broke {n} link|Broke {n} links Interrotto {n} collegamento|Interrotti {n} collegamenti +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first Interrotto {n} collegamento; impossibile leggerne {missing}: ricollegali o aggiornali prima|Interrotti {n} collegamenti; impossibile leggerne {missing}: ricollegali o aggiornali prima +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} file collegato non leggibile qui: viene mostrata la sua anteprima|{n} file collegati non leggibili qui: vengono mostrate le loro anteprime +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes {n} immagine non decodificabile: viene mostrata come riquadro barrato da una croce|{n} immagini non decodificabili: vengono mostrate come riquadri barrati da una croce +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} immagine collegata modificata su disco: Aggiorna collegamenti mostra la nuova versione|{n} immagini collegate modificate su disco: Aggiorna collegamenti mostra le nuove versioni +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Aggiornato {n} file collegato modificato su disco|Aggiornati {n} file collegati modificati su disco +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Esportato {what} con {n} nota: {first}|Esportato {what} con {n} note: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} file di font ora in {folder}|{n} file di font ora in {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} file di font ora in {folder}; impossibile aggiungerne {failed}: {reason}|{n} file di font ora in {folder}; impossibile aggiungerne {failed}: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} font non disponibile qui: il suo testo viene mostrato con un altro font|{n} font non disponibili qui: il loro testo viene mostrato con un altro font +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Copiato il CSS di {n} oggetto|Copiato il CSS di {n} oggetti +@msgplural Downloaded {n} file|Downloaded {n} files Scaricato {n} file|Scaricati {n} file +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Esportato {n} file in {folder}|Esportati {n} file in {folder} @msg Unembedded to {_1} Incorporamento rimosso, salvato in {_1} @msg Reset {_1} Reimpostato {_1} @msg Sent to {_1} Inviato a {_1} @@ -4614,9 +4620,6 @@ axis Both Entrambi @msg every search thread stopped on an internal error (please report this bug) tutti i thread di ricerca si sono fermati per un errore interno (segnala questo bug) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it La cartella Fonts di VectorCraft non è impostata qui: la impostano l'app desktop e vectorcraft-cli @msg choose the font files to add scegli i file dei font da aggiungere -@msg {n} font file(s) are now in {folder} File di font ora in {folder}: {n} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} File di font ora in {folder}: {n}; impossibile aggiungerne {failed}: {reason} -@msg {n} font(s) aren't available here: their text shows in another font font non disponibili qui: {n}; il loro testo viene mostrato con un altro font @msg not a file non è un file @msg not a font file non è un file di font @msg that document is no longer open quel documento non è più aperto @@ -4625,7 +4628,6 @@ axis Both Entrambi @msg every numbered name for it is taken in the Fonts folder tutti i nomi numerati per il file sono già usati nella cartella Fonts @msg every numbered name for {name} is taken in the document's folder tutti i nomi numerati per {name} sono già usati nella cartella del documento @msg No linked files to look for Nessun file collegato da cercare -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} Immagini ricollegate: {n}; impossibile ricollegare {name}: {reason} # The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages. Services Servizi diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4d97ac7425..6a2c6ff4ef 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4006,7 +4006,6 @@ swatch Bright Violet ビビッドバイオレット @msg the drawing is too large to open 図面が大きすぎて開けません @msg scale must be a number from {_1} to {_2}, not {_3} 縮尺は {_1} から {_2} までの数値にしてください ({_3} は指定できません) @msg an image has no pixels and was left out ピクセルがない画像を省略しました -@msg Embedded {n} image(s) 画像を {n} 枚埋め込みました @msg object {0} cannot have children オブジェクト {0} には子オブジェクトを含められません @msg range `{s}` is empty 範囲 `{s}` が空です @msg range `{s}`: `{part}` names no number 範囲 `{s}`: `{part}` に番号が指定されていません @@ -4473,10 +4472,6 @@ swatch Bright Violet ビビッドバイオレット @msg the PDF is no longer loaded PDF はもう読み込まれていません @msg no such layer or object 指定されたレイヤーまたはオブジェクトが見つかりません @msg `{tool}` isn't a Liquify tool `{tool}` はゆがみツールではありません -@msg {_1} linked file(s) can't be read here: their previews show この環境では {_1} 個のリンクファイルを読み込めません: 代わりにプレビューを表示しています -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes {undecoded} 個の画像をデコードできませんでした: バツ印の付いた枠で表示しています -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} 個のリンク画像がディスク上で変更されました: 「リンクを更新」で新しいバージョンを表示できます -@msg Updated {_1} linked file(s) changed on disk ディスク上で変更された {_1} 個のリンクファイルを更新しました @msg pick a colour, gradient or pattern to save as a swatch スウォッチとして保存するカラー、グラデーション、またはパターンを選択してください @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} {n} 個のファイルを {folder} にパッケージしました({note}) @msg Packaged {n} file(s){note} {n} 個のファイルをパッケージしました{note} @@ -4504,7 +4499,6 @@ swatch Bright Violet ビビッドバイオレット @msg print settings are not an object プリント設定がオブジェクト形式ではありません @msg no colour group `{g}` カラーグループ `{g}` が見つかりません @msg select artwork (or a colour group) to recolor 再配色するアートワーク (またはカラーグループ) を選択してください -@msg Downloaded {_1} file(s) {_1} 個のファイルをダウンロードしました @msg Preview in Browser needs the desktop app (the web downloads files instead) 「ブラウザーでプレビュー」にはデスクトップアプリが必要です (Web 版では代わりにファイルをダウンロードします) @msg no file system here この環境にはファイルシステムがありません @msg nothing to preview プレビューするものがありません @@ -4532,7 +4526,6 @@ swatch Bright Violet ビビッドバイオレット @msg unknown panel `{raw}` `{raw}` は不明なパネルです @msg x and y must both be numbers x と y はどちらも数値で指定してください @msg Downloaded {what} {what} をダウンロードしました -@msg Exported {count} file(s) to {folder} {count} 個のファイルを {folder} に書き出しました @msg Imported {what}: {_1} {what} を読み込みました: {_1} @msg Installed plug-in {_1} プラグイン {_1} をインストールしました @msg Opened with {_1} note(s): {_2} ドキュメントを開きました (注意 {_1} 件): {_2} @@ -4546,7 +4539,6 @@ swatch Bright Violet ビビッドバイオレット @msg the document has never been saved ドキュメントはまだ一度も保存されていません @msg the export returned unreadable data 書き出し処理から読み取れないデータが返されました @msg {status} ({e}) {status} ({e}) -@msg Exported {what} with {_1} note(s): {first} {what} を書き出しましたが、注意事項が {_1} 件あります: {first} @msg Saved {path} with {_1} note(s): {first} {path} を保存しましたが、注意事項が {_1} 件あります: {first} @msg Couldn't open {name}: {e} {name} を開けませんでした: {e} @msg Couldn't read {name}: {e} {name} を読み込めませんでした: {e} @@ -4605,7 +4597,6 @@ swatch Bright Violet ビビッドバイオレット @msg the library item is damaged ライブラリの項目が破損しています @msg {_1} font families available {_1} 個のフォントファミリーを使用できます @msg {_1} has no {_2} style {_1} には {_2} スタイルがありません -@msg Copied the CSS of {rules} object(s) {rules} 個のオブジェクトの CSS をコピーしました @msg Copied the script report スクリプトのレポートをコピーしました @msg Exported {path} {path} を書き出しました @msg no CSS to copy: select objects with CSS of their own コピーする CSS がありません: 独自の CSS を持つオブジェクトを選択してください @@ -4618,12 +4609,27 @@ swatch Bright Violet ビビッドバイオレット @msg no library `{key}` (see {list}) ライブラリ `{key}` が見つかりません ({list} を参照) @msg select a linked image: an embedded one has no file リンク画像を選択してください: 埋め込み画像にはファイルがありません @msg {path} can't be found: relink it first {path} が見つかりません: 先に再リンクしてください -@msg Embedded {n} image(s); {missing} missing: relink them first 画像を {n} 枚埋め込みましたが、{missing} 枚は見つかりません: 先に再リンクしてください -@msg Relinked {_1} image(s) 画像を {_1} 枚再リンクしました -@msg Relinked {n} image(s) 画像を {n} 枚再リンクしました -@msg Relinked {n} image(s); not in that folder: {_1} 画像を {n} 枚再リンクしましたが、次の画像はそのフォルダーにありません: {_1} +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first 画像を {n} 枚埋め込みましたが、{missing} 枚は見つかりません: 先に再リンクしてください +@msgplural Embedded {n} image|Embedded {n} images 画像を {n} 枚埋め込みました +@msgplural Relinked {n} image|Relinked {n} images 画像を {n} 枚再リンクしました +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} 画像を {n} 枚再リンクしましたが、次の画像はそのフォルダーにありません: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} 画像を {n} 枚再リンクしましたが、{name} は再リンクできませんでした: {reason} +@msgplural Updated {n} image|Updated {n} images 画像を {n} 枚更新しました +@msgplural Replaced {n} image|Replaced {n} images 画像を {n} 枚置換しました +@msgplural Broke {n} link|Broke {n} links {n} 個のリンクを解除しました +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first {n} 個のリンクを解除しましたが、{missing} 個は読み込めません: 先に再リンクするか更新してください +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show この環境では {n} 個のリンクファイルを読み込めません: 代わりにプレビューを表示しています +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes {n} 個の画像をデコードできませんでした: バツ印の付いた枠で表示しています +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} 個のリンク画像がディスク上で変更されました: 「リンクを更新」で新しいバージョンを表示できます +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk ディスク上で変更された {n} 個のリンクファイルを更新しました +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} {what} を書き出しましたが、注意事項が {n} 件あります: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} 個のフォントファイルが {folder} に入りました +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} 個のフォントファイルが {folder} に入りましたが、{failed} 個は追加できませんでした: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} 個のフォントはこの環境では使用できません: テキストは別のフォントで表示されます +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects {n} 個のオブジェクトの CSS をコピーしました +@msgplural Downloaded {n} file|Downloaded {n} files {n} 個のファイルをダウンロードしました +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} 個のファイルを {folder} に書き出しました @msg Unembedded to {_1} 埋め込みを解除して {_1} に保存しました -@msg Updated {_1} image(s) 画像を {_1} 枚更新しました @msg no swatch library `{l}` (see swatch.library.list) スウォッチライブラリ `{l}` が見つかりません (swatch.library.list を参照) @msg no user library folder here この環境にはユーザーライブラリフォルダーがありません @msg Couldn't place {name}: the document it was dropped on was closed {name} を配置できませんでした: ドロップ先のドキュメントは閉じられています @@ -4683,9 +4689,6 @@ swatch Bright Violet ビビッドバイオレット @msg every search thread stopped on an internal error (please report this bug) すべての検索スレッドが内部エラーで停止しました (このバグを報告してください) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it この環境では VectorCraft の Fonts フォルダーが設定されていません: デスクトップアプリと vectorcraft-cli が設定します @msg choose the font files to add 追加するフォントファイルを選択してください -@msg {n} font file(s) are now in {folder} {n} 個のフォントファイルが {folder} に入りました -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} 個のフォントファイルが {folder} に入りましたが、{failed} 個は追加できませんでした: {reason} -@msg {n} font(s) aren't available here: their text shows in another font {n} 個のフォントはこの環境では使用できません: テキストは別のフォントで表示されます @msg not a file ファイルではありません @msg not a font file フォントファイルではありません @msg that document is no longer open そのドキュメントはもう開かれていません @@ -4694,7 +4697,6 @@ swatch Bright Violet ビビッドバイオレット @msg every numbered name for it is taken in the Fonts folder Fonts フォルダーでは、このファイルの番号付きの名前がすべて使われています @msg every numbered name for {name} is taken in the document's folder ドキュメントのフォルダーでは、{name} の番号付きの名前がすべて使われています @msg No linked files to look for 検索するリンクファイルがありません -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} 画像を {n} 枚再リンクしましたが、{name} は再リンクできませんでした: {reason} @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` はステップ参照 {r} です。ステップ参照を解決できるのは `run` と `command_batch` だけです @msg `ids` must be an array of object ids, not {v} `ids` はオブジェクト ID の配列にしてください ({v} は使えません) @msg `corners` must be an array of anchor indices, not {v} `corners` はアンカーポイントのインデックスの配列にしてください ({v} は使えません) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b10c28a807..b634eadf88 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -568,7 +568,6 @@ Links ბმულები @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? დისკზე შეიცვალა დაკავშირებული გამოსახულებები ({n}). ვაჩვენო ახალი ვერსიები? Update Changed Links შეცვლილი ბმულების განახლება -@msg Updated {_1} linked file(s) changed on disk განახლდა დისკზე შეცვლილი დაკავშირებული ფაილები: {_1} Magic Wand ჯადოსნური ჯოხი Navigator ნავიგატორი Pattern Options პატერნის პარამეტრები @@ -3695,7 +3694,6 @@ font-technology Variable ცვლადი @msg Combine Slices: the slices have no bounds ნაჭრების გაერთიანება: ნაჭრებს საზღვრები არ აქვს @msg Convert to Artboards: selection has no area სამუშაო დაფებად გარდაქმნა: მონიშნულს ფართობი არ აქვს @msg Convert to Shape: no rectangles or ellipses selected ფიგურად გარდაქმნა: მართკუთხედები ან ელიფსები მონიშნული არ არის -@msg Copied the CSS of {rules} object(s) კოპირებულია ობიექტის CSS ({rules}) @msg Corners edits the corners of a path „კუთხეები“ ტრაექტორიის კუთხეებს არედაქტირებს @msg Couldn't copy to the system clipboard: {e} სისტემის გაცვლის ბუფერში კოპირება ვერ მოხერხდა: {e} @msg Couldn't open {name}: {e} {name} ვერ გაიხსნა: {e} @@ -3711,13 +3709,11 @@ font-technology Variable ცვლადი @msg direct-select anchor points to cut at (not the end points of open paths) პირდაპირი მონიშვნით მონიშნეთ საყრდენი წერტილები, სადაც გაიჭრება (არა ღია ტრაექტორიების ბოლო წერტილები) @msg Divide Objects Below: select a path ქვედა ობიექტების დაყოფა: მონიშნეთ ტრაექტორია @msg Divide Objects Below: select exactly one path ქვედა ობიექტების დაყოფა: მონიშნეთ ზუსტად ერთი ტრაექტორია -@msg Downloaded {_1} file(s) ჩამოტვირთულია ფაილი ({_1}) @msg Downloaded {what} ჩამოტვირთულია: {what} @msg Expand Appearance: the selection has a basic appearance იერსახის გაშლა: მონიშნულს საბაზისო იერსახე აქვს @msg Expand: no brush strokes selected გაშლა: ფუნჯის შტრიხები მონიშნული არ არის @msg Expand: no gradient fills გაშლა: გრადიენტული შევსებები არ არის @msg Expand: nothing to expand გაშლა: გასაშლელი არაფერია -@msg Exported {count} file(s) to {folder} ექსპორტირებულია ფაილი ({count}) საქაღალდეში {folder} @msg Exported {path} ექსპორტირებულია: {path} @msg Flatten Transparency: select objects to flatten გამჭვირვალობის გაბრტყელება: მონიშნეთ გასაბრტყელებელი ობიექტები @msg Flatten Transparency: {e} გამჭვირვალობის გაბრტყელება: {e} @@ -4235,9 +4231,6 @@ font-technology Variable ცვლადი @msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` {size} ბაიტია (ლიმიტი {MAX_DOCUMENT_DATA}) @msg {_1} is already used by {_2} {_1} უკვე გამოიყენება აქ: {_2} @msg {_1} is reserved by the system {_1} დაჯავშნილია სისტემის მიერ -@msg {_1} linked file(s) can't be read here: their previews show მიბმული ფაილების წაკითხვა აქ ვერ ხერხდება ({_1}): ჩანს მათი გადახედვა -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes სურათების დეკოდირება ვერ მოხერხდა ({undecoded}): ისინი ჯვრით გადახაზული ჩარჩოებით ჩანს -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions მიბმული გამოსახულებები შეიცვალა დისკზე ({_1}): ბმულების განახლება აჩვენებს ახალ ვერსიებს @msg {_1}: not saved, so not closed {_1}: არ შენახულა, ამიტომ არ დაიხურა @msg {bpp}-bit bitmaps can't be read {bpp}-ბიტიანი bitmap-ების წაკითხვა ვერ ხერხდება @msg {command} didn't create an object {command}-მა ობიექტი არ შექმნა @@ -4256,7 +4249,6 @@ font-technology Variable ცვლადი @msg Couldn't place {name}: {e} {name}-ის განთავსება ვერ მოხერხდა: {e} @msg Couldn't paste from the clipboard: {e} გაცვლის ბუფერიდან ჩასმა ვერ მოხერხდა: {e} @msg Saved {path} with {_1} note(s): {first} შენახულია {path}, შენიშვნები: {_1}: {first} -@msg Exported {what} with {_1} note(s): {first} ექსპორტირებულია {what}, შენიშვნები: {_1}: {first} @msg Exported {what} ექსპორტირებულია {what} @msg Saved {n} files beside {path} {path}-ის გვერდით შენახულია ფაილები: {n} @msg Saving შენახვა @@ -4267,12 +4259,26 @@ font-technology Variable ცვლადი @msg Saving recovery data for {_1} {_1}-ის აღდგენის მონაცემების შენახვა @msg Discarded {_1} recovered document(s) უარყოფილია აღდგენილი დოკუმენტები: {_1} @msg Restored {_1} recovered document(s): save them to keep them აღდგენილია დოკუმენტები: {_1}: შესანარჩუნებლად შეინახეთ ისინი -@msg Embedded {n} image(s); {missing} missing: relink them first ჩაშენებულია გამოსახულებები: {n}; აკლია {missing}: ჯერ ხელახლა მიაბით -@msg Embedded {n} image(s) ჩაშენებულია გამოსახულებები: {n} -@msg Relinked {_1} image(s) ხელახლა მიბმულია გამოსახულებები: {_1} -@msg Relinked {n} image(s) ხელახლა მიბმულია გამოსახულებები: {n} -@msg Relinked {n} image(s); not in that folder: {_1} ხელახლა მიბმულია გამოსახულებები: {n}; იმ საქაღალდეში არ არის: {_1} -@msg Updated {_1} image(s) განახლებულია გამოსახულებები: {_1} +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first ჩაშენებულია გამოსახულებები: {n}; აკლია {missing}: ჯერ ხელახლა მიაბით +@msgplural Embedded {n} image|Embedded {n} images ჩაშენებულია გამოსახულებები: {n} +@msgplural Relinked {n} image|Relinked {n} images ხელახლა მიბმულია გამოსახულებები: {n} +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} ხელახლა მიბმულია გამოსახულებები: {n}; იმ საქაღალდეში არ არის: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} ხელახლა დაკავშირდა გამოსახულება: {n}; {name} ვერ დაკავშირდა: {reason} +@msgplural Updated {n} image|Updated {n} images განახლებულია გამოსახულებები: {n} +@msgplural Replaced {n} image|Replaced {n} images ჩანაცვლებულია გამოსახულებები: {n} +@msgplural Broke {n} link|Broke {n} links გაწყვეტილია ბმულები: {n} +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first გაწყვეტილია ბმულები: {n}; ვერ იკითხება {missing}: ჯერ ხელახლა მიაბით ან განაახლეთ +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show მიბმული ფაილების წაკითხვა აქ ვერ ხერხდება ({n}): ჩანს მათი გადახედვა +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes სურათების დეკოდირება ვერ მოხერხდა ({n}): ისინი ჯვრით გადახაზული ჩარჩოებით ჩანს +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions მიბმული გამოსახულებები შეიცვალა დისკზე ({n}): ბმულების განახლება აჩვენებს ახალ ვერსიებს +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk განახლდა დისკზე შეცვლილი დაკავშირებული ფაილები: {n} +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} ექსპორტირებულია {what}, შენიშვნები: {n}: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} შრიფტის ფაილები ({n}) ახლა აქ არის: {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} შრიფტის ფაილები ({n}) ახლა აქ არის: {folder}; ვერ დაემატა {failed}: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font შრიფტები ({n}) აქ მიუწვდომელია: მათი ტექსტი სხვა შრიფტით ჩანს +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects კოპირებულია ობიექტის CSS ({n}) +@msgplural Downloaded {n} file|Downloaded {n} files ჩამოტვირთულია ფაილი ({n}) +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} ექსპორტირებულია ფაილი ({n}) საქაღალდეში {folder} @msg Unembedded to {_1} ჩაშენება მოხსნილია: {_1} @msg Reset {_1} ჩამოყრილია: {_1} @msg Sent to {_1} გაგზავნილია: {_1} @@ -4320,9 +4326,6 @@ font-technology Variable ცვლადი @msg every search thread stopped on an internal error (please report this bug) ძიების ყველა ნაკადი შიდა შეცდომით შეჩერდა (გთხოვთ, შეგვატყობინოთ ეს ხარვეზი) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it VectorCraft-ის შრიფტების საქაღალდე აქ დაყენებული არ არის: მას აყენებს სამაგიდო აპი და vectorcraft-cli @msg choose the font files to add აირჩიეთ დასამატებელი შრიფტის ფაილები -@msg {n} font file(s) are now in {folder} შრიფტის ფაილები ({n}) ახლა აქ არის: {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} შრიფტის ფაილები ({n}) ახლა აქ არის: {folder}; ვერ დაემატა {failed}: {reason} -@msg {n} font(s) aren't available here: their text shows in another font შრიფტები ({n}) აქ მიუწვდომელია: მათი ტექსტი სხვა შრიფტით ჩანს @msg not a file ფაილი არ არის @msg not a font file შრიფტის ფაილი არ არის @msg that document is no longer open ის დოკუმენტი აღარ არის გახსნილი @@ -4680,7 +4683,6 @@ font-technology Variable ცვლადი @msg the art on them differs from the page's in {_1}% of it: they come from its editing data all the same მათზე არსებული ნახატი გვერდისგან {_1}%-ით განსხვავდება: მიუხედავად ამისა, ისინი რედაქტირების მონაცემებიდან აიღება @msg every numbered name for {name} is taken in the document's folder დოკუმენტის საქაღალდეში {name}-ის ყველა დანომრილი სახელი დაკავებულია @msg No linked files to look for მოსაძებნი დაკავშირებული ფაილები არ არის -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} ხელახლა დაკავშირდა გამოსახულება: {n}; {name} ვერ დაკავშირდა: {reason} Ruler Origin სახაზავების სათავე Reset Ruler Origin სახაზავების სათავის ჩამოყრა Artistic მხატვრული diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 86f82fad40..8cbb908f66 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3933,7 +3933,6 @@ theme Appearance 외관 @msg the drawing is too large to open 도면이 너무 커서 열 수 없습니다 @msg scale must be a number from {_1} to {_2}, not {_3} 배율은 {_1}에서 {_2} 사이의 숫자여야 합니다: {_3} @msg an image has no pixels and was left out 픽셀이 없는 이미지를 제외했습니다 -@msg Embedded {n} image(s) 이미지 {n}개를 포함했습니다 @msg object {0} cannot have children 개체 {0}에는 하위 항목을 둘 수 없습니다 @msg range `{s}` is empty 범위 `{s}`이(가) 비어 있습니다 @msg range `{s}`: `{part}` names no number 범위 `{s}`: `{part}`에 숫자가 없습니다 @@ -4400,10 +4399,6 @@ theme Appearance 외관 @msg the PDF is no longer loaded PDF가 더 이상 로드되어 있지 않습니다 @msg no such layer or object 해당 레이어나 개체가 없습니다 @msg `{tool}` isn't a Liquify tool `{tool}`은(는) 픽셀 유동화 도구가 아닙니다 -@msg {_1} linked file(s) can't be read here: their previews show 링크된 파일 {_1}개를 여기서 읽을 수 없습니다: 미리 보기가 표시됩니다 -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes 이미지 {undecoded}개를 디코딩할 수 없습니다: X 표시가 된 상자로 표시됩니다 -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions 링크된 이미지 {_1}개가 디스크에서 바뀌었습니다: 링크 업데이트를 하면 새 버전이 표시됩니다 -@msg Updated {_1} linked file(s) changed on disk 디스크에서 바뀐 링크된 파일 {_1}개를 업데이트했습니다 @msg pick a colour, gradient or pattern to save as a swatch 견본으로 저장할 색상, 그레이디언트 또는 패턴을 선택하세요 @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} {folder}에 파일 {n}개를 패키지했습니다({note}) @msg Packaged {n} file(s){note} 파일 {n}개를 패키지했습니다{note} @@ -4431,7 +4426,6 @@ theme Appearance 외관 @msg print settings are not an object 인쇄 설정이 개체가 아닙니다 @msg no colour group `{g}` 색상 그룹 `{g}`이(가) 없습니다 @msg select artwork (or a colour group) to recolor 리컬러할 아트웍(또는 색상 그룹)을 선택하세요 -@msg Downloaded {_1} file(s) 파일 {_1}개를 다운로드했습니다 @msg Preview in Browser needs the desktop app (the web downloads files instead) 브라우저에서 미리 보기는 데스크톱 앱이 필요합니다(웹에서는 파일을 다운로드합니다) @msg no file system here 여기에는 파일 시스템이 없습니다 @msg nothing to preview 미리 볼 항목이 없습니다 @@ -4459,7 +4453,6 @@ theme Appearance 외관 @msg unknown panel `{raw}` 알 수 없는 패널 `{raw}` @msg x and y must both be numbers x와 y는 모두 숫자여야 합니다 @msg Downloaded {what} {what}을(를) 다운로드했습니다 -@msg Exported {count} file(s) to {folder} 파일 {count}개를 {folder}에 내보냈습니다 @msg Imported {what}: {_1} {what}을(를) 가져왔습니다: {_1} @msg Installed plug-in {_1} 플러그인 {_1}을(를) 설치했습니다 @msg Opened with {_1} note(s): {_2} 참고 {_1}건과 함께 열었습니다: {_2} @@ -4473,7 +4466,6 @@ theme Appearance 외관 @msg the document has never been saved 문서가 저장된 적이 없습니다 @msg the export returned unreadable data 내보내기가 읽을 수 없는 데이터를 반환했습니다 @msg {status} ({e}) {status}({e}) -@msg Exported {what} with {_1} note(s): {first} 참고 {_1}건과 함께 {what}을(를) 내보냈습니다: {first} @msg Saved {path} with {_1} note(s): {first} 참고 {_1}건과 함께 {path}을(를) 저장했습니다: {first} @msg Couldn't open {name}: {e} {name}을(를) 열 수 없습니다: {e} @msg Couldn't read {name}: {e} {name}을(를) 읽을 수 없습니다: {e} @@ -4532,7 +4524,6 @@ theme Appearance 외관 @msg the library item is damaged 라이브러리 항목이 손상되었습니다 @msg {_1} font families available 사용 가능한 글꼴 패밀리 {_1}개 @msg {_1} has no {_2} style {_1}에는 {_2} 스타일이 없습니다 -@msg Copied the CSS of {rules} object(s) 개체 {rules}개의 CSS를 복사했습니다 @msg Copied the script report 스크립트 보고서를 복사했습니다 @msg Exported {path} {path}을(를) 내보냈습니다 @msg no CSS to copy: select objects with CSS of their own 복사할 CSS가 없습니다: 자체 CSS가 있는 개체를 선택하세요 @@ -4545,12 +4536,27 @@ theme Appearance 외관 @msg no library `{key}` (see {list}) 라이브러리 `{key}`이(가) 없습니다({list} 참조) @msg select a linked image: an embedded one has no file 링크된 이미지를 선택하세요: 포함된 이미지에는 파일이 없습니다 @msg {path} can't be found: relink it first {path}을(를) 찾을 수 없습니다: 먼저 다시 링크하세요 -@msg Embedded {n} image(s); {missing} missing: relink them first 이미지 {n}개를 포함했으며 {missing}개가 없습니다: 먼저 다시 링크하세요 -@msg Relinked {_1} image(s) 이미지 {_1}개를 다시 링크했습니다 -@msg Relinked {n} image(s) 이미지 {n}개를 다시 링크했습니다 -@msg Relinked {n} image(s); not in that folder: {_1} 이미지 {n}개를 다시 링크했습니다. 해당 폴더에 없음: {_1} +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first 이미지 {n}개를 포함했으며 {missing}개가 없습니다: 먼저 다시 링크하세요 +@msgplural Embedded {n} image|Embedded {n} images 이미지 {n}개를 포함했습니다 +@msgplural Relinked {n} image|Relinked {n} images 이미지 {n}개를 다시 링크했습니다 +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} 이미지 {n}개를 다시 링크했습니다. 해당 폴더에 없음: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} 이미지 {n}개를 다시 링크했으며 {name}은(는) 다시 링크할 수 없었습니다: {reason} +@msgplural Updated {n} image|Updated {n} images 이미지 {n}개를 업데이트했습니다 +@msgplural Replaced {n} image|Replaced {n} images 이미지 {n}개를 바꿨습니다 +@msgplural Broke {n} link|Broke {n} links 링크 {n}개를 끊었습니다 +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first 링크 {n}개를 끊었으며 {missing}개를 읽을 수 없습니다: 먼저 다시 링크하거나 업데이트하세요 +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show 링크된 파일 {n}개를 여기서 읽을 수 없습니다: 미리 보기가 표시됩니다 +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes 이미지 {n}개를 디코딩할 수 없습니다: X 표시가 된 상자로 표시됩니다 +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions 링크된 이미지 {n}개가 디스크에서 바뀌었습니다: 링크 업데이트를 하면 새 버전이 표시됩니다 +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk 디스크에서 바뀐 링크된 파일 {n}개를 업데이트했습니다 +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} 참고 {n}건과 함께 {what}을(를) 내보냈습니다: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} 글꼴 파일 {n}개가 이제 {folder}에 있습니다 +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} 글꼴 파일 {n}개가 이제 {folder}에 있으며, {failed}개는 추가할 수 없었습니다: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font 글꼴 {n}개를 여기서 사용할 수 없습니다: 해당 텍스트는 다른 글꼴로 표시됩니다 +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects 개체 {n}개의 CSS를 복사했습니다 +@msgplural Downloaded {n} file|Downloaded {n} files 파일 {n}개를 다운로드했습니다 +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} 파일 {n}개를 {folder}에 내보냈습니다 @msg Unembedded to {_1} {_1}에 포함 해제했습니다 -@msg Updated {_1} image(s) 이미지 {_1}개를 업데이트했습니다 @msg no swatch library `{l}` (see swatch.library.list) 견본 라이브러리 `{l}`이(가) 없습니다(swatch.library.list 참조) @msg no user library folder here 여기에는 사용자 라이브러리 폴더가 없습니다 @msg Couldn't place {name}: the document it was dropped on was closed {name}을(를) 가져올 수 없습니다: 놓은 문서가 닫혔습니다 @@ -4610,9 +4616,6 @@ theme Appearance 외관 @msg every search thread stopped on an internal error (please report this bug) 내부 오류로 모든 검색 스레드가 중지되었습니다(이 버그를 신고해 주세요) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it 여기에는 VectorCraft의 글꼴 폴더가 설정되어 있지 않습니다: 데스크톱 앱과 vectorcraft-cli가 설정합니다 @msg choose the font files to add 추가할 글꼴 파일을 선택하세요 -@msg {n} font file(s) are now in {folder} 글꼴 파일 {n}개가 이제 {folder}에 있습니다 -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} 글꼴 파일 {n}개가 이제 {folder}에 있으며, {failed}개는 추가할 수 없었습니다: {reason} -@msg {n} font(s) aren't available here: their text shows in another font 글꼴 {n}개를 여기서 사용할 수 없습니다: 해당 텍스트는 다른 글꼴로 표시됩니다 @msg not a file 파일이 아닙니다 @msg not a font file 글꼴 파일이 아닙니다 @msg that document is no longer open 해당 문서는 더 이상 열려 있지 않습니다 @@ -4621,7 +4624,6 @@ theme Appearance 외관 @msg every numbered name for it is taken in the Fonts folder 글꼴 폴더에서 이를 위한 번호 이름이 모두 사용 중입니다 @msg every numbered name for {name} is taken in the document's folder 문서 폴더에서 {name}을(를) 위한 번호 이름이 모두 사용 중입니다 @msg No linked files to look for 찾을 링크된 파일이 없습니다 -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} 이미지 {n}개를 다시 링크했으며 {name}은(는) 다시 링크할 수 없었습니다: {reason} @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id`는 단계 참조 {r}이며, `run`과 `command_batch`만 이를 해석합니다 @msg `ids` must be an array of object ids, not {v} `ids`는 {v}이(가) 아니라 개체 id 배열이어야 합니다 @msg `corners` must be an array of anchor indices, not {v} `corners`는 {v}이(가) 아니라 앵커 인덱스 배열이어야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 39d58c856a..8e1401cc04 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -640,7 +640,6 @@ Links Koppelingen @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} gekoppelde afbeelding gewijzigd op de schijf. Nieuwe versie tonen?|{n} gekoppelde afbeeldingen gewijzigd op de schijf. Nieuwe versies tonen? Update Changed Links Gewijzigde koppelingen bijwerken -@msg Updated {_1} linked file(s) changed on disk Bijgewerkt: {_1} gekoppelde bestand(en) gewijzigd op de schijf Magic Wand Magische toverstaf Navigator Navigator Pattern Options Patroonopties @@ -3937,7 +3936,6 @@ imageTrace Outline Contour @msg Combine Slices: the slices have no bounds Slices combineren: de slices hebben geen grenzen @msg Convert to Artboards: selection has no area Converteren naar tekengebieden: de selectie heeft geen oppervlakte @msg Convert to Shape: no rectangles or ellipses selected Converteren naar vorm: geen rechthoeken of ellipsen geselecteerd -@msg Copied the CSS of {rules} object(s) CSS van {rules} object(en) gekopieerd @msg Copied the script report Scriptrapport gekopieerd @msg Corners edits the corners of a path Hoeken bewerkt de hoeken van een pad @msg Couldn't copy to the system clipboard: {e} Kon niet naar het systeemklembord kopiëren: {e} @@ -3954,13 +3952,11 @@ imageTrace Outline Contour @msg direct-select anchor points to cut at (not the end points of open paths) selecteer met directe selectie ankerpunten om te knippen (niet de eindpunten van open paden) @msg Divide Objects Below: select a path Objecten eronder verdelen: selecteer een pad @msg Divide Objects Below: select exactly one path Objecten eronder verdelen: selecteer precies één pad -@msg Downloaded {_1} file(s) {_1} bestand(en) gedownload @msg Downloaded {what} {what} gedownload @msg Expand Appearance: the selection has a basic appearance Vormgeving uitbreiden: de selectie heeft een basisvormgeving @msg Expand: no brush strokes selected Uitbreiden: geen penseelstreken geselecteerd @msg Expand: no gradient fills Uitbreiden: geen verloopvullingen @msg Expand: nothing to expand Uitbreiden: niets om uit te breiden -@msg Exported {count} file(s) to {folder} {count} bestand(en) geëxporteerd naar {folder} @msg Exported {path} {path} geëxporteerd @msg Flatten Transparency: select objects to flatten Transparantie afvlakken: selecteer objecten om af te vlakken @msg Flatten Transparency: {e} Transparantie afvlakken: {e} @@ -4460,8 +4456,6 @@ imageTrace Outline Contour @msg {_1} is a live effect (Effect › Plug-ins) {_1} is een live-effect (Effect › Plug-ins) @msg {_1} is already used by {_2} {_1} wordt al gebruikt door {_2} @msg {_1} is reserved by the system {_1} is gereserveerd door het systeem -@msg {_1} linked file(s) can't be read here: their previews show {_1} gekoppelde bestand(en) kunnen hier niet worden gelezen: hun voorbeelden worden weergegeven -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} gekoppelde afbeelding(en) zijn gewijzigd op de schijf: Koppelingen bijwerken toont de nieuwe versies @msg {_1}: not saved, so not closed {_1}: niet opgeslagen, dus niet gesloten @msg {bpp}-bit bitmaps can't be read {bpp}-bits bitmaps kunnen niet worden gelezen @msg {command} didn't create an object {command} heeft geen object gemaakt @@ -4481,7 +4475,6 @@ imageTrace Outline Contour @msg Couldn't place {name}: {e} Kon {name} niet plaatsen: {e} @msg Couldn't paste from the clipboard: {e} Kon niet van het klembord plakken: {e} @msg Saved {path} with {_1} note(s): {first} {path} opgeslagen met {_1} opmerking(en): {first} -@msg Exported {what} with {_1} note(s): {first} {what} geëxporteerd met {_1} opmerking(en): {first} @msg Exported {what} {what} geëxporteerd @msg Saved {n} files beside {path} {n} bestanden opgeslagen naast {path} @msg Saving Bezig met opslaan @@ -4492,12 +4485,26 @@ imageTrace Outline Contour @msg Saving recovery data for {_1} Bezig met opslaan van herstelgegevens voor {_1} @msg Discarded {_1} recovered document(s) {_1} hersteld(e) document(en) verworpen @msg Restored {_1} recovered document(s): save them to keep them {_1} hersteld(e) document(en) teruggezet: sla ze op om ze te behouden -@msg Embedded {n} image(s); {missing} missing: relink them first {n} afbeelding(en) ingesloten; {missing} ontbreken: koppel ze eerst opnieuw -@msg Embedded {n} image(s) {n} afbeelding(en) ingesloten -@msg Relinked {_1} image(s) {_1} afbeelding(en) opnieuw gekoppeld -@msg Relinked {n} image(s) {n} afbeelding(en) opnieuw gekoppeld -@msg Relinked {n} image(s); not in that folder: {_1} {n} afbeelding(en) opnieuw gekoppeld; niet in die map: {_1} -@msg Updated {_1} image(s) {_1} afbeelding(en) bijgewerkt +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} afbeelding ingesloten; {missing} ontbreken: koppel ze eerst opnieuw|{n} afbeeldingen ingesloten; {missing} ontbreken: koppel ze eerst opnieuw +@msgplural Embedded {n} image|Embedded {n} images {n} afbeelding ingesloten|{n} afbeeldingen ingesloten +@msgplural Relinked {n} image|Relinked {n} images {n} afbeelding opnieuw gekoppeld|{n} afbeeldingen opnieuw gekoppeld +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} {n} afbeelding opnieuw gekoppeld; niet in die map: {names}|{n} afbeeldingen opnieuw gekoppeld; niet in die map: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} {n} afbeelding opnieuw gekoppeld; {name} kon niet opnieuw worden gekoppeld: {reason}|{n} afbeeldingen opnieuw gekoppeld; {name} kon niet opnieuw worden gekoppeld: {reason} +@msgplural Updated {n} image|Updated {n} images {n} afbeelding bijgewerkt|{n} afbeeldingen bijgewerkt +@msgplural Replaced {n} image|Replaced {n} images {n} afbeelding vervangen|{n} afbeeldingen vervangen +@msgplural Broke {n} link|Broke {n} links {n} koppeling verbroken|{n} koppelingen verbroken +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first {n} koppeling verbroken; {missing} kunnen niet worden gelezen: koppel ze eerst opnieuw of werk ze bij|{n} koppelingen verbroken; {missing} kunnen niet worden gelezen: koppel ze eerst opnieuw of werk ze bij +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} gekoppeld bestand kan hier niet worden gelezen: het voorbeeld wordt weergegeven|{n} gekoppelde bestanden kunnen hier niet worden gelezen: hun voorbeelden worden weergegeven +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes {n} afbeelding kon niet worden gedecodeerd en wordt als doorgekruist vak weergegeven|{n} afbeeldingen konden niet worden gedecodeerd en worden als doorgekruiste vakken weergegeven +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} gekoppelde afbeelding is gewijzigd op de schijf: Koppelingen bijwerken toont de nieuwe versie|{n} gekoppelde afbeeldingen zijn gewijzigd op de schijf: Koppelingen bijwerken toont de nieuwe versies +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Bijgewerkt: {n} gekoppeld bestand gewijzigd op de schijf|Bijgewerkt: {n} gekoppelde bestanden gewijzigd op de schijf +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} {what} geëxporteerd met {n} opmerking: {first}|{what} geëxporteerd met {n} opmerkingen: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} er staat nu {n} lettertypebestand in {folder}|er staan nu {n} lettertypebestanden in {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} er staat nu {n} lettertypebestand in {folder}; {failed} konden niet worden toegevoegd: {reason}|er staan nu {n} lettertypebestanden in {folder}; {failed} konden niet worden toegevoegd: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} lettertype hier niet beschikbaar: de tekst verschijnt in een ander lettertype|{n} lettertypen hier niet beschikbaar: de tekst verschijnt in een ander lettertype +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects CSS van {n} object gekopieerd|CSS van {n} objecten gekopieerd +@msgplural Downloaded {n} file|Downloaded {n} files {n} bestand gedownload|{n} bestanden gedownload +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} bestand geëxporteerd naar {folder}|{n} bestanden geëxporteerd naar {folder} @msg Unembedded to {_1} Extern gemaakt: {_1} @msg Reset {_1} {_1} opnieuw ingesteld @msg Sent to {_1} Verzonden naar {_1} @@ -4547,9 +4554,6 @@ imageTrace Outline Contour @msg every search thread stopped on an internal error (please report this bug) elke zoekthread is gestopt door een interne fout (meld deze bug) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it de map Lettertypen van VectorCraft is hier niet ingesteld: de desktopapp en vectorcraft-cli stellen die in @msg choose the font files to add kies de lettertypebestanden die je wilt toevoegen -@msg {n} font file(s) are now in {folder} er staan nu {n} lettertypebestand(en) in {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} er staan nu {n} lettertypebestand(en) in {folder}; {failed} konden niet worden toegevoegd: {reason} -@msg {n} font(s) aren't available here: their text shows in another font {n} lettertype(n) hier niet beschikbaar: de tekst verschijnt in een ander lettertype @msg not a file geen bestand @msg not a font file geen lettertypebestand @msg that document is no longer open dat document is niet langer geopend @@ -4558,7 +4562,6 @@ imageTrace Outline Contour @msg every numbered name for it is taken in the Fonts folder elke genummerde naam ervoor is al vergeven in de map Lettertypen @msg every numbered name for {name} is taken in the document's folder elke genummerde naam voor {name} is al vergeven in de map van het document @msg No linked files to look for Geen gekoppelde bestanden om naar te zoeken -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} {n} afbeelding(en) opnieuw gekoppeld; {name} kon niet opnieuw worden gekoppeld: {reason} @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` is de stapverwijzing {r}, die alleen `run` en `command_batch` oplossen @msg `ids` must be an array of object ids, not {v} `ids` moet een array van object-id's zijn, niet {v} @msg `corners` must be an array of anchor indices, not {v} `corners` moet een array van ankerindices zijn, niet {v} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 6b6141546f..e11a11366d 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -622,7 +622,6 @@ Links Łącza @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? Połączone obrazy zmienione na dysku: {n}. Pokazać nowe wersje?|Połączone obrazy zmienione na dysku: {n}. Pokazać nowe wersje?|Połączone obrazy zmienione na dysku: {n}. Pokazać nowe wersje? Update Changed Links Aktualizuj zmienione łącza -@msg Updated {_1} linked file(s) changed on disk Zaktualizowano połączone pliki zmienione na dysku: {_1} Magic Wand Różdżka Navigator Nawigator Pattern Options Opcje wzorka @@ -4032,7 +4031,6 @@ imageTrace Outline Kontur @msg Combine Slices: the slices have no bounds Połącz plasterki: plasterki nie mają granic @msg Convert to Artboards: selection has no area Konwertuj na obszary kompozycji: zaznaczenie nie ma powierzchni @msg Convert to Shape: no rectangles or ellipses selected Konwertuj na kształt: nie zaznaczono prostokątów ani elips -@msg Copied the CSS of {rules} object(s) Skopiowano CSS obiektów: {rules} @msg Copied the script report Skopiowano raport skryptu @msg Corners edits the corners of a path Narożniki edytuje narożniki ścieżki @msg Couldn't copy to the system clipboard: {e} Nie udało się skopiować do schowka systemowego: {e} @@ -4049,13 +4047,11 @@ imageTrace Outline Kontur @msg direct-select anchor points to cut at (not the end points of open paths) zaznacz bezpośrednio punkty kontrolne, w których ma nastąpić cięcie (nie punkty końcowe otwartych ścieżek) @msg Divide Objects Below: select a path Podziel obiekty poniżej: zaznacz ścieżkę @msg Divide Objects Below: select exactly one path Podziel obiekty poniżej: zaznacz dokładnie jedną ścieżkę -@msg Downloaded {_1} file(s) Pobrane pliki: {_1} @msg Downloaded {what} Pobrano {what} @msg Expand Appearance: the selection has a basic appearance Rozszerz wygląd: zaznaczenie ma wygląd podstawowy @msg Expand: no brush strokes selected Rozszerz: nie zaznaczono pociągnięć pędzla @msg Expand: no gradient fills Rozszerz: brak wypełnień gradientem @msg Expand: nothing to expand Rozszerz: nie ma czego rozszerzać -@msg Exported {count} file(s) to {folder} Wyeksportowane pliki do {folder}: {count} @msg Exported {path} Wyeksportowano {path} @msg Flatten Transparency: select objects to flatten Spłaszcz przezroczystość: zaznacz obiekty do spłaszczenia @msg Flatten Transparency: {e} Spłaszcz przezroczystość: {e} @@ -4616,9 +4612,6 @@ imageTrace Outline Kontur @msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` ma {size} bajtów (limit {MAX_DOCUMENT_DATA}) @msg {_1} is already used by {_2} {_1} jest już używany przez {_2} @msg {_1} is reserved by the system Skrót {_1} jest zarezerwowany przez system -@msg {_1} linked file(s) can't be read here: their previews show połączonych plików nie można tu odczytać ({_1}): wyświetlane są ich podglądy -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes nie udało się zdekodować obrazów ({undecoded}): są wyświetlane jako przekreślone ramki -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions połączone obrazy zmienione na dysku: {_1} — Aktualizuj łącza pokaże nowe wersje @msg {_1}: not saved, so not closed {_1}: nie zapisano, więc nie zamknięto @msg {bpp}-bit bitmaps can't be read nie można odczytać bitmap {bpp}-bitowych @msg {command} didn't create an object {command} nie utworzyło obiektu @@ -4638,7 +4631,6 @@ imageTrace Outline Kontur @msg Couldn't place {name}: {e} Nie udało się umieścić {name}: {e} @msg Couldn't paste from the clipboard: {e} Nie udało się wkleić ze schowka: {e} @msg Saved {path} with {_1} note(s): {first} Zapisano {path}, uwagi ({_1}): {first} -@msg Exported {what} with {_1} note(s): {first} Wyeksportowano {what}, uwagi ({_1}): {first} @msg Exported {what} Wyeksportowano {what} @msg Saved {n} files beside {path} Zapisane pliki obok {path}: {n} @msg Saving Zapisywanie @@ -4649,12 +4641,26 @@ imageTrace Outline Kontur @msg Saving recovery data for {_1} Zapisywanie danych odzyskiwania dla {_1} @msg Discarded {_1} recovered document(s) Odrzucone odzyskane dokumenty: {_1} @msg Restored {_1} recovered document(s): save them to keep them Przywrócone odzyskane dokumenty: {_1} — zapisz je, aby je zachować -@msg Embedded {n} image(s); {missing} missing: relink them first Osadzone obrazy: {n}; brakujące: {missing} — najpierw połącz je ponownie -@msg Embedded {n} image(s) Osadzone obrazy: {n} -@msg Relinked {_1} image(s) Ponownie połączone obrazy: {_1} -@msg Relinked {n} image(s) Ponownie połączone obrazy: {n} -@msg Relinked {n} image(s); not in that folder: {_1} Ponownie połączone obrazy: {n}; nie ma ich w tym folderze: {_1} -@msg Updated {_1} image(s) Zaktualizowane obrazy: {_1} +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Osadzono {n} obraz; brakuje {missing}: najpierw połącz je ponownie|Osadzono {n} obrazy; brakuje {missing}: najpierw połącz je ponownie|Osadzono {n} obrazów; brakuje {missing}: najpierw połącz je ponownie +@msgplural Embedded {n} image|Embedded {n} images Osadzono {n} obraz|Osadzono {n} obrazy|Osadzono {n} obrazów +@msgplural Relinked {n} image|Relinked {n} images Ponownie połączono {n} obraz|Ponownie połączono {n} obrazy|Ponownie połączono {n} obrazów +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} Ponownie połączono {n} obraz; nie ma ich w tym folderze: {names}|Ponownie połączono {n} obrazy; nie ma ich w tym folderze: {names}|Ponownie połączono {n} obrazów; nie ma ich w tym folderze: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} Ponownie połączono {n} obraz; nie udało się ponownie połączyć {name}: {reason}|Ponownie połączono {n} obrazy; nie udało się ponownie połączyć {name}: {reason}|Ponownie połączono {n} obrazów; nie udało się ponownie połączyć {name}: {reason} +@msgplural Updated {n} image|Updated {n} images Zaktualizowano {n} obraz|Zaktualizowano {n} obrazy|Zaktualizowano {n} obrazów +@msgplural Replaced {n} image|Replaced {n} images Zastąpiono {n} obraz|Zastąpiono {n} obrazy|Zastąpiono {n} obrazów +@msgplural Broke {n} link|Broke {n} links Zerwano {n} łącze|Zerwano {n} łącza|Zerwano {n} łączy +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first Zerwano {n} łącze; nie można odczytać {missing}: najpierw połącz je ponownie lub zaktualizuj|Zerwano {n} łącza; nie można odczytać {missing}: najpierw połącz je ponownie lub zaktualizuj|Zerwano {n} łączy; nie można odczytać {missing}: najpierw połącz je ponownie lub zaktualizuj +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show nie można tu odczytać {n} połączonego pliku: wyświetlany jest jego podgląd|nie można tu odczytać {n} połączonych plików: wyświetlane są ich podglądy|nie można tu odczytać {n} połączonych plików: wyświetlane są ich podglądy +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes nie udało się zdekodować {n} obrazu: jest wyświetlany jako przekreślona ramka|nie udało się zdekodować {n} obrazów: są wyświetlane jako przekreślone ramki|nie udało się zdekodować {n} obrazów: są wyświetlane jako przekreślone ramki +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} połączony obraz zmienił się na dysku: Aktualizuj łącza pokaże nową wersję|{n} połączone obrazy zmieniły się na dysku: Aktualizuj łącza pokaże nowe wersje|{n} połączonych obrazów zmieniło się na dysku: Aktualizuj łącza pokaże nowe wersje +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Zaktualizowano {n} połączony plik zmieniony na dysku|Zaktualizowano {n} połączone pliki zmienione na dysku|Zaktualizowano {n} połączonych plików zmienionych na dysku +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Wyeksportowano {what} z {n} uwagą: {first}|Wyeksportowano {what} z {n} uwagami: {first}|Wyeksportowano {what} z {n} uwagami: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} plik czcionki jest teraz w {folder}|{n} pliki czcionek są teraz w {folder}|{n} plików czcionek jest teraz w {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} plik czcionki jest teraz w {folder}; nie udało się dodać {failed}: {reason}|{n} pliki czcionek są teraz w {folder}; nie udało się dodać {failed}: {reason}|{n} plików czcionek jest teraz w {folder}; nie udało się dodać {failed}: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} czcionka jest tu niedostępna: jej tekst jest wyświetlany inną czcionką|{n} czcionki są tu niedostępne: ich tekst jest wyświetlany inną czcionką|{n} czcionek jest tu niedostępnych: ich tekst jest wyświetlany inną czcionką +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Skopiowano CSS {n} obiektu|Skopiowano CSS {n} obiektów|Skopiowano CSS {n} obiektów +@msgplural Downloaded {n} file|Downloaded {n} files Pobrano {n} plik|Pobrano {n} pliki|Pobrano {n} plików +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Wyeksportowano {n} plik do {folder}|Wyeksportowano {n} pliki do {folder}|Wyeksportowano {n} plików do {folder} @msg Unembedded to {_1} Wyodrębniono do {_1} @msg Reset {_1} Zresetowano {_1} @msg Sent to {_1} Wysłano do {_1} @@ -4706,9 +4712,6 @@ imageTrace Outline Kontur @msg every search thread stopped on an internal error (please report this bug) wszystkie wątki wyszukiwania zatrzymały się na błędzie wewnętrznym (zgłoś ten błąd) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it folder czcionek VectorCraft nie jest tu ustawiony: ustawia go aplikacja desktopowa i vectorcraft-cli @msg choose the font files to add wybierz pliki czcionek do dodania -@msg {n} font file(s) are now in {folder} pliki czcionek w {folder}: {n} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} pliki czcionek w {folder}: {n}; nie udało się dodać: {failed} ({reason}) -@msg {n} font(s) aren't available here: their text shows in another font niedostępne czcionki: {n} — ich tekst jest wyświetlany inną czcionką @msg not a file to nie jest plik @msg not a font file to nie jest plik czcionki @msg that document is no longer open ten dokument nie jest już otwarty @@ -4717,7 +4720,6 @@ imageTrace Outline Kontur @msg every numbered name for it is taken in the Fonts folder wszystkie numerowane nazwy dla niego są zajęte w folderze czcionek @msg every numbered name for {name} is taken in the document's folder wszystkie numerowane nazwy dla {name} są zajęte w folderze dokumentu @msg No linked files to look for Brak połączonych plików do wyszukania -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} Ponownie połączone obrazy: {n}; nie udało się ponownie połączyć {name}: {reason} @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` to odwołanie do kroku {r}, które rozwiązują tylko `run` i `command_batch` @msg `ids` must be an array of object ids, not {v} `ids` musi być tablicą identyfikatorów obiektów, nie {v} @msg `corners` must be an array of anchor indices, not {v} `corners` musi być tablicą indeksów punktów, nie {v} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 9c79f3edb0..be472f5cfc 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2885,7 +2885,6 @@ digits Malayalam Malaiala Update Links Atualizar Links Update Changed Links Atualizar Links alterados @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} imagem vinculada alterada no disco. Mostrar a nova versão?|{n} imagens vinculadas alteradas no disco. Mostrar as novas versões? -@msg Updated {_1} linked file(s) changed on disk {_1} arquivo(s) vinculado(s) alterado(s) no disco atualizado(s) Update Modified Links Atualizar Links Modificados Use Use Use Artboards Usar Mesas de Trabalho @@ -3485,7 +3484,6 @@ axis Both Ambos @msg Combine Slices: the slices have no bounds Combinar fatias: as fatias não têm limites @msg Convert to Artboards: selection has no area Converter em pranchetas: a seleção não tem área @msg Convert to Shape: no rectangles or ellipses selected Converter em forma: nenhum retângulo ou elipse selecionado -@msg Copied the CSS of {rules} object(s) CSS de {rules} objeto(s) copiado @msg Corners edits the corners of a path Cantos edita os cantos de um traçado @msg Couldn't copy to the system clipboard: {e} Não foi possível copiar para a área de transferência do sistema: {e} @msg Couldn't open {name}: {e} Não foi possível abrir {name}: {e} @@ -3501,13 +3499,11 @@ axis Both Ambos @msg direct-select anchor points to cut at (not the end points of open paths) selecione diretamente os pontos de ancoragem onde cortar (não as extremidades de traçados abertos) @msg Divide Objects Below: select a path Dividir objetos abaixo: selecione um traçado @msg Divide Objects Below: select exactly one path Dividir objetos abaixo: selecione exatamente um traçado -@msg Downloaded {_1} file(s) {_1} arquivo(s) baixado(s) @msg Downloaded {what} {what} baixado @msg Expand Appearance: the selection has a basic appearance Expandir aparência: a seleção tem uma aparência básica @msg Expand: no brush strokes selected Expandir: nenhum traço de pincel selecionado @msg Expand: no gradient fills Expandir: nenhum preenchimento em gradiente @msg Expand: nothing to expand Expandir: nada para expandir -@msg Exported {count} file(s) to {folder} {count} arquivo(s) exportado(s) para {folder} @msg Exported {path} {path} exportado @msg Flatten Transparency: select objects to flatten Achatar transparência: selecione os objetos a achatar @msg Flatten Transparency: {e} Achatar transparência: {e} @@ -4056,9 +4052,6 @@ axis Both Ambos @msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` tem {size} bytes (limite {MAX_DOCUMENT_DATA}) @msg {_1} is already used by {_2} {_1} já é usado por {_2} @msg {_1} is reserved by the system {_1} é reservado pelo sistema -@msg {_1} linked file(s) can't be read here: their previews show {_1} arquivo(s) vinculado(s) não podem ser lidos aqui: suas visualizações são exibidas -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes não foi possível decodificar {undecoded} imagem(ns): elas aparecem como caixas marcadas com um X -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} imagem(ns) vinculada(s) mudou(aram) no disco: Atualizar links mostra as novas versões @msg {_1}: not saved, so not closed {_1}: não salvo, portanto não fechado @msg {bpp}-bit bitmaps can't be read bitmaps de {bpp} bits não podem ser lidos @msg {command} didn't create an object {command} não criou um objeto @@ -4077,7 +4070,6 @@ axis Both Ambos @msg Couldn't place {name}: {e} Não foi possível inserir {name}: {e} @msg Couldn't paste from the clipboard: {e} Não foi possível colar da área de transferência: {e} @msg Saved {path} with {_1} note(s): {first} {path} salvo com {_1} observação(ões): {first} -@msg Exported {what} with {_1} note(s): {first} {what} exportado com {_1} observação(ões): {first} @msg Exported {what} {what} exportado @msg Saved {n} files beside {path} {n} arquivos salvos ao lado de {path} @msg Saving Salvando @@ -4088,12 +4080,26 @@ axis Both Ambos @msg Saving recovery data for {_1} Salvando dados de recuperação de {_1} @msg Discarded {_1} recovered document(s) {_1} documento(s) recuperado(s) descartado(s) @msg Restored {_1} recovered document(s): save them to keep them {_1} documento(s) recuperado(s) restaurado(s): salve-os para mantê-los -@msg Embedded {n} image(s); {missing} missing: relink them first {n} imagem(ns) incorporada(s); {missing} ausente(s): revincule-as primeiro -@msg Embedded {n} image(s) {n} imagem(ns) incorporada(s) -@msg Relinked {_1} image(s) {_1} imagem(ns) revinculada(s) -@msg Relinked {n} image(s) {n} imagem(ns) revinculada(s) -@msg Relinked {n} image(s); not in that folder: {_1} {n} imagem(ns) revinculada(s); fora dessa pasta: {_1} -@msg Updated {_1} image(s) {_1} imagem(ns) atualizada(s) +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} imagem incorporada; faltam {missing}: revincule-as primeiro|{n} imagens incorporadas; faltam {missing}: revincule-as primeiro +@msgplural Embedded {n} image|Embedded {n} images {n} imagem incorporada|{n} imagens incorporadas +@msgplural Relinked {n} image|Relinked {n} images {n} imagem revinculada|{n} imagens revinculadas +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} {n} imagem revinculada; fora dessa pasta: {names}|{n} imagens revinculadas; fora dessa pasta: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} {n} imagem revinculada; não foi possível revincular {name}: {reason}|{n} imagens revinculadas; não foi possível revincular {name}: {reason} +@msgplural Updated {n} image|Updated {n} images {n} imagem atualizada|{n} imagens atualizadas +@msgplural Replaced {n} image|Replaced {n} images {n} imagem substituída|{n} imagens substituídas +@msgplural Broke {n} link|Broke {n} links {n} vínculo quebrado|{n} vínculos quebrados +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first {n} vínculo quebrado; não é possível ler {missing}: revincule-os ou atualize-os primeiro|{n} vínculos quebrados; não é possível ler {missing}: revincule-os ou atualize-os primeiro +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} arquivo vinculado não pode ser lido aqui: sua visualização é exibida|{n} arquivos vinculados não podem ser lidos aqui: suas visualizações são exibidas +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes não foi possível decodificar {n} imagem: ela aparece como uma caixa marcada com um X|não foi possível decodificar {n} imagens: elas aparecem como caixas marcadas com um X +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} imagem vinculada mudou no disco: Atualizar links mostra a nova versão|{n} imagens vinculadas mudaram no disco: Atualizar links mostra as novas versões +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk {n} arquivo vinculado alterado no disco atualizado|{n} arquivos vinculados alterados no disco atualizados +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} {what} exportado com {n} observação: {first}|{what} exportado com {n} observações: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} arquivo de fonte agora está em {folder}|{n} arquivos de fonte agora estão em {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} arquivo de fonte agora está em {folder}; não foi possível adicionar {failed}: {reason}|{n} arquivos de fonte agora estão em {folder}; não foi possível adicionar {failed}: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} fonte não está disponível aqui: o texto dela aparece em outra fonte|{n} fontes não estão disponíveis aqui: o texto delas aparece em outra fonte +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects CSS de {n} objeto copiado|CSS de {n} objetos copiado +@msgplural Downloaded {n} file|Downloaded {n} files {n} arquivo baixado|{n} arquivos baixados +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} arquivo exportado para {folder}|{n} arquivos exportados para {folder} @msg Unembedded to {_1} Desincorporado para {_1} @msg Reset {_1} Redefinir {_1} @msg Sent to {_1} Enviado para {_1} @@ -4143,9 +4149,6 @@ axis Both Ambos @msg every search thread stopped on an internal error (please report this bug) todos os processos de pesquisa pararam por um erro interno (relate este bug) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it A pasta Fontes do VectorCraft não está definida aqui: o aplicativo para desktop e o vectorcraft-cli a definem @msg choose the font files to add escolha os arquivos de fonte a adicionar -@msg {n} font file(s) are now in {folder} {n} arquivo(s) de fonte agora está(ão) em {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} arquivo(s) de fonte agora está(ão) em {folder}; {failed} não pôde(puderam) ser adicionado(s): {reason} -@msg {n} font(s) aren't available here: their text shows in another font {n} fonte(s) não está(ão) disponível(is) aqui: o texto delas aparece em outra fonte @msg not a file não é um arquivo @msg not a font file não é um arquivo de fonte @msg that document is no longer open esse documento não está mais aberto @@ -4786,7 +4789,6 @@ axis Both Ambos @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise o texto de área em molduras baixas demais para uma linha da fonte em que aparece recebeu molduras mais altas ({_1}): senão o texto não apareceria @msg every numbered name for {name} is taken in the document's folder todos os nomes numerados para {name} já existem na pasta do documento @msg No linked files to look for Nenhum arquivo vinculado para procurar -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} {n} imagem(ns) revinculada(s); não foi possível revincular {name}: {reason} De-Interlace Desentrelaçar Eliminate Eliminar Create New Fields by Criar Novos Campos por diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index de3223891d..50f1057a3d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3936,7 +3936,6 @@ axis Both Оба @msg Combine Slices: the slices have no bounds Объединение фрагментов: у фрагментов нет границ @msg Convert to Artboards: selection has no area Преобразование в монтажные области: у выделения нет области @msg Convert to Shape: no rectangles or ellipses selected Преобразование в фигуру: не выделены прямоугольники или эллипсы -@msg Copied the CSS of {rules} object(s) Скопирован CSS для {rules} объекта(ов) @msg Copied the script report Отчёт о сценарии скопирован @msg Corners edits the corners of a path «Углы» редактирует углы контура @msg Couldn't copy to the system clipboard: {e} Не удалось скопировать в системный буфер обмена: {e} @@ -3953,13 +3952,11 @@ axis Both Оба @msg direct-select anchor points to cut at (not the end points of open paths) выделите прямым выделением опорные точки для разреза (не конечные точки открытых контуров) @msg Divide Objects Below: select a path Разделение объектов ниже: выделите контур @msg Divide Objects Below: select exactly one path Разделение объектов ниже: выделите ровно один контур -@msg Downloaded {_1} file(s) Скачано файлов: {_1} @msg Downloaded {what} Скачано: {what} @msg Expand Appearance: the selection has a basic appearance Разбор оформления: у выделения основное оформление @msg Expand: no brush strokes selected Разбор: не выделены мазки кисти @msg Expand: no gradient fills Разбор: нет градиентных заливок @msg Expand: nothing to expand Разбор: нечего разбирать -@msg Exported {count} file(s) to {folder} Экспортировано файлов: {count} в {folder} @msg Exported {path} Экспортировано: {path} @msg Flatten Transparency: select objects to flatten Объединение прозрачностей: выделите объекты для объединения @msg Flatten Transparency: {e} Объединение прозрачностей: {e} @@ -4519,10 +4516,6 @@ axis Both Оба @msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` занимает {size} байт (предел {MAX_DOCUMENT_DATA}) @msg {_1} is already used by {_2} {_1} уже используется {_2} @msg {_1} is reserved by the system Сочетание {_1} зарезервировано системой -@msg {_1} linked file(s) can't be read here: their previews show здесь невозможно прочитать связанных файлов: {_1}: отображаются их предварительные просмотры -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes не удалось декодировать изображения ({undecoded}): они показаны как перечёркнутые рамки -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions связанных изображений ({_1}) изменились на диске: «Обновить связи» покажет новые версии -@msg Updated {_1} linked file(s) changed on disk Обновлено связанных файлов, измененных на диске: {_1} @msg {_1}: not saved, so not closed {_1}: не сохранён, поэтому не закрыт @msg {bpp}-bit bitmaps can't be read растровые изображения с глубиной {bpp} бит не читаются @msg {command} didn't create an object {command} не создал объект @@ -4542,7 +4535,6 @@ axis Both Оба @msg Couldn't place {name}: {e} Не удалось поместить {name}: {e} @msg Couldn't paste from the clipboard: {e} Не удалось вставить из буфера обмена: {e} @msg Saved {path} with {_1} note(s): {first} Сохранено: {path} с примечаниями ({_1}) : {first} -@msg Exported {what} with {_1} note(s): {first} Экспортировано: {what} с примечаниями ({_1}) : {first} @msg Exported {what} Экспортировано: {what} @msg Saved {n} files beside {path} Сохранено файлов: {n} рядом с {path} @msg Saving Сохранение @@ -4553,12 +4545,26 @@ axis Both Оба @msg Saving recovery data for {_1} Сохранение данных восстановления для {_1} @msg Discarded {_1} recovered document(s) Отменено восстановленных документов: {_1} @msg Restored {_1} recovered document(s): save them to keep them Восстановлено документов: {_1}: сохраните их, чтобы оставить -@msg Embedded {n} image(s); {missing} missing: relink them first Внедрено изображений: {n}; отсутствует {missing}: сначала восстановите связи -@msg Embedded {n} image(s) Внедрено изображений: {n} -@msg Relinked {_1} image(s) Восстановлена связь с изображениями: {_1} -@msg Relinked {n} image(s) Восстановлена связь с изображениями: {n} -@msg Relinked {n} image(s); not in that folder: {_1} Восстановлена связь с изображениями: {n}; нет в этой папке: {_1} -@msg Updated {_1} image(s) Обновлено изображений: {_1} +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Внедрено {n} изображение; отсутствует {missing}: сначала восстановите связи|Внедрено {n} изображения; отсутствует {missing}: сначала восстановите связи|Внедрено {n} изображений; отсутствует {missing}: сначала восстановите связи +@msgplural Embedded {n} image|Embedded {n} images Внедрено {n} изображение|Внедрено {n} изображения|Внедрено {n} изображений +@msgplural Relinked {n} image|Relinked {n} images Восстановлена связь с {n} изображением|Восстановлена связь с {n} изображениями|Восстановлена связь с {n} изображениями +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} Восстановлена связь с {n} изображением; нет в этой папке: {names}|Восстановлена связь с {n} изображениями; нет в этой папке: {names}|Восстановлена связь с {n} изображениями; нет в этой папке: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} Восстановлена связь с {n} изображением; не удалось восстановить связь с {name}: {reason}|Восстановлена связь с {n} изображениями; не удалось восстановить связь с {name}: {reason}|Восстановлена связь с {n} изображениями; не удалось восстановить связь с {name}: {reason} +@msgplural Updated {n} image|Updated {n} images Обновлено {n} изображение|Обновлено {n} изображения|Обновлено {n} изображений +@msgplural Replaced {n} image|Replaced {n} images Заменено {n} изображение|Заменено {n} изображения|Заменено {n} изображений +@msgplural Broke {n} link|Broke {n} links Разорвана {n} связь|Разорвано {n} связи|Разорвано {n} связей +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first Разорвана {n} связь; не удаётся прочитать {missing}: сначала восстановите или обновите их связи|Разорвано {n} связи; не удаётся прочитать {missing}: сначала восстановите или обновите их связи|Разорвано {n} связей; не удаётся прочитать {missing}: сначала восстановите или обновите их связи +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show здесь невозможно прочитать {n} связанный файл: отображается его предварительный просмотр|здесь невозможно прочитать {n} связанных файла: отображаются их предварительные просмотры|здесь невозможно прочитать {n} связанных файлов: отображаются их предварительные просмотры +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes не удалось декодировать {n} изображение: оно показано как перечёркнутая рамка|не удалось декодировать {n} изображения: они показаны как перечёркнутые рамки|не удалось декодировать {n} изображений: они показаны как перечёркнутые рамки +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} связанное изображение изменилось на диске: «Обновить связи» покажет новую версию|{n} связанных изображения изменились на диске: «Обновить связи» покажет новые версии|{n} связанных изображений изменились на диске: «Обновить связи» покажет новые версии +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Обновлён {n} связанный файл, изменённый на диске|Обновлено {n} связанных файла, изменённых на диске|Обновлено {n} связанных файлов, изменённых на диске +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Экспортировано: {what} с {n} примечанием: {first}|Экспортировано: {what} с {n} примечаниями: {first}|Экспортировано: {what} с {n} примечаниями: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} файл шрифта теперь в {folder}|{n} файла шрифтов теперь в {folder}|{n} файлов шрифтов теперь в {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} файл шрифта теперь в {folder}; не удалось добавить {failed}: {reason}|{n} файла шрифтов теперь в {folder}; не удалось добавить {failed}: {reason}|{n} файлов шрифтов теперь в {folder}; не удалось добавить {failed}: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font здесь недоступен {n} шрифт: его текст отображается другим шрифтом|здесь недоступно {n} шрифта: их текст отображается другим шрифтом|здесь недоступно {n} шрифтов: их текст отображается другим шрифтом +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Скопирован CSS {n} объекта|Скопирован CSS {n} объектов|Скопирован CSS {n} объектов +@msgplural Downloaded {n} file|Downloaded {n} files Скачан {n} файл|Скачано {n} файла|Скачано {n} файлов +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Экспортирован {n} файл в {folder}|Экспортировано {n} файла в {folder}|Экспортировано {n} файлов в {folder} @msg Unembedded to {_1} Извлечено в {_1} @msg Reset {_1} Сброшено: {_1} @msg Sent to {_1} Отправлено в {_1} @@ -4610,9 +4616,6 @@ axis Both Оба @msg every search thread stopped on an internal error (please report this bug) все потоки поиска остановились из-за внутренней ошибки (сообщите об этой ошибке) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it Папка Fonts VectorCraft здесь не задана: её задают настольное приложение и vectorcraft-cli @msg choose the font files to add выберите файлы шрифтов для добавления -@msg {n} font file(s) are now in {folder} Файлов шрифтов теперь в {folder}: {n} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} Файлов шрифтов теперь в {folder}: {n}; не удалось добавить {failed}: {reason} -@msg {n} font(s) aren't available here: their text shows in another font здесь недоступно шрифтов: {n}; их текст отображается другим шрифтом @msg not a file не файл @msg not a font file не файл шрифта @msg that document is no longer open этот документ больше не открыт @@ -4621,7 +4624,6 @@ axis Both Оба @msg every numbered name for it is taken in the Fonts folder все нумерованные имена для него уже заняты в папке Fonts @msg every numbered name for {name} is taken in the document's folder все нумерованные имена для {name} уже заняты в папке документа @msg No linked files to look for Нет связанных файлов для поиска -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} Восстановлена связь с изображениями: {n}; не удалось восстановить связь с {name}: {reason} # The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages. Services Службы diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 61f1c1f987..f0a3149f68 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3817,7 +3817,6 @@ axis Both Båda @msg Combine Slices: the slices have no bounds Kombinera skivor: skivorna har inga gränser @msg Convert to Artboards: selection has no area Konvertera till ritytor: markeringen har ingen area @msg Convert to Shape: no rectangles or ellipses selected Konvertera till form: inga rektanglar eller ellipser är markerade -@msg Copied the CSS of {rules} object(s) Kopierade CSS för {rules} objekt @msg Copied the script report Kopierade skriptrapporten @msg Corners edits the corners of a path Hörn redigerar hörnen på en bana @msg Couldn't copy to the system clipboard: {e} Kunde inte kopiera till systemets urklipp: {e} @@ -3834,13 +3833,11 @@ axis Both Båda @msg direct-select anchor points to cut at (not the end points of open paths) direktmarkera ankarpunkter att klippa vid (inte slutpunkterna på öppna banor) @msg Divide Objects Below: select a path Dela objekt under: markera en bana @msg Divide Objects Below: select exactly one path Dela objekt under: markera exakt en bana -@msg Downloaded {_1} file(s) Hämtade {_1} fil(er) @msg Downloaded {what} Hämtade {what} @msg Expand Appearance: the selection has a basic appearance Expandera utseende: markeringen har ett grundläggande utseende @msg Expand: no brush strokes selected Expandera: inga penseldrag är markerade @msg Expand: no gradient fills Expandera: inga gradientfyllningar @msg Expand: nothing to expand Expandera: ingenting att expandera -@msg Exported {count} file(s) to {folder} Exporterade {count} fil(er) till {folder} @msg Exported {path} Exporterade {path} @msg Flatten Transparency: select objects to flatten Platta till transparens: markera objekt att platta till @msg Flatten Transparency: {e} Platta till transparens: {e} @@ -4388,10 +4385,6 @@ axis Both Båda @msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` är {size} byte (gräns {MAX_DOCUMENT_DATA}) @msg {_1} is already used by {_2} {_1} används redan av {_2} @msg {_1} is reserved by the system {_1} är reserverat av systemet -@msg {_1} linked file(s) can't be read here: their previews show {_1} länkade fil(er) kan inte läsas här: deras förhandsgranskningar visas -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes {undecoded} bild(er) kunde inte avkodas och visas som överkryssade rutor -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} länkade bild(er) har ändrats på disken: Uppdatera länkar visar de nya versionerna -@msg Updated {_1} linked file(s) changed on disk Uppdaterade {_1} länkade fil(er) som ändrats på disken @msg {_1}: not saved, so not closed {_1}: inte sparat, så inte stängt @msg {bpp}-bit bitmaps can't be read {bpp}-bitars bitmappar kan inte läsas @msg {command} didn't create an object {command} skapade inget objekt @@ -4411,7 +4404,6 @@ axis Both Båda @msg Couldn't place {name}: {e} Kunde inte placera {name}: {e} @msg Couldn't paste from the clipboard: {e} Kunde inte klistra in från urklippet: {e} @msg Saved {path} with {_1} note(s): {first} Sparade {path} med {_1} anteckning(ar): {first} -@msg Exported {what} with {_1} note(s): {first} Exporterade {what} med {_1} anteckning(ar): {first} @msg Exported {what} Exporterade {what} @msg Saved {n} files beside {path} Sparade {n} filer bredvid {path} @msg Saving Sparar @@ -4422,12 +4414,26 @@ axis Both Båda @msg Saving recovery data for {_1} Sparar återställningsdata för {_1} @msg Discarded {_1} recovered document(s) Kastade {_1} återställda dokument @msg Restored {_1} recovered document(s): save them to keep them Återställde {_1} återskapade dokument: spara dem för att behålla dem -@msg Embedded {n} image(s); {missing} missing: relink them first Bäddade in {n} bild(er); {missing} saknas: länka om dem först -@msg Embedded {n} image(s) Bäddade in {n} bild(er) -@msg Relinked {_1} image(s) Omlänkade {_1} bild(er) -@msg Relinked {n} image(s) Omlänkade {n} bild(er) -@msg Relinked {n} image(s); not in that folder: {_1} Omlänkade {n} bild(er); finns inte i mappen: {_1} -@msg Updated {_1} image(s) Uppdaterade {_1} bild(er) +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Bäddade in {n} bild; {missing} saknas: länka om dem först|Bäddade in {n} bilder; {missing} saknas: länka om dem först +@msgplural Embedded {n} image|Embedded {n} images Bäddade in {n} bild|Bäddade in {n} bilder +@msgplural Relinked {n} image|Relinked {n} images Omlänkade {n} bild|Omlänkade {n} bilder +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} Omlänkade {n} bild; finns inte i mappen: {names}|Omlänkade {n} bilder; finns inte i mappen: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} Omlänkade {n} bild; {name} kunde inte omlänkas: {reason}|Omlänkade {n} bilder; {name} kunde inte omlänkas: {reason} +@msgplural Updated {n} image|Updated {n} images Uppdaterade {n} bild|Uppdaterade {n} bilder +@msgplural Replaced {n} image|Replaced {n} images Ersatte {n} bild|Ersatte {n} bilder +@msgplural Broke {n} link|Broke {n} links Bröt {n} länk|Bröt {n} länkar +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first Bröt {n} länk; {missing} kan inte läsas: länka om eller uppdatera dem först|Bröt {n} länkar; {missing} kan inte läsas: länka om eller uppdatera dem först +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} länkad fil kan inte läsas här: dess förhandsgranskning visas|{n} länkade filer kan inte läsas här: deras förhandsgranskningar visas +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes {n} bild kunde inte avkodas och visas som en överkryssad ruta|{n} bilder kunde inte avkodas och visas som överkryssade rutor +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} länkad bild har ändrats på disken: Uppdatera länkar visar den nya versionen|{n} länkade bilder har ändrats på disken: Uppdatera länkar visar de nya versionerna +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Uppdaterade {n} länkad fil som ändrats på disken|Uppdaterade {n} länkade filer som ändrats på disken +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Exporterade {what} med {n} anteckning: {first}|Exporterade {what} med {n} anteckningar: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} typsnittsfil finns nu i {folder}|{n} typsnittsfiler finns nu i {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} typsnittsfil finns nu i {folder}; {failed} kunde inte läggas till: {reason}|{n} typsnittsfiler finns nu i {folder}; {failed} kunde inte läggas till: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} typsnitt är inte tillgängligt här: dess text visas med ett annat typsnitt|{n} typsnitt är inte tillgängliga här: deras text visas med ett annat typsnitt +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Kopierade CSS för {n} objekt|Kopierade CSS för {n} objekt +@msgplural Downloaded {n} file|Downloaded {n} files Hämtade {n} fil|Hämtade {n} filer +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Exporterade {n} fil till {folder}|Exporterade {n} filer till {folder} @msg Unembedded to {_1} Extraherad till {_1} @msg Reset {_1} Återställ {_1} @msg Sent to {_1} Skickat till {_1} @@ -4479,9 +4485,6 @@ axis Both Båda @msg every search thread stopped on an internal error (please report this bug) alla söktrådar stoppades av ett internt fel (rapportera gärna felet) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it VectorCrafts mapp Fonts anges inte här: den anges av skrivbordsappen och vectorcraft-cli @msg choose the font files to add välj de typsnittsfiler som ska läggas till -@msg {n} font file(s) are now in {folder} {n} typsnittsfil(er) finns nu i {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} typsnittsfil(er) finns nu i {folder}; {failed} kunde inte läggas till: {reason} -@msg {n} font(s) aren't available here: their text shows in another font {n} typsnitt är inte tillgängliga här: deras text visas med ett annat typsnitt @msg not a file inte en fil @msg not a font file inte en typsnittsfil @msg that document is no longer open det dokumentet är inte längre öppet @@ -4490,7 +4493,6 @@ axis Both Båda @msg every numbered name for it is taken in the Fonts folder alla numrerade namn för den är upptagna i mappen Typsnitt @msg every numbered name for {name} is taken in the document's folder alla numrerade namn för {name} är upptagna i dokumentets mapp @msg No linked files to look for Inga länkade filer att leta efter -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} Omlänkade {n} bild(er); {name} kunde inte omlänkas: {reason} Services Tjänster Hide VectorCraft Göm VectorCraft Zoom Zoom diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index c3e3345a02..e6517df494 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1517,6 +1517,63 @@ fn messages_with_a_count_take_the_plural_form() { assert_eq!(message(cs, "Packaged 21 files"), "Zabaleno 21 souborů"); } +/// The link, font and export status messages with a count, in English for a count of 1 and of 2. +const COUNTED_STATUS_MESSAGES: &[(&str, &str)] = &[ + ("1 linked file can't be read here: its preview shows", "2 linked files can't be read here: their previews show"), + ("1 image couldn't be decoded and shows as a crossed box", "2 images couldn't be decoded and show as crossed boxes"), + ("1 linked image changed on disk: Update Links shows the new version", "2 linked images changed on disk: Update Links shows the new versions"), + ("Updated 1 linked file changed on disk", "Updated 2 linked files changed on disk"), + ("Exported /out/a.svg with 1 note: a note", "Exported /out/a.svg with 2 notes: a note"), + ("Embedded 1 image; 1 missing: relink them first", "Embedded 2 images; 1 missing: relink them first"), + ("Embedded 1 image", "Embedded 2 images"), + ("Relinked 1 image", "Relinked 2 images"), + ("Relinked 1 image; not in that folder: a.png", "Relinked 2 images; not in that folder: a.png"), + ("Relinked 1 image; a.png couldn't be relinked: a reason", "Relinked 2 images; a.png couldn't be relinked: a reason"), + ("Updated 1 image", "Updated 2 images"), + ("Replaced 1 image", "Replaced 2 images"), + ("Broke 1 link", "Broke 2 links"), + ("Broke 1 link; 1 can't be read: relink or update them first", "Broke 2 links; 1 can't be read: relink or update them first"), + ("1 font file is now in /fonts", "2 font files are now in /fonts"), + ("1 font file is now in /fonts; 1 couldn't be added: a reason", "2 font files are now in /fonts; 1 couldn't be added: a reason"), + ("1 font isn't available here: its text shows in another font", "2 fonts aren't available here: their text shows in another font"), + ("Copied the CSS of 1 object", "Copied the CSS of 2 objects"), + ("Downloaded 1 file", "Downloaded 2 files"), + ("Exported 1 file to /out", "Exported 2 files to /out"), +]; + +/// The link, font and export status messages name a count of 1 in the singular and other counts in +/// the plural, and every complete catalog translates both, in the form its plural rule picks. +#[test] +fn counted_status_messages_take_the_plural_form() { + use crate::panels::links::{relinked_status, updated_status}; + assert_eq!((relinked_status(1), relinked_status(2)), ("Relinked 1 image".to_string(), "Relinked 2 images".to_string())); + assert_eq!((updated_status(1), updated_status(2)), ("Updated 1 image".to_string(), "Updated 2 images".to_string())); + assert_eq!(crate::dialogs::missing_links::changed_on_disk_status(1), COUNTED_STATUS_MESSAGES[2].0); + assert_eq!(crate::dialogs::missing_links::changed_on_disk_status(2), COUNTED_STATUS_MESSAGES[2].1); + assert_eq!(crate::io::exported_with_notes("/out/a.svg", 1, "a note"), COUNTED_STATUS_MESSAGES[4].0); + assert_eq!(crate::io::exported_with_notes("/out/a.svg", 2, "a note"), COUNTED_STATUS_MESSAGES[4].1); + // A value that holds placeholder text is not filled in again. + assert_eq!(crate::io::exported_with_notes("/out/{first}.svg", 1, "{n}"), "Exported /out/{first}.svg with 1 note: {n}"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for s in COUNTED_STATUS_MESSAGES.iter().flat_map(|(one, other)| [one, other]) { + assert_ne!(message(lang, s), *s, "{code}: {s}"); + } + } + let cs = cs(); + assert_eq!(message(cs, &relinked_status(1)), "Znovu propojen 1 obrázek"); + assert_eq!(message(cs, &relinked_status(3)), "Znovu propojeny 3 obrázky"); + assert_eq!(message(cs, &relinked_status(5)), "Znovu propojeno 5 obrázků"); + assert_eq!(message(de(), &updated_status(1)), "1 Bild aktualisiert"); + assert_eq!(message(de(), &updated_status(2)), "2 Bilder aktualisiert"); + let noted = crate::io::exported_with_notes("/out/{n}.svg", 1, "{what}"); + assert_eq!(message(de(), ¬ed), "/out/{n}.svg mit 1 Hinweis exportiert: {what}"); + let ru = Lang::from_code("ru").expect("registered"); + assert_eq!(message(ru, COUNTED_STATUS_MESSAGES[19].0), "Экспортирован 1 файл в /out"); + assert_eq!(message(ru, "Exported 3 files to /out"), "Экспортировано 3 файла в /out"); + assert_eq!(message(ru, "Exported 5 files to /out"), "Экспортировано 5 файлов в /out"); +} + /// The scan reads the message of an error made with one of the engine's [`ERROR_HELPERS`] or with /// an error enum's variant, `EngineError::Disabled`'s reason included: a literal or a `format!` /// string, on the call's line or wrapped over several lines, in the same template form as the diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 938c519152..4c1b9eae30 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3705,7 +3705,6 @@ axis Both Her İkisi @msg Combine Slices: the slices have no bounds Dilimleri Birleştir: dilimlerin sınırları yoktur @msg Convert to Artboards: selection has no area Çalışma Yüzeylerine Dönüştür: seçimin alanı yok @msg Convert to Shape: no rectangles or ellipses selected Şekle Dönüştür: seçili dikdörtgen veya elips yok -@msg Copied the CSS of {rules} object(s) {rules} nesnelerinin CSS'si kopyalandı @msg Copied the script report Komut dosyası raporu kopyalandı @msg Corners edits the corners of a path Köşeler bir yolun köşelerini düzenler @msg Couldn't copy to the system clipboard: {e} Sistem panosuna kopyalanamadı: {e} @@ -3722,13 +3721,11 @@ axis Both Her İkisi @msg direct-select anchor points to cut at (not the end points of open paths) kesilecek bağlantı noktalarını doğrudan seçin (açık yolların bitiş noktalarını değil) @msg Divide Objects Below: select a path Aşağıdaki Nesneleri Böl: bir yol seçin @msg Divide Objects Below: select exactly one path Aşağıdaki Nesneleri Böl: tam olarak bir yol seçin -@msg Downloaded {_1} file(s) İndirilen {_1} dosya(lar)ı @msg Downloaded {what} {what} indirildi @msg Expand Appearance: the selection has a basic appearance Görünümü Genişlet: seçimin temel bir görünümü vardır @msg Expand: no brush strokes selected Genişlet: seçili fırça darbesi yok @msg Expand: no gradient fills Genişlet: degrade dolgu yok @msg Expand: nothing to expand Genişlet: genişletilecek bir şey yok -@msg Exported {count} file(s) to {folder} {count} dosyası/dosyaları {folder}'ye aktarıldı @msg Exported {path} Dışa aktarılan {path} @msg Flatten Transparency: select objects to flatten Düzleştir Şeffaflığı: düzleştirilecek nesneleri seçin @msg Flatten Transparency: {e} Şeffaflığı Düzleştir: {e} @@ -4234,10 +4231,6 @@ axis Both Her İkisi @msg {_1} font families available {_1} yazı tipi aileleri mevcut @msg {_1} is a live effect (Effect › Plug-ins) {_1} canlı bir efekttir (Efekt › Eklentiler) @msg {_1} is already used by {_2} {_1} zaten {_2} tarafından kullanılıyor -@msg {_1} linked file(s) can't be read here: their previews show {_1} bağlantılı dosya(lar) burada okunamıyor: önizlemeleri gösteriliyor -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes {undecoded} görüntünün kodu çözülemedi: çarpı işaretli kutular olarak gösteriliyor -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} bağlantılı görseller diskte değiştirildi: Güncelleme Bağlantıları yeni sürümleri gösteriyor -@msg Updated {_1} linked file(s) changed on disk Güncellenmiş {_1} bağlantılı dosya(lar) diskte değiştirildi @msg {_1}: not saved, so not closed {_1}: kaydedilmedi, dolayısıyla kapatılmadı @msg {bpp}-bit bitmaps can't be read {bpp} bit bit eşlemleri okunamıyor @msg {command} didn't create an object {command} bir nesne yaratmadı @@ -4257,7 +4250,6 @@ axis Both Her İkisi @msg Couldn't place {name}: {e} {name} yerleştirilemedi: {e} @msg Couldn't paste from the clipboard: {e} Panodan yapıştırılamadı: {e} @msg Saved {path} with {_1} note(s): {first} {path}, {_1} notlarıyla kaydedildi: {first} -@msg Exported {what} with {_1} note(s): {first} {_1} notlarıyla birlikte dışa aktarılan {what}: {first} @msg Exported {what} Dışa aktarılan {what} @msg Saved {n} files beside {path} {path}'nin yanında kaydedilen {n} dosyaları @msg Saving Kaydediliyor @@ -4268,12 +4260,26 @@ axis Both Her İkisi @msg Saving recovery data for {_1} {_1} için kurtarma verileri kaydediliyor @msg Discarded {_1} recovered document(s) Atılan {_1} kurtarılan belge(ler) @msg Restored {_1} recovered document(s): save them to keep them Geri yüklenen {_1} kurtarılan belge(ler): saklamak için bunları kaydedin -@msg Embedded {n} image(s); {missing} missing: relink them first Gömülü {n} görselleri; {missing} eksik: önce onları yeniden bağlayın -@msg Embedded {n} image(s) Gömülü {n} görselleri -@msg Relinked {_1} image(s) Yeniden bağlanan {_1} görselleri -@msg Relinked {n} image(s) Yeniden bağlanan {n} görselleri -@msg Relinked {n} image(s); not in that folder: {_1} Yeniden bağlanan {n} görselleri; bu klasörde değil: {_1} -@msg Updated {_1} image(s) Güncellenmiş {_1} görselleri +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} görsel gömüldü; {missing} eksik: önce onları yeniden bağlayın +@msgplural Embedded {n} image|Embedded {n} images {n} görsel gömüldü +@msgplural Relinked {n} image|Relinked {n} images {n} görsel yeniden bağlandı +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} {n} görsel yeniden bağlandı; bu klasörde değil: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} {n} görsel yeniden bağlandı; {name} yeniden bağlanamadı: {reason} +@msgplural Updated {n} image|Updated {n} images {n} görsel güncellendi +@msgplural Replaced {n} image|Replaced {n} images {n} görsel değiştirildi +@msgplural Broke {n} link|Broke {n} links {n} bağlantı kesildi +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first {n} bağlantı kesildi; {missing} okunamıyor: önce onları yeniden bağlayın veya güncelleyin +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} bağlantılı dosya burada okunamıyor: önizlemeleri gösteriliyor +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes {n} görüntünün kodu çözülemedi: çarpı işaretli kutular olarak gösteriliyor +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} bağlantılı görsel diskte değişti: Bağlantıları Güncelle yeni sürümleri gösterir +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Diskte değişen {n} bağlantılı dosya güncellendi +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} {what} {n} notla dışa aktarıldı: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} yazı tipi dosyası artık {folder} içinde +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} yazı tipi dosyası artık {folder} içinde; {failed} eklenemedi: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} yazı tipi burada kullanılamıyor: metni başka bir yazı tipiyle gösteriliyor +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects {n} nesnenin CSS'si kopyalandı +@msgplural Downloaded {n} file|Downloaded {n} files {n} dosya indirildi +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} dosya {folder} klasörüne aktarıldı @msg Unembedded to {_1} {_1}'ye gömülü değil @msg Reset {_1} {_1}'yi sıfırla @msg Sent to {_1} {_1}'ye gönderildi @@ -4325,9 +4331,6 @@ axis Both Her İkisi @msg every search thread stopped on an internal error (please report this bug) her arama dizisi dahili bir hata nedeniyle durduruldu (lütfen bu hatayı bildirin) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it VectorCraft'ın Fonts klasörü burada ayarlanmamış: masaüstü uygulaması ve Vectorcraft-cli bunu ayarlıyor @msg choose the font files to add eklenecek yazı tipi dosyalarını seçin -@msg {n} font file(s) are now in {folder} {n} yazı tipi dosyası/dosyaları artık {folder}'de -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} yazı tipi dosyası/dosyaları artık {folder}'de; {failed} eklenemedi: {reason} -@msg {n} font(s) aren't available here: their text shows in another font {n} yazı tipleri burada mevcut değil: metinleri başka bir yazı tipinde gösteriliyor @msg not a file dosya değil @msg not a font file yazı tipi dosyası değil @msg that document is no longer open bu belge artık açık değil @@ -4336,7 +4339,6 @@ axis Both Her İkisi @msg every numbered name for it is taken in the Fonts folder bunun için numaralandırılmış her ad Yazı Tipleri klasöründe alınır @msg every numbered name for {name} is taken in the document's folder {name} için numaralandırılmış her ad belgenin klasöründe alınır @msg No linked files to look for Aranacak bağlantılı dosya yok -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} Yeniden bağlanan {n} görselleri; {name} yeniden bağlanamadı: {reason} Services Hizmetler Hide VectorCraft VectorCraft'ı gizle Zoom Yakınlaştır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d9d01c69d8..446e45cfbf 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3924,7 +3924,6 @@ axis Both Обидві @msg Combine Slices: the slices have no bounds Об’єднання фрагментів: фрагменти не мають кордонів @msg Convert to Artboards: selection has no area Перетворення на монтажні області: виділення не має області @msg Convert to Shape: no rectangles or ellipses selected Перетворення на фігуру: не виділено прямокутники або еліпси -@msg Copied the CSS of {rules} object(s) Скопійовано CSS об’єктів: {rules} @msg Copied the script report Звіт про сценарій скопійовано @msg Corners edits the corners of a path «Кути» редагує кути контуру @msg Couldn't copy to the system clipboard: {e} Не вдалося скопіювати до системного буфера обміну: {e} @@ -3941,13 +3940,11 @@ axis Both Обидві @msg direct-select anchor points to cut at (not the end points of open paths) виділіть прямим виділенням опорні точки для розрізу (не кінцеві точки відкритих контурів) @msg Divide Objects Below: select a path Поділ об’єктів нижче: виділіть контур @msg Divide Objects Below: select exactly one path Поділ об’єктів нижче: виділіть рівно один контур -@msg Downloaded {_1} file(s) Завантажено файли: {_1} @msg Downloaded {what} Завантажено: {what} @msg Expand Appearance: the selection has a basic appearance Розбір оформлення: виділення основне оформлення @msg Expand: no brush strokes selected Розбір: не виділено мазки пензлі @msg Expand: no gradient fills Розбір: немає градієнтних заливок @msg Expand: nothing to expand Розбір: нема чого розбирати -@msg Exported {count} file(s) to {folder} Експортовано файли: {count} до {folder} @msg Exported {path} Експортовано: {path} @msg Flatten Transparency: select objects to flatten Зведення прозорості: виділіть об’єкти для зведення @msg Flatten Transparency: {e} Зведення прозорості: {e} @@ -4507,10 +4504,6 @@ axis Both Обидві @msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` займає {size} байт (межа {MAX_DOCUMENT_DATA}) @msg {_1} is already used by {_2} {_1} вже використовується {_2} @msg {_1} is reserved by the system Сполучення {_1} зарезервоване системою -@msg {_1} linked file(s) can't be read here: their previews show тут неможливо прочитати пов’язані файли: {_1}: відображаються їх попередні перегляди -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes не вдалося декодувати зображення ({undecoded}): вони показані як перекреслені рамки -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions пов’язаних зображень ({_1}) змінилися на диску: «Оновити зв’язки» покаже нові версії -@msg Updated {_1} linked file(s) changed on disk Оновлено пов’язаних файлів, змінених на диску: {_1} @msg {_1}: not saved, so not closed {_1}: не збережено, тому не закрито @msg {bpp}-bit bitmaps can't be read растрові зображення з глибиною {bpp} біт не читаються @msg {command} didn't create an object {command} не створив об’єкт @@ -4530,7 +4523,6 @@ axis Both Обидві @msg Couldn't place {name}: {e} Не вдалося помістити {name}: {e} @msg Couldn't paste from the clipboard: {e} Не вдалося вставити з буфера обміну: {e} @msg Saved {path} with {_1} note(s): {first} Збережено: {path} з примітками ({_1}) : {first} -@msg Exported {what} with {_1} note(s): {first} Експортовано: {what} з примітками ({_1}) : {first} @msg Exported {what} Експортовано: {what} @msg Saved {n} files beside {path} Збережено файлів: {n} поруч із {path} @msg Saving Збереження @@ -4541,12 +4533,26 @@ axis Both Обидві @msg Saving recovery data for {_1} Збереження даних відновлення для {_1} @msg Discarded {_1} recovered document(s) Скасовано відновлених документів: {_1} @msg Restored {_1} recovered document(s): save them to keep them Відновлено документів: {_1}: збережіть їх, щоб залишити -@msg Embedded {n} image(s); {missing} missing: relink them first Вбудовано зображень: {n}; відсутніх: {missing}. Спочатку відновіть їхні зв’язки -@msg Embedded {n} image(s) Вбудовано зображення: {n} -@msg Relinked {_1} image(s) Відновлено зв’язок із зображеннями: {_1} -@msg Relinked {n} image(s) Відновлено зв’язок із зображеннями: {n} -@msg Relinked {n} image(s); not in that folder: {_1} Відновлено зв’язок із зображеннями: {n}; немає в цій папці: {_1} -@msg Updated {_1} image(s) Оновлено зображень: {_1} +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Вбудовано {n} зображення; відсутніх: {missing}. Спочатку відновіть їхні зв’язки|Вбудовано {n} зображення; відсутніх: {missing}. Спочатку відновіть їхні зв’язки|Вбудовано {n} зображень; відсутніх: {missing}. Спочатку відновіть їхні зв’язки +@msgplural Embedded {n} image|Embedded {n} images Вбудовано {n} зображення|Вбудовано {n} зображення|Вбудовано {n} зображень +@msgplural Relinked {n} image|Relinked {n} images Відновлено зв’язок із {n} зображенням|Відновлено зв’язок із {n} зображеннями|Відновлено зв’язок із {n} зображеннями +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} Відновлено зв’язок із {n} зображенням; немає в цій папці: {names}|Відновлено зв’язок із {n} зображеннями; немає в цій папці: {names}|Відновлено зв’язок із {n} зображеннями; немає в цій папці: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} Відновлено зв’язок із {n} зображенням; не вдалося відновити зв’язок із {name}: {reason}|Відновлено зв’язок із {n} зображеннями; не вдалося відновити зв’язок із {name}: {reason}|Відновлено зв’язок із {n} зображеннями; не вдалося відновити зв’язок із {name}: {reason} +@msgplural Updated {n} image|Updated {n} images Оновлено {n} зображення|Оновлено {n} зображення|Оновлено {n} зображень +@msgplural Replaced {n} image|Replaced {n} images Замінено {n} зображення|Замінено {n} зображення|Замінено {n} зображень +@msgplural Broke {n} link|Broke {n} links Розірвано {n} зв’язок|Розірвано {n} зв’язки|Розірвано {n} зв’язків +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first Розірвано {n} зв’язок; не вдається прочитати {missing}: спочатку відновіть або оновіть їхні зв’язки|Розірвано {n} зв’язки; не вдається прочитати {missing}: спочатку відновіть або оновіть їхні зв’язки|Розірвано {n} зв’язків; не вдається прочитати {missing}: спочатку відновіть або оновіть їхні зв’язки +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show тут неможливо прочитати {n} пов’язаний файл: відображається його попередній перегляд|тут неможливо прочитати {n} пов’язані файли: відображаються їх попередні перегляди|тут неможливо прочитати {n} пов’язаних файлів: відображаються їх попередні перегляди +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes не вдалося декодувати {n} зображення: воно показане як перекреслена рамка|не вдалося декодувати {n} зображення: вони показані як перекреслені рамки|не вдалося декодувати {n} зображень: вони показані як перекреслені рамки +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} пов’язане зображення змінилося на диску: «Оновити зв’язки» покаже нову версію|{n} пов’язані зображення змінилися на диску: «Оновити зв’язки» покаже нові версії|{n} пов’язаних зображень змінилися на диску: «Оновити зв’язки» покаже нові версії +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Оновлено {n} пов’язаний файл, змінений на диску|Оновлено {n} пов’язані файли, змінені на диску|Оновлено {n} пов’язаних файлів, змінених на диску +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Експортовано: {what} з {n} приміткою: {first}|Експортовано: {what} з {n} примітками: {first}|Експортовано: {what} з {n} примітками: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} файл шрифту тепер у {folder}|{n} файли шрифтів тепер у {folder}|{n} файлів шрифтів тепер у {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} файл шрифту тепер у {folder}; не вдалося додати {failed}: {reason}|{n} файли шрифтів тепер у {folder}; не вдалося додати {failed}: {reason}|{n} файлів шрифтів тепер у {folder}; не вдалося додати {failed}: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font тут недоступний {n} шрифт: його текст показано іншим шрифтом|тут недоступні {n} шрифти: їхній текст показано іншим шрифтом|тут недоступно {n} шрифтів: їхній текст показано іншим шрифтом +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Скопійовано CSS {n} об’єкта|Скопійовано CSS {n} об’єктів|Скопійовано CSS {n} об’єктів +@msgplural Downloaded {n} file|Downloaded {n} files Завантажено {n} файл|Завантажено {n} файли|Завантажено {n} файлів +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Експортовано {n} файл до {folder}|Експортовано {n} файли до {folder}|Експортовано {n} файлів до {folder} @msg Unembedded to {_1} Вилучено у {_1} @msg Reset {_1} Скинуто: {_1} @msg Sent to {_1} Відправлено до {_1} @@ -4598,9 +4604,6 @@ axis Both Обидві @msg every search thread stopped on an internal error (please report this bug) усі потоки пошуку зупинилися через внутрішню помилку (повідомте про цю помилку) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it Папку Fonts VectorCraft тут не задано: її задають настільна програма та vectorcraft-cli @msg choose the font files to add виберіть файли шрифтів для додавання -@msg {n} font file(s) are now in {folder} Файлів шрифтів тепер у {folder}: {n} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} Файлів шрифтів тепер у {folder}: {n}; не вдалося додати {failed}: {reason} -@msg {n} font(s) aren't available here: their text shows in another font тут недоступно шрифтів: {n}; їхній текст показано іншим шрифтом @msg not a file не файл @msg not a font file не файл шрифту @msg that document is no longer open цей документ більше не відкрито @@ -4609,7 +4612,6 @@ axis Both Обидві @msg every numbered name for it is taken in the Fonts folder усі нумеровані імена для нього вже зайняті в папці Fonts @msg every numbered name for {name} is taken in the document's folder усі нумеровані імена для {name} уже зайняті в папці документа @msg No linked files to look for Немає пов’язаних файлів для пошуку -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} Відновлено зв’язок із зображеннями: {n}; не вдалося відновити зв’язок із {name}: {reason} Services Служби Hide VectorCraft Приховати VectorCraft Zoom Масштаб diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index e2bbed903a..a5ef6b2e0d 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4330,7 +4330,6 @@ theme Appearance Giao diện @msg compressed (RLE) bitmaps can't be read yet bitmap nén (RLE) chưa thể đọc được @msg Convert to Artboards: selection has no area Chuyển thành bảng vẽ: vùng chọn không có diện tích @msg Convert to Shape: no rectangles or ellipses selected Chuyển thành hình dạng: chưa chọn hình chữ nhật hay hình elip -@msg Copied the CSS of {rules} object(s) Đã sao chép CSS của {rules} đối tượng @msg Copied the script report Đã sao chép báo cáo script @msg Corners edits the corners of a path Corners chỉnh sửa các góc của đường dẫn @msg could not decode image: {0} không thể giải mã ảnh: {0} @@ -4355,11 +4354,8 @@ theme Appearance Giao diện @msg Divide Objects Below: select a path Chia đối tượng bên dưới: hãy chọn một đường dẫn @msg Divide Objects Below: select exactly one path Chia đối tượng bên dưới: chọn đúng một đường dẫn @msg docking action contains an unknown panel or an excessive split path hành động neo chứa bảng không xác định hoặc đường dẫn tách quá dài -@msg Downloaded {_1} file(s) Đã tải xuống {_1} tệp @msg Downloaded {what} Đã tải xuống {what} @msg effect {k} is `{_1}`, not `{id}` hiệu ứng {k} là `{_1}`, không phải `{id}` -@msg Embedded {n} image(s) Đã nhúng {n} ảnh -@msg Embedded {n} image(s); {missing} missing: relink them first Đã nhúng {n} ảnh; thiếu {missing}: hãy liên kết lại trước @msg empty brush stroke nét cọ trống @msg empty cutter dao cắt trống @msg empty path đường dẫn trống @@ -4370,10 +4366,8 @@ theme Appearance Giao diện @msg Expand: no brush strokes selected Mở rộng: chưa chọn nét cọ @msg Expand: no gradient fills Mở rộng: không có tô chuyển sắc @msg Expand: nothing to expand Mở rộng: không có gì để mở rộng -@msg Exported {count} file(s) to {folder} Đã xuất {count} tệp vào {folder} @msg Exported {path} Đã xuất {path} @msg Exported {what} Đã xuất {what} -@msg Exported {what} with {_1} note(s): {first} Đã xuất {what} với {_1} ghi chú: {first} @msg Exporting {_1} Đang xuất {_1} @msg Packaging {_1} Đang đóng gói {_1} @msg Placing {_1} Đang đặt {_1} @@ -4662,10 +4656,26 @@ theme Appearance Giao diện @msg recovery copy `{file}`: {e} bản sao phục hồi `{file}`: {e} @msg Release Guides: no guides Giải phóng đường căn: không có đường căn @msg Release: no layer to put the rectangle in Giải phóng: không có lớp để đặt hình chữ nhật -@msg Relinked {_1} image(s) Đã liên kết lại {_1} ảnh -@msg Relinked {n} image(s) Đã liên kết lại {n} ảnh -@msg Relinked {n} image(s); not in that folder: {_1} Đã liên kết lại {n} ảnh; không có trong thư mục đó: {_1} -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} Đã liên kết lại {n} ảnh; {name} không thể liên kết lại: {reason} +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Đã nhúng {n} ảnh; thiếu {missing}: hãy liên kết lại trước +@msgplural Embedded {n} image|Embedded {n} images Đã nhúng {n} ảnh +@msgplural Relinked {n} image|Relinked {n} images Đã liên kết lại {n} ảnh +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} Đã liên kết lại {n} ảnh; không có trong thư mục đó: {names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} Đã liên kết lại {n} ảnh; {name} không thể liên kết lại: {reason} +@msgplural Updated {n} image|Updated {n} images Đã cập nhật {n} ảnh +@msgplural Replaced {n} image|Replaced {n} images Đã thay thế {n} ảnh +@msgplural Broke {n} link|Broke {n} links Đã ngắt {n} liên kết +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first Đã ngắt {n} liên kết; không thể đọc {missing}: hãy liên kết lại hoặc cập nhật trước +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} tệp liên kết không thể đọc ở đây: bản xem trước được hiển thị +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes {n} hình ảnh không thể giải mã: chúng hiển thị dưới dạng khung có dấu gạch chéo +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} ảnh liên kết đã thay đổi trên đĩa: Cập nhật liên kết hiển thị phiên bản mới +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Đã cập nhật {n} tệp liên kết đã thay đổi trên đĩa +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Đã xuất {what} với {n} ghi chú: {first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} tệp phông chữ hiện ở trong {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} tệp phông chữ hiện ở trong {folder}; {failed} không thể thêm: {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} phông chữ không khả dụng ở đây: văn bản hiển thị bằng phông khác +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Đã sao chép CSS của {n} đối tượng +@msgplural Downloaded {n} file|Downloaded {n} files Đã tải xuống {n} tệp +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Đã xuất {n} tệp vào {folder} @msg Reload the page to go on (changes not saved yet may be lost). Tải lại trang để tiếp tục (các thay đổi chưa lưu có thể bị mất). @msg Replace Spine: select a blend and a path Thay thế trục: chọn một đối tượng hòa trộn và một đường dẫn @msg Reset {_1} Đã đặt lại {_1} @@ -4884,8 +4894,6 @@ theme Appearance Giao diện @msg unknown workspace (one of {_1}) không gian làm việc không xác định (một trong {_1}) @msg unsupported native docking operation thao tác neo gốc không được hỗ trợ @msg unsupported: {0} không được hỗ trợ: {0} -@msg Updated {_1} image(s) Đã cập nhật {_1} ảnh -@msg Updated {_1} linked file(s) changed on disk Đã cập nhật {_1} tệp liên kết đã thay đổi trên đĩa @msg variables are locked biến số bị khóa @msg variables that aren't text were left out: {kinds} các biến số không phải văn bản đã bị bỏ qua: {kinds} @msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft không tìm kiếm trong thư mục của ứng dụng khác hoặc hệ thống: {path} @@ -4914,9 +4922,6 @@ theme Appearance Giao diện @msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` có {size} byte (giới hạn {MAX_DOCUMENT_DATA}) @msg {_1} is already used by {_2} {_1} đã được dùng bởi {_2} @msg {_1} is reserved by the system {_1} được hệ thống dành riêng -@msg {_1} linked file(s) can't be read here: their previews show {_1} tệp liên kết không thể đọc ở đây: bản xem trước được hiển thị -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes {undecoded} hình ảnh không thể giải mã: chúng hiển thị dưới dạng khung có dấu gạch chéo -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} ảnh liên kết đã thay đổi trên đĩa: Cập nhật liên kết hiển thị phiên bản mới @msg {_1}: not saved, so not closed {_1}: chưa lưu, nên không đóng @msg {bpp}-bit bitmaps can't be read bitmap {bpp}-bit không thể đọc được @msg {command} didn't create an object {command} không tạo đối tượng @@ -4933,9 +4938,6 @@ theme Appearance Giao diện @msg {name}: CRC mismatch {name}: CRC không khớp @msg {name}: no local header {name}: không có tiêu đề cục bộ @msg {name}: no such recovery entry {name}: không có mục phục hồi như vậy -@msg {n} font file(s) are now in {folder} {n} tệp phông chữ hiện ở trong {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} tệp phông chữ hiện ở trong {folder}; {failed} không thể thêm: {reason} -@msg {n} font(s) aren't available here: their text shows in another font {n} phông chữ không khả dụng ở đây: văn bản hiển thị bằng phông khác @msg {path} can't be found: relink it first {path} không tìm thấy: hãy liên kết lại trước @msg {path} is not a folder {path} không phải là thư mục @msg {path}: no file system here (pass dataBase64 to open; omit the path to get dataBase64) {path}: không có hệ thống tệp ở đây (truyền dataBase64 để mở; bỏ path để nhận dataBase64) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index ae44d95484..75d3e9dfdc 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3399,7 +3399,6 @@ digits Malayalam 马拉雅拉姆数字 Update Links 更新链接 Update Changed Links 更新已更改的链接 @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? 有 {n} 个链接图像已在磁盘上更改。要显示新版本吗? -@msg Updated {_1} linked file(s) changed on disk 已更新 {_1} 个在磁盘上更改的链接文件 @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel 链接的图片在找到其文件之前显示文件中存储的低分辨率预览:请在“链接”面板中重新链接 @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise 框架高度不足以容纳所显示字体一行的区域文字已加高框架 ({_1}):否则文字不会显示 Update Modified Links 更新已修改的链接 @@ -3744,7 +3743,6 @@ imageTrace Outline 轮廓 @msg the drawing is too large to open 图纸过大,无法打开 @msg scale must be a number from {_1} to {_2}, not {_3} 比例必须是 {_1} 到 {_2} 之间的数字,而不是 {_3} @msg an image has no pixels and was left out 已略去没有像素的图像 -@msg Embedded {n} image(s) 已嵌入 {n} 张图像 @msg object {0} cannot have children 对象 {0} 不能包含子对象 @msg range `{s}` is empty 范围 `{s}` 为空 @msg range `{s}`: `{part}` names no number 范围 `{s}`:`{part}` 未指定数字 @@ -4194,9 +4192,6 @@ imageTrace Outline 轮廓 @msg the PDF is no longer loaded 该 PDF 已不再加载 @msg no such layer or object 没有此图层或对象 @msg `{tool}` isn't a Liquify tool `{tool}` 不是液化工具 -@msg {_1} linked file(s) can't be read here: their previews show 此处无法读取 {_1} 个链接文件:显示的是其预览 -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes 无法解码 {undecoded} 张图像:它们显示为打叉的方框 -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions 有 {_1} 个链接图像已在磁盘上更改:“更新链接”可显示新版本 @msg pick a colour, gradient or pattern to save as a swatch 请选取要保存为色板的颜色、渐变或图案 @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} 已将 {n} 个文件打包到 {folder}({note}) @msg Packaged {n} file(s){note} 已打包 {n} 个文件{note} @@ -4224,7 +4219,6 @@ imageTrace Outline 轮廓 @msg print settings are not an object 打印设置不是对象 @msg no colour group `{g}` 没有颜色组 `{g}` @msg select artwork (or a colour group) to recolor 请选择要重新着色的图稿 (或颜色组) -@msg Downloaded {_1} file(s) 已下载 {_1} 个文件 @msg Preview in Browser needs the desktop app (the web downloads files instead) “在浏览器中预览”需要桌面应用 (网页版会改为下载文件) @msg no file system here 此处没有文件系统 @msg nothing to preview 没有可预览的内容 @@ -4252,7 +4246,6 @@ imageTrace Outline 轮廓 @msg unknown panel `{raw}` 未知面板 `{raw}` @msg x and y must both be numbers x 和 y 都必须是数字 @msg Downloaded {what} 已下载 {what} -@msg Exported {count} file(s) to {folder} 已将 {count} 个文件导出到 {folder} @msg Imported {what}: {_1} 已导入 {what}:{_1} @msg Installed plug-in {_1} 已安装增效工具 {_1} @msg Opened with {_1} note(s): {_2} 已打开,有 {_1} 条注释:{_2} @@ -4266,7 +4259,6 @@ imageTrace Outline 轮廓 @msg the document has never been saved 该文档从未保存过 @msg the export returned unreadable data 导出返回了无法读取的数据 @msg {status} ({e}) {status} ({e}) -@msg Exported {what} with {_1} note(s): {first} 已导出 {what},有 {_1} 条注释:{first} @msg Saved {path} with {_1} note(s): {first} 已保存 {path},有 {_1} 条注释:{first} @msg Couldn't open {name}: {e} 无法打开 {name}:{e} @msg Couldn't read {name}: {e} 无法读取 {name}:{e} @@ -4322,7 +4314,6 @@ imageTrace Outline 轮廓 @msg the library item is damaged 库项目已损坏 @msg {_1} font families available 有 {_1} 个可用的字体系列 @msg {_1} has no {_2} style {_1} 没有 {_2} 样式 -@msg Copied the CSS of {rules} object(s) 已复制 {rules} 个对象的 CSS @msg Copied the script report 已复制脚本报告 @msg Exported {path} 已导出 {path} @msg no CSS to copy: select objects with CSS of their own 没有可复制的 CSS:请选择带有自身 CSS 的对象 @@ -4335,12 +4326,27 @@ imageTrace Outline 轮廓 @msg no library `{key}` (see {list}) 没有库 `{key}` (请参阅 {list}) @msg select a linked image: an embedded one has no file 请选择链接的图像:嵌入的图像没有文件 @msg {path} can't be found: relink it first 找不到 {path}:请先重新链接 -@msg Embedded {n} image(s); {missing} missing: relink them first 已嵌入 {n} 张图像;缺少 {missing} 张:请先重新链接 -@msg Relinked {_1} image(s) 已重新链接 {_1} 张图像 -@msg Relinked {n} image(s) 已重新链接 {n} 张图像 -@msg Relinked {n} image(s); not in that folder: {_1} 已重新链接 {n} 张图像;不在该文件夹中:{_1} +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first 已嵌入 {n} 张图像;缺少 {missing} 张:请先重新链接 +@msgplural Embedded {n} image|Embedded {n} images 已嵌入 {n} 张图像 +@msgplural Relinked {n} image|Relinked {n} images 已重新链接 {n} 张图像 +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} 已重新链接 {n} 张图像;不在该文件夹中:{names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} 已重新链接 {n} 张图像;无法重新链接 {name}:{reason} +@msgplural Updated {n} image|Updated {n} images 已更新 {n} 张图像 +@msgplural Replaced {n} image|Replaced {n} images 已替换 {n} 张图像 +@msgplural Broke {n} link|Broke {n} links 已断开 {n} 个链接 +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first 已断开 {n} 个链接;有 {missing} 个无法读取:请先重新链接或更新 +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show 此处无法读取 {n} 个链接文件:显示的是其预览 +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes 无法解码 {n} 张图像:它们显示为打叉的方框 +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions 有 {n} 个链接图像已在磁盘上更改:“更新链接”可显示新版本 +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk 已更新 {n} 个在磁盘上更改的链接文件 +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} 已导出 {what},有 {n} 条注释:{first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} 个字体文件现已位于 {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} 个字体文件现已位于 {folder};有 {failed} 个无法添加:{reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font 此处没有 {n} 种字体:使用它们的文字以其他字体显示 +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects 已复制 {n} 个对象的 CSS +@msgplural Downloaded {n} file|Downloaded {n} files 已下载 {n} 个文件 +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} 已将 {n} 个文件导出到 {folder} @msg Unembedded to {_1} 已取消嵌入到 {_1} -@msg Updated {_1} image(s) 已更新 {_1} 张图像 @msg no swatch library `{l}` (see swatch.library.list) 没有色板库 `{l}` (请参阅 swatch.library.list) @msg no user library folder here 此处没有用户库文件夹 @msg Couldn't place {name}: the document it was dropped on was closed 无法置入 {name}:将它拖放到的文档已关闭 @@ -4397,9 +4403,6 @@ imageTrace Outline 轮廓 @msg every search thread stopped on an internal error (please report this bug) 所有搜索线程均因内部错误而停止 (请报告此错误) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it 此处未设置 VectorCraft 的字体文件夹:桌面应用和 vectorcraft-cli 会设置该文件夹 @msg choose the font files to add 请选择要添加的字体文件 -@msg {n} font file(s) are now in {folder} {n} 个字体文件现已位于 {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} 个字体文件现已位于 {folder};有 {failed} 个无法添加:{reason} -@msg {n} font(s) aren't available here: their text shows in another font 此处没有 {n} 种字体:使用它们的文字以其他字体显示 @msg not a file 不是文件 @msg not a font file 不是字体文件 @msg that document is no longer open 该文档已不再打开 @@ -4408,7 +4411,6 @@ imageTrace Outline 轮廓 @msg every numbered name for it is taken in the Fonts folder 字体文件夹中所有带编号的名称均已被占用 @msg every numbered name for {name} is taken in the document's folder 文档所在文件夹中 {name} 的所有带编号的名称均已被占用 @msg No linked files to look for 没有要查找的链接文件 -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} 已重新链接 {n} 张图像;无法重新链接 {name}:{reason} @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` 是步骤引用 {r},只有 `run` 和 `command_batch` 能解析它 @msg `ids` must be an array of object ids, not {v} `ids` 必须是由对象 id 组成的数组,而不是 {v} @msg `corners` must be an array of anchor indices, not {v} `corners` 必须是由锚点索引组成的数组,而不是 {v} diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 454747090b..e51a8896e0 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1668,7 +1668,6 @@ file-filter Templates 範本 @msg the drawing is too large to open 圖面過大,無法開啟 @msg scale must be a number from {_1} to {_2}, not {_3} 比例必須是 {_1} 到 {_2} 之間的數字,而非 {_3} @msg an image has no pixels and was left out 已略過沒有像素的影像 -@msg Embedded {n} image(s) 已內嵌 {n} 個影像 @msg object {0} cannot have children 物件 {0} 不能有子物件 @msg range `{s}` is empty 範圍 `{s}` 是空的 @msg range `{s}`: `{part}` names no number 範圍 `{s}`:`{part}` 沒有指定數字 @@ -2116,9 +2115,6 @@ file-filter Templates 範本 @msg the PDF is no longer loaded 此 PDF 已不再載入 @msg no such layer or object 沒有這個圖層或物件 @msg `{tool}` isn't a Liquify tool `{tool}` 不是液化工具 -@msg {_1} linked file(s) can't be read here: their previews show 此處無法讀取 {_1} 個連結檔案:顯示的是其預覽 -@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes 無法解碼 {undecoded} 張影像:它們顯示為打叉的方框 -@msg {_1} linked image(s) changed on disk: Update Links shows the new versions 有 {_1} 個連結影像已在磁碟上變更:「更新連結」可顯示新版本 @msg pick a colour, gradient or pattern to save as a swatch 請挑選要儲存為色票的顏色、漸層或圖樣 @msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} 已將 {n} 個檔案封裝到 {folder}({note}) @msg Packaged {n} file(s){note} 已封裝 {n} 個檔案{note} @@ -2146,7 +2142,6 @@ file-filter Templates 範本 @msg print settings are not an object 列印設定不是物件 @msg no colour group `{g}` 沒有顏色群組 `{g}` @msg select artwork (or a colour group) to recolor 請選取要重新上色的圖稿 (或顏色群組) -@msg Downloaded {_1} file(s) 已下載 {_1} 個檔案 @msg Preview in Browser needs the desktop app (the web downloads files instead) 「在瀏覽器中預覽」需要桌面應用程式 (網頁版會改為下載檔案) @msg no file system here 此處沒有檔案系統 @msg nothing to preview 沒有可預覽的內容 @@ -2174,7 +2169,6 @@ file-filter Templates 範本 @msg unknown panel `{raw}` 未知的面板 `{raw}` @msg x and y must both be numbers x 和 y 都必須是數字 @msg Downloaded {what} 已下載 {what} -@msg Exported {count} file(s) to {folder} 已將 {count} 個檔案匯出至 {folder} @msg Imported {what}: {_1} 已匯入 {what}:{_1} @msg Installed plug-in {_1} 已安裝增效模組 {_1} @msg Opened with {_1} note(s): {_2} 已開啟,附有 {_1} 則註解:{_2} @@ -2188,7 +2182,6 @@ file-filter Templates 範本 @msg the document has never been saved 文件從未儲存過 @msg the export returned unreadable data 匯出傳回了無法讀取的資料 @msg {status} ({e}) {status} ({e}) -@msg Exported {what} with {_1} note(s): {first} 已匯出 {what},附有 {_1} 則註解:{first} @msg Saved {path} with {_1} note(s): {first} 已儲存 {path},附有 {_1} 則註解:{first} @msg Couldn't open {name}: {e} 無法開啟 {name}:{e} @msg Couldn't read {name}: {e} 無法讀取 {name}:{e} @@ -2244,7 +2237,6 @@ file-filter Templates 範本 @msg the library item is damaged 資料庫項目已損毀 @msg {_1} font families available 有 {_1} 個可用的字體家族 @msg {_1} has no {_2} style {_1} 沒有 {_2} 樣式 -@msg Copied the CSS of {rules} object(s) 已複製 {rules} 個物件的 CSS @msg Copied the script report 已複製指令碼報告 @msg Exported {path} 已匯出 {path} @msg no CSS to copy: select objects with CSS of their own 沒有可複製的 CSS:請選取有自己 CSS 的物件 @@ -2257,12 +2249,27 @@ file-filter Templates 範本 @msg no library `{key}` (see {list}) 沒有資料庫 `{key}` (請參閱 {list}) @msg select a linked image: an embedded one has no file 請選取連結的影像:內嵌的影像沒有檔案 @msg {path} can't be found: relink it first 找不到 {path}:請先重新連結 -@msg Embedded {n} image(s); {missing} missing: relink them first 已內嵌 {n} 個影像;遺失 {missing} 個:請先重新連結 -@msg Relinked {_1} image(s) 已重新連結 {_1} 個影像 -@msg Relinked {n} image(s) 已重新連結 {n} 個影像 -@msg Relinked {n} image(s); not in that folder: {_1} 已重新連結 {n} 個影像;不在該資料夾中:{_1} +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first 已內嵌 {n} 個影像;遺失 {missing} 個:請先重新連結 +@msgplural Embedded {n} image|Embedded {n} images 已內嵌 {n} 個影像 +@msgplural Relinked {n} image|Relinked {n} images 已重新連結 {n} 個影像 +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} 已重新連結 {n} 個影像;不在該資料夾中:{names} +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} 已重新連結 {n} 個影像;無法重新連結 {name}:{reason} +@msgplural Updated {n} image|Updated {n} images 已更新 {n} 個影像 +@msgplural Replaced {n} image|Replaced {n} images 已取代 {n} 個影像 +@msgplural Broke {n} link|Broke {n} links 已中斷 {n} 個連結 +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first 已中斷 {n} 個連結;有 {missing} 個無法讀取:請先重新連結或更新 +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show 此處無法讀取 {n} 個連結檔案:顯示的是其預覽 +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes 無法解碼 {n} 張影像:它們顯示為打叉的方框 +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions 有 {n} 個連結影像已在磁碟上變更:「更新連結」可顯示新版本 +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk 已更新 {n} 個在磁碟上變更的連結檔案 +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} 已匯出 {what},附有 {n} 則註解:{first} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} 個字體檔案現已位於 {folder} +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} 個字體檔案現已位於 {folder};有 {failed} 個無法加入:{reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font 此處沒有 {n} 種字體:使用這些字體的文字會以其他字體顯示 +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects 已複製 {n} 個物件的 CSS +@msgplural Downloaded {n} file|Downloaded {n} files 已下載 {n} 個檔案 +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} 已將 {n} 個檔案匯出至 {folder} @msg Unembedded to {_1} 已取消內嵌至 {_1} -@msg Updated {_1} image(s) 已更新 {_1} 個影像 @msg no swatch library `{l}` (see swatch.library.list) 沒有色票資料庫 `{l}` (請參閱 swatch.library.list) @msg no user library folder here 此處沒有使用者資料庫資料夾 @msg Couldn't place {name}: the document it was dropped on was closed 無法置入 {name}:放置它的文件已關閉 @@ -2319,9 +2326,6 @@ file-filter Templates 範本 @msg every search thread stopped on an internal error (please report this bug) 所有搜尋執行緒都因內部錯誤而停止 (請回報此錯誤) @msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it 此處未設定 VectorCraft 的字體資料夾:桌面應用程式和 vectorcraft-cli 會設定它 @msg choose the font files to add 請選擇要加入的字體檔案 -@msg {n} font file(s) are now in {folder} {n} 個字體檔案現已位於 {folder} -@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} 個字體檔案現已位於 {folder};有 {failed} 個無法加入:{reason} -@msg {n} font(s) aren't available here: their text shows in another font 此處沒有 {n} 種字體:使用這些字體的文字會以其他字體顯示 @msg not a file 不是檔案 @msg not a font file 不是字體檔案 @msg that document is no longer open 該文件已不再開啟 @@ -2330,7 +2334,6 @@ file-filter Templates 範本 @msg every numbered name for it is taken in the Fonts folder 字體資料夾中所有編號名稱都已被使用 @msg every numbered name for {name} is taken in the document's folder 文件所在資料夾中 {name} 的所有編號名稱都已被使用 @msg No linked files to look for 沒有要尋找的連結檔案 -@msg Relinked {n} image(s); {name} couldn't be relinked: {reason} 已重新連結 {n} 個影像;無法重新連結 {name}:{reason} @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` 是步驟參照 {r},只有 `run` 和 `command_batch` 能解析它 @msg `ids` must be an array of object ids, not {v} `ids` 必須是由物件 id 組成的陣列,而非 {v} @msg `corners` must be an array of anchor indices, not {v} `corners` 必須是由錨點索引組成的陣列,而非 {v} @@ -4381,7 +4384,6 @@ digits Malayalam 馬來亞拉姆數字 Update Links 更新連結 Update Changed Links 更新已變更的連結 @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? 有 {n} 個連結影像已在磁碟上變更。要顯示新版本嗎? -@msg Updated {_1} linked file(s) changed on disk 已更新 {_1} 個在磁碟上變更的連結檔案 @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel 連結的圖片在找到其檔案之前顯示檔案中儲存的低解析度預覽:請在「連結」面板中重新連結 @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise 框架高度不足以容納所顯示字體一行的區域文字已加高框架 ({_1}):否則文字不會顯示 Update Modified Links 更新已修改的連結 diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index c6b9c26772..a9cbeea13c 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -18,7 +18,7 @@ mod open; mod save; pub use export::{EXPORT_CANCELLED, cancel_exports, export, export_for_screens, export_pdf, hide_exports, reveal, save_command_output}; -pub(crate) use export::{export_files, file_url, open_in_app, reveal_path, run_to_file, save_command_output_named}; +pub(crate) use export::{export_files, exported_with_notes, file_url, open_in_app, reveal_path, run_to_file, save_command_output_named}; #[cfg(test)] pub(crate) use open::open_file; pub(crate) use open::opened; diff --git a/crates/ui-egui/src/io/export.rs b/crates/ui-egui/src/io/export.rs index 9e463f49e9..3bb5be7d26 100644 --- a/crates/ui-egui/src/io/export.rs +++ b/crates/ui-egui/src/io/export.rs @@ -91,7 +91,7 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option<Strin }; let warnings: Vec<&str> = r["warnings"].as_array().map(|w| w.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); app.status(match warnings.first() { - Some(first) => format!("Exported {what} with {} note(s): {first}", warnings.len()), + Some(first) => exported_with_notes(&what, warnings.len(), first), None => format!("Exported {what}"), }); Ok(r) @@ -102,6 +102,12 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option<Strin Ok(r) } +/// The status bar's line for an export of `what` with `n` notes, the first of them `first`. +pub(crate) fn exported_with_notes(what: &str, n: usize, first: &str) -> String { + let (one, other) = ("Exported {what} with {n} note: {first}", "Exported {what} with {n} notes: {first}"); + crate::i18n::msg_n(n as u64, one, other, &[("what", what), ("first", first)]) +} + /// Run an engine command that returns `{dataBase64}` and write the bytes to a picked path /// (Export Selection, Save for Office Documents, Text Export Options and the presets dialogs' /// Export…), reported with the first of the command's warnings ([`report_saved`]). @@ -273,7 +279,7 @@ fn report_exported(app: &mut VectorcraftApp, r: Value, folder: &str, open_locati }; if returned.is_empty() { let first = r["path"].as_str().or_else(|| r["files"][0].as_str()); - let mut status = format!("Exported {count} file(s) to {folder}"); + let mut status = crate::i18n::msg_n(count as u64, "Exported {n} file to {folder}", "Exported {n} files to {folder}", &[("folder", folder)]); if warned { status = saved_status(r["path"].as_str().unwrap_or(folder), &r); } diff --git a/crates/ui-egui/src/panels/css_properties.rs b/crates/ui-egui/src/panels/css_properties.rs index 97e270e3c8..bc362fb576 100644 --- a/crates/ui-egui/src/panels/css_properties.rs +++ b/crates/ui-egui/src/panels/css_properties.rs @@ -182,7 +182,7 @@ pub(crate) fn copy(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> let css = r["css"].as_str().filter(|c| !c.is_empty()).ok_or("no CSS to copy: select objects with CSS of their own")?.to_string(); let rules = r["rules"].as_array().map_or(0, Vec::len); app.clipboard_out = Some(css.clone()); - app.status(format!("Copied the CSS of {rules} object(s)")); + app.status(crate::i18n::msg_n(rules as u64, "Copied the CSS of {n} object", "Copied the CSS of {n} objects", &[])); Ok(json!({ "css": css, "rules": rules })) } @@ -208,7 +208,7 @@ pub(crate) fn export_file(app: &mut VectorcraftApp, p: &Value) -> Result<Value, let warnings: Vec<&str> = r["warnings"].as_array().map(|w| w.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); let what = &path; app.status(match warnings.first() { - Some(first) => format!("Exported {what} with {} note(s): {first}", warnings.len()), + Some(first) => io::exported_with_notes(what, warnings.len(), first), None => format!("Exported {path}"), }); Ok(json!({ "path": path, "rules": r["rules"], "images": images, "warnings": r["warnings"] })) diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 85665215ed..80196fcd90 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -117,6 +117,16 @@ fn report(app: &mut VectorcraftApp, r: Result<Value, String>, done: impl FnOnce( app.status(msg); } +/// The status bar's line for `n` relinked images. +pub(crate) fn relinked_status(n: usize) -> String { + crate::i18n::msg_n(n as u64, "Relinked {n} image", "Relinked {n} images", &[]) +} + +/// The status bar's line for `n` images read again from their updated files. +pub(crate) fn updated_status(n: usize) -> String { + crate::i18n::msg_n(n as u64, "Updated {n} image", "Updated {n} images", &[]) +} + /// Relink images `ids` to a picked file. pub(crate) fn relink(app: &mut VectorcraftApp, ids: Vec<u64>) { crate::picks::button(app, move |app| relink_picked(app, ids.clone())); @@ -126,7 +136,7 @@ fn relink_picked(app: &mut VectorcraftApp, ids: Vec<u64>) { let pick = crate::FilePick { filters: crate::FilePick::filters(vectorcraft_engine::cmd::fileio::place_filters()), ..Default::default() }; let Some(path) = crate::picks::open(app, &pick) else { return }; let r = app.run("links.relink", json!({ "ids": ids, "path": path })); - report(app, r, |v| format!("Relinked {} image(s)", v["relinked"].as_array().map_or(0, Vec::len))); + report(app, r, |v| relinked_status(v["relinked"].as_array().map_or(0, Vec::len))); } /// Replace images `ids` with a picked file (Control bar, Properties): it keeps its own aspect @@ -137,7 +147,7 @@ pub(crate) fn replace(app: &mut VectorcraftApp, ids: Vec<u64>) { let pick = crate::FilePick { filters: crate::FilePick::filters(vectorcraft_engine::cmd::fileio::place_filters()), ..Default::default() }; let Some(path) = crate::picks::open(app, &pick) else { return }; let r = app.run("links.relink", json!({ "ids": ids.clone(), "path": path, "preserve": "fit" })); - report(app, r, |v| format!("Replaced {} image(s)", v["relinked"].as_array().map_or(0, Vec::len))); + report(app, r, |v| crate::i18n::msg_n(v["relinked"].as_array().map_or(0, Vec::len) as u64, "Replaced {n} image", "Replaced {n} images", &[])); }); } @@ -153,7 +163,12 @@ fn relink_to_picked_folder(app: &mut VectorcraftApp, ids: Vec<u64>) { report(app, r, |v| { let missed: Vec<&str> = v["notFound"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); let n = v["relinked"].as_array().map_or(0, Vec::len); - if missed.is_empty() { format!("Relinked {n} image(s)") } else { format!("Relinked {n} image(s); not in that folder: {}", missed.join(", ")) } + if missed.is_empty() { + relinked_status(n) + } else { + let (one, other) = ("Relinked {n} image; not in that folder: {names}", "Relinked {n} images; not in that folder: {names}"); + crate::i18n::msg_n(n as u64, one, other, &[("names", &missed.join(", "))]) + } }); } @@ -400,7 +415,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } if widgets::icon_button_enabled(ui, "rotate-cw", tl!("Update Link"), false, !modified.is_empty(), 24.0).clicked() { let r = app.run("links.update", json!({ "ids": modified })); - report(app, r, |v| format!("Updated {} image(s)", v["updated"].as_array().map_or(0, Vec::len))); + report(app, r, |v| updated_status(v["updated"].as_array().map_or(0, Vec::len))); } if widgets::icon_button_enabled(ui, "zoom-in", tl!("Go To Link"), false, sel.len() == 1, 24.0).clicked() && let Some(id) = sel.first().and_then(|r| r["id"].as_u64()) @@ -424,7 +439,16 @@ fn break_link(app: &mut VectorcraftApp, ids: Vec<u64>) { report(app, r, |v| { let missing = v["missing"].as_array().map_or(0, Vec::len); let n = v["embedded"].as_array().map_or(0, Vec::len); - if missing == 0 { format!("Broke {n} link(s)") } else { format!("Broke {n} link(s); {missing} can't be read: relink or update them first") } + if missing == 0 { + crate::i18n::msg_n(n as u64, "Broke {n} link", "Broke {n} links", &[]) + } else { + crate::i18n::msg_n( + n as u64, + "Broke {n} link; {missing} can't be read: relink or update them first", + "Broke {n} links; {missing} can't be read: relink or update them first", + &[("missing", &missing.to_string())], + ) + } }); } @@ -534,7 +558,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } if menu_item(ui, tl!("Update Link"), sel.iter().any(|r| status_is(r, "modified")), false) { let r = app.run("links.update", json!({ "ids": ids(&sel, |r| status_is(r, "modified")) })); - report(app, r, |v| format!("Updated {} image(s)", v["updated"].as_array().map_or(0, Vec::len))); + report(app, r, |v| updated_status(v["updated"].as_array().map_or(0, Vec::len))); } if menu_item(ui, tl!("Edit Original"), sel.iter().any(|r| r["linked"] == true && !status_is(r, "missing")), false) { crate::menus::invoke(app, "links.editOriginal", json!({})); @@ -545,7 +569,16 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { report(app, r, |v| { let missing = v["missing"].as_array().map_or(0, Vec::len); let n = v["embedded"].as_array().map_or(0, Vec::len); - if missing == 0 { format!("Embedded {n} image(s)") } else { format!("Embedded {n} image(s); {missing} missing: relink them first") } + if missing == 0 { + crate::i18n::msg_n(n as u64, "Embedded {n} image", "Embedded {n} images", &[]) + } else { + crate::i18n::msg_n( + n as u64, + "Embedded {n} image; {missing} missing: relink them first", + "Embedded {n} images; {missing} missing: relink them first", + &[("missing", &missing.to_string())], + ) + } }); } if menu_item(ui, tl!("Unembed…"), embedded.len() == 1, false) diff --git a/crates/ui-egui/src/panels/tests_css_properties.rs b/crates/ui-egui/src/panels/tests_css_properties.rs index a23f108eb2..619be4d70b 100644 --- a/crates/ui-egui/src/panels/tests_css_properties.rs +++ b/crates/ui-egui/src/panels/tests_css_properties.rs @@ -143,6 +143,6 @@ fn export_says_in_the_status_bar_when_an_image_could_not_be_decoded() { vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({})); let r = app.run("css.exportFile", json!({"path": "/tmp/site/site.css", "scope": "all", "rasterize": true})).unwrap(); assert_eq!(r["warnings"], json!([WARNING])); - assert_eq!(app.ui.status, format!("Exported /tmp/site/site.css with 1 note(s): {WARNING}")); + assert_eq!(app.ui.status, format!("Exported /tmp/site/site.css with 1 note: {WARNING}")); assert_eq!(log.borrow().len(), 3, "the sheet and the image's picture are still written"); } diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index e8ccdf0d7a..c2b920b837 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -615,7 +615,7 @@ fn link_menu(app: &mut VectorcraftApp, ui: &mut egui::Ui, id: u64, linked: bool) } if widgets::menu_item(ui, tl!("Update Link"), linked, false) { let msg = match app.run("links.update", json!({ "ids": [id] })) { - Ok(v) => format!("Updated {} image(s)", v["updated"].as_array().map_or(0, Vec::len)), + Ok(v) => crate::panels::links::updated_status(v["updated"].as_array().map_or(0, Vec::len)), Err(e) => e, }; app.status(msg); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c1dd457607..20e77f1d18 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -591,6 +591,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The History panel, Edit › Undo and Edit › Redo translate the names of the steps that apply or redefine a character or paragraph style and of the step that redefines a graphic style: each such step keeps its template (`Apply {name}`, `Redefine {name}`, `Redefine Graphic Style “{name}”`) and the style's name, every complete catalog has a row for each template, and the panel and the menu show the style's name as the document holds it, except the Normal styles' names, which they show in the interface language (`steps_named_after_a_style_list_the_template_around_the_name`, `undo_and_redo_name_a_style_step_around_the_style_name`). - Localised UI: menus (in-window and native), panels, dialogs, toolbar and Preferences read from per-language catalogs (`crates/ui-egui/src/i18n`, see `docs/development.md`); Traditional Chinese (Taiwan), Simplified Chinese (mainland), Japanese, Korean, Vietnamese, German, Spanish, French, Italian, Polish, Brazilian Portuguese, Russian, Ukrainian, Georgian and Catalan ship complete, and Czech covers every menu label (and more), with system-locale detection on macOS, Windows, Linux and the web (the browser's languages, or `?lang=`), a Language preference and, on macOS, a VectorCraft ▸ Language menu. Names are never translated (fonts and their styles, layers, artboards, saved presets, user libraries, custom workspaces, recent files, plug-ins). The counts that Package's status and question, the folder search of Missing Fonts and Find Linked Files, the modified and missing linked file prompts and the CSS Properties panel's notes show use the interface language's plural forms instead of a fixed "(s)" form. Evidence: `the_missing_links_note_uses_each_count_form` in `crates/ui-egui/src/dialogs/tests_package.rs`, `the_modified_links_question_uses_each_count_form` in `crates/ui-egui/src/dialogs/missing_links.rs`, `search_counts_use_each_count_form` in `crates/ui-egui/src/dialogs/missing_fonts/tests.rs` and `the_unnamed_objects_note_uses_each_count_form` in `crates/ui-egui/src/panels/tests_css_properties.rs`. + The status bar's messages for relinked, replaced, updated and embedded images, broken links, linked files that can't be read or changed on disk, images that can't be decoded, added and unavailable fonts, copied CSS, downloads and exports with their notes name one item in the singular and more in the plural, in English and in each language's plural forms (`counted_status_messages_take_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). - Edit › Undo and Edit › Redo, in the in-window and native menus, name the step in the interface language as the History panel lists it (`panels::history::step_name`), so when the catalog has no plain row for a step named after an effect, such as Feather, the menu shows the translation of the effect's menu row without its ellipsis (`undo_and_redo_name_the_step_as_the_history_panel_does`). - The History panel translates the undo step names the engine, the tools and the shell write as literals: the untranslated report (`untranslated_report`) lists any a complete catalog lacks, and a step whose catalog row exists only with an ellipsis (such as an effect's menu name) shows that row without the ellipsis. - The History panel menu has Step Backward and Step Forward, which run Edit › Undo and Edit › Redo and are disabled when there is no step to undo or redo, and Set History Limit…, which opens Preferences at Performance, where History States is set. Not done: a new document from the selected state. From 1e14719c1608b40abf5eb6f215c36bd8a6d5c0f7 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 15:35:17 -0700 Subject: [PATCH 217/260] i18n: French rows keep the no-break space before punctuation --- crates/ui-egui/src/i18n/fr.tsv | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 9ea315ee73..4c3423a194 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4505,23 +4505,23 @@ axis Both Les deux @msg Saving recovery data for {_1} Enregistrement des données de récupération de {_1} @msg Discarded {_1} recovered document(s) {_1} document(s) récupéré(s) supprimé(s) @msg Restored {_1} recovered document(s): save them to keep them {_1} document(s) récupéré(s) restauré(s) : enregistrez-les pour les conserver -@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} image incorporée ; il en manque {missing} : rétablissez d’abord leurs liens|{n} images incorporées ; il en manque {missing} : rétablissez d’abord leurs liens +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} image incorporée ; il en manque {missing} : rétablissez d’abord leurs liens|{n} images incorporées ; il en manque {missing} : rétablissez d’abord leurs liens @msgplural Embedded {n} image|Embedded {n} images {n} image incorporée|{n} images incorporées @msgplural Relinked {n} image|Relinked {n} images Lien rétabli pour {n} image|Lien rétabli pour {n} images -@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} Lien rétabli pour {n} image ; absentes de ce dossier : {names}|Lien rétabli pour {n} images ; absentes de ce dossier : {names} +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} Lien rétabli pour {n} image ; absentes de ce dossier : {names}|Lien rétabli pour {n} images ; absentes de ce dossier : {names} @msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} Lien rétabli pour {n} image, mais impossible de lier à nouveau {name} ({reason})|Lien rétabli pour {n} images, mais impossible de lier à nouveau {name} ({reason}) @msgplural Updated {n} image|Updated {n} images {n} image mise à jour|{n} images mises à jour @msgplural Replaced {n} image|Replaced {n} images {n} image remplacée|{n} images remplacées @msgplural Broke {n} link|Broke {n} links {n} lien rompu|{n} liens rompus -@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first {n} lien rompu ; lecture impossible pour {missing} : rétablissez ou mettez d’abord à jour leurs liens|{n} liens rompus ; lecture impossible pour {missing} : rétablissez ou mettez d’abord à jour leurs liens -@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} fichier lié illisible ici : son aperçu est affiché|{n} fichiers liés illisibles ici : leurs aperçus sont affichés +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first {n} lien rompu ; lecture impossible pour {missing} : rétablissez ou mettez d’abord à jour leurs liens|{n} liens rompus ; lecture impossible pour {missing} : rétablissez ou mettez d’abord à jour leurs liens +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} fichier lié illisible ici : son aperçu est affiché|{n} fichiers liés illisibles ici : leurs aperçus sont affichés @msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes {n} image impossible à décoder, affichée sous forme de cadre barré d’une croix|{n} images impossibles à décoder, affichées sous forme de cadres barrés d’une croix -@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} image liée modifiée sur le disque : Mettre à jour les liens affiche la nouvelle version|{n} images liées modifiées sur le disque : Mettre à jour les liens affiche les nouvelles versions +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} image liée modifiée sur le disque : Mettre à jour les liens affiche la nouvelle version|{n} images liées modifiées sur le disque : Mettre à jour les liens affiche les nouvelles versions @msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk {n} fichier lié modifié sur le disque mis à jour|{n} fichiers liés modifiés sur le disque mis à jour -@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} {what} exporté avec {n} remarque : {first}|{what} exporté avec {n} remarques : {first} +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} {what} exporté avec {n} remarque : {first}|{what} exporté avec {n} remarques : {first} @msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} fichier de polices se trouve maintenant dans {folder}|{n} fichiers de polices se trouvent maintenant dans {folder} -@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} fichier de polices se trouve maintenant dans {folder} ; {failed} n’ont pas pu être ajoutés : {reason}|{n} fichiers de polices se trouvent maintenant dans {folder} ; {failed} n’ont pas pu être ajoutés : {reason} -@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} police indisponible ici : son texte s’affiche dans une autre police|{n} polices indisponibles ici : leur texte s’affiche dans une autre police +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} fichier de polices se trouve maintenant dans {folder} ; {failed} n’ont pas pu être ajoutés : {reason}|{n} fichiers de polices se trouvent maintenant dans {folder} ; {failed} n’ont pas pu être ajoutés : {reason} +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} police indisponible ici : son texte s’affiche dans une autre police|{n} polices indisponibles ici : leur texte s’affiche dans une autre police @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects CSS de {n} objet copié|CSS de {n} objets copié @msgplural Downloaded {n} file|Downloaded {n} files {n} fichier téléchargé|{n} fichiers téléchargés @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} fichier exporté vers {folder}|{n} fichiers exportés vers {folder} From 5b639169cde5e7d0e4b34cad082787add71c7f56 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sun, 1 Nov 2026 02:47:13 +0300 Subject: [PATCH 218/260] Fix #4918: Symbols panel Select All Unused symbol.unused lists the symbols nothing places: instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. The Symbols panel menu's Select All Unused shows them selected, and Delete Symbol asks once and deletes those still unused in one undo step (symbol.delete {names}). --- crates/engine/src/cmd/brushsym.rs | 13 ++- crates/engine/src/cmd/brushsym/symbols.rs | 84 +++++++++++++--- crates/engine/src/tests/brushsym.rs | 57 +++++++++++ crates/ui-egui/src/dialogs/symbol_delete.rs | 49 ++++++++- crates/ui-egui/src/panels/symbols.rs | 106 ++++++++++++++++++-- docs/mcp.md | 8 +- docs/target-app-parity.md | 4 +- 7 files changed, 290 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 4f335dc0cb..7f78aa2465 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -38,7 +38,7 @@ use symbols::selected_instances; pub(crate) use symbols::{instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol}; use symbols::{ symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_edit, symbol_list, symbol_new, symbol_options, symbol_place, - symbol_replace, symbol_select_instances, symbol_set_current, symbol_spray, symbol_update, + symbol_replace, symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update, }; const SIZES_KEY: &str = vectorcraft_doc::SYMBOL_SIZES; @@ -228,7 +228,7 @@ pub fn specs() -> Vec<CommandSpec> { "Delete Symbol", [], None, - "{name, expandInstances?: true} delete a symbol; its instances are expanded (or deleted with false)", + "{name | names: [name…], expandInstances?: true} delete a symbol (or several, in one undo step); its instances are expanded (or deleted with false)", has_doc, symbol_delete ), @@ -269,6 +269,15 @@ pub fn specs() -> Vec<CommandSpec> { has_doc, symbol_set_current ), + cmd!( + query "symbol.unused", + "Select All Unused", + [], + None, + "{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used", + has_doc, + symbol_unused + ), cmd!(query "symbol.selectInstances", "Select All Instances", [], None, "{name} select every instance of a symbol → {count}", has_doc, symbol_select_instances), cmd!( "symbol.spray", diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index c7fe433541..c5518c70b0 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -107,6 +107,37 @@ fn instances_of(d: &Document, name: Option<&str>) -> Vec<NodeId> { v } +/// The symbols an instance in `n` (its opacity masks included) places, pushed onto `out`. +fn art_symbols(n: &Node, out: &mut Vec<String>) { + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + if let NodeKind::SymbolInstance { symbol, .. } = &m.kind { + out.push(symbol.clone()); + } + }); +} + +/// Select All Unused (#4918): the symbols nothing places. Instances in the art (opacity masks +/// included), graph designs, pattern tiles and the tiles that pattern editing's Cancel puts back, +/// and the art of the document's brushes count, and so do the instances in the art of every symbol +/// a counted instance places. A symbol placed only inside an unused symbol is unused too. +pub(super) fn symbol_unused(s: &mut Session, _: &Value) -> Result<Value> { + let d = &s.doc()?.doc; + let mut todo = vec![]; + let lib = brush::library(d); + let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref())); + let trees = d.layers.iter().map(|l| &**l).chain(d.graph_designs.iter().map(|g| &*g.art)); + trees.chain(patterns.flat_map(|p| p.art.iter().map(|n| &**n))).chain(lib.iter().flat_map(|b| b.art())).for_each(|n| art_symbols(n, &mut todo)); + let mut used = std::collections::BTreeSet::new(); + while let Some(name) = todo.pop() { + if !used.contains(&name) { + d.symbols.iter().filter(|sym| sym.name == name).for_each(|sym| art_symbols(&sym.art, &mut todo)); + used.insert(name); + } + } + let names: Vec<&str> = d.symbols.iter().map(|sym| sym.name.as_str()).filter(|n| !used.contains(*n)).collect(); + Ok(json!({ "names": names })) +} + fn symbol_names(d: &Document) -> Vec<String> { d.symbols.iter().map(|s| s.name.clone()).collect() } @@ -419,25 +450,46 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> { pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "symbol.delete"; - let name = name_param(p, C)?.to_string(); - if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) { + // `names` deletes several symbols in one undo step (the Symbols panel's Select All Unused, #4918). + let names: Vec<String> = match p.get("names") { + Some(v) => { + let a = v.as_array().ok_or_else(|| bad(C, "names must be an array of symbol names"))?; + let mut names = Vec::with_capacity(a.len()); + for n in a { + let n = n.as_str().ok_or_else(|| bad(C, "names must be an array of symbol names"))?; + if !names.iter().any(|x: &String| x == n) { + names.push(n.to_string()); + } + } + if names.is_empty() { + return Err(bad(C, "names is empty")); + } + names + } + None => vec![name_param(p, C)?.to_string()], + }; + let d = &s.doc()?.doc; + if let Some(name) = names.iter().find(|n| !d.symbols.iter().any(|x| &x.name == *n)) { return Err(bad(C, format!("no symbol named `{name}`"))); } let expand = switch_or(p, "expandInstances", true, C)?; - s.edit("Delete Symbol", |d, _| { - let inst = instances_of(d, Some(&name)); - if expand { - break_links(d, &inst, true)?; - } else { - remove_each(d, &inst)?; - } - d.symbols.retain(|x| x.name != name); - set_natural_size(d, &name, None); - d.set_symbol_registration(&name, SymbolRegistration::CENTER); - d.clear_symbol_export_type(&name); - d.set_symbol_nine_slice(&name, None); - if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { - d.unknown.remove(CURRENT_SYMBOL); + let label = if names.len() == 1 { "Delete Symbol" } else { "Delete Symbols" }; + s.edit(label, |d, _| { + for name in &names { + let inst = instances_of(d, Some(name)); + if expand { + break_links(d, &inst, true)?; + } else { + remove_each(d, &inst)?; + } + d.symbols.retain(|x| &x.name != name); + set_natural_size(d, name, None); + d.set_symbol_registration(name, SymbolRegistration::CENTER); + d.clear_symbol_export_type(name); + d.set_symbol_nine_slice(name, None); + if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { + d.unknown.remove(CURRENT_SYMBOL); + } } Ok(()) })?; diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index ef448da9de..adfe4ef117 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1432,3 +1432,60 @@ fn symbol_nine_slice_guides_round_trip() { s.execute("symbol.delete", &json!({"name": "Box copy"})).unwrap(); assert!(s.doc().unwrap().doc.unknown.get(vectorcraft_doc::SYMBOL_NINE_SLICE).is_none()); } + +/// Symbols panel › Select All Unused (#4918): a symbol counts as used when an instance in the art, +/// a pattern tile, the art of a brush or a used symbol places it; one placed only inside an unused +/// symbol is unused too. Delete Symbol with `names` deletes several in one undo step. +#[test] +fn symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several() { + let mut s = session(); + // A symbol of the selection (a new square at `x` when `x` is given), left placed. + let symbol = |s: &mut Session, name: &str, x: Option<f64>| { + if let Some(x) = x { + rect(s, x, 0.0, 10.0, 10.0); + } + NodeId(s.execute("symbol.new", &json!({"name": name})).unwrap()["id"].as_u64().unwrap()) + }; + let unused = + |s: &mut Session| -> Vec<String> { serde_json::from_value(s.execute("symbol.unused", &json!({})).unwrap()["names"].clone()).unwrap() }; + // Placed: its instance stays on the artboard. + symbol(&mut s, "Placed", Some(0.0)); + // Inner is placed only inside Outer, whose instance stays: both are used. + let inner = symbol(&mut s, "Inner", Some(20.0)); + s.execute("select.set", &json!({"ids": [inner.0]})).unwrap(); + symbol(&mut s, "Outer", None); + // Lonely's and Nested's instances go; Nested is placed only inside Lonely. + let nested = symbol(&mut s, "Nested", Some(40.0)); + s.execute("select.set", &json!({"ids": [nested.0]})).unwrap(); + let lonely = symbol(&mut s, "Lonely", None); + s.execute("edit.clear", &json!({"ids": [lonely.0]})).unwrap(); + // In a brush's art only. + let in_brush = symbol(&mut s, "Brushed", Some(60.0)); + s.execute("brush.new", &json!({"type": "art", "name": "B", "ids": [in_brush.0]})).unwrap(); + s.execute("edit.clear", &json!({"ids": [in_brush.0]})).unwrap(); + assert_eq!(unused(&mut s), ["Nested", "Lonely"], "in panel order"); + // A placed one becomes unused when its last instance goes. + let placed = s.doc().unwrap().doc.layers[0] + .children() + .unwrap() + .iter() + .find(|n| matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Placed")) + .unwrap() + .id; + s.execute("edit.clear", &json!({"ids": [placed.0]})).unwrap(); + assert_eq!(unused(&mut s), ["Placed", "Nested", "Lonely"]); + // Delete Symbol takes them all in one undo step, and Undo brings them back. + let before = s.doc().unwrap().history.undo.len(); + s.execute("symbol.delete", &json!({"names": ["Placed", "Nested", "Lonely"]})).unwrap(); + let names = |s: &Session| s.doc().unwrap().doc.symbols.iter().map(|x| x.name.clone()).collect::<Vec<_>>(); + assert_eq!(names(&s), ["Inner", "Outer", "Brushed"]); + assert_eq!(s.doc().unwrap().history.undo.len(), before + 1); + assert!(unused(&mut s).is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(names(&s), ["Placed", "Inner", "Outer", "Nested", "Lonely", "Brushed"]); + // Bad `names` are refused and change nothing. + for bad in [json!({"names": []}), json!({"names": "Placed"}), json!({"names": [1]}), json!({"names": ["Placed", "Nope"]})] { + assert!(s.execute("symbol.delete", &bad).is_err(), "{bad}"); + } + assert_eq!(names(&s).len(), 6); +} diff --git a/crates/ui-egui/src/dialogs/symbol_delete.rs b/crates/ui-egui/src/dialogs/symbol_delete.rs index 730c00cb4d..77b308b3c9 100644 --- a/crates/ui-egui/src/dialogs/symbol_delete.rs +++ b/crates/ui-egui/src/dialogs/symbol_delete.rs @@ -20,7 +20,7 @@ pub const KIND: &str = "deleteSymbol"; pub const USED: &str = "deleteUsedSymbol"; pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |_| tl!("Delete the selected symbol?").into(), + heading: |d| if d.fields.get("names").is_some() { tl!("Delete the selected symbols?") } else { tl!("Delete the selected symbol?") }.into(), body: |_, _, _| false, confirm: confirm_unused, ok: Some("Yes"), @@ -55,6 +55,36 @@ pub(crate) fn ask(app: &mut VectorcraftApp, name: &str, now: bool) { } } +/// Delete Symbol for the unused symbols `names` that Select All Unused picked (#4918): asked once +/// ("Delete the selected symbols?"), or at once with `now`. They go in one undo step. +pub(crate) fn ask_many(app: &mut VectorcraftApp, names: &[String], now: bool) { + let Some(uid) = app.session.active().map(|st| st.uid) else { return }; + if now { + // An error already went to the status bar. + let _ = delete_unused(app, uid, names); + } else { + app.ui.dialog = Some(Dialog::new(KIND, json!({ "names": names, "doc": uid }))); + } +} + +/// Deletes those of `names` that are still unused in document `uid` while it is the active one. +fn delete_unused(app: &mut VectorcraftApp, uid: u64, names: &[String]) -> DialogResult { + if app.session.active().map(|st| st.uid) != Some(uid) { + return Ok(Value::Null); + } + let unused: Vec<String> = + app.run("symbol.unused", json!({})).ok().and_then(|r| serde_json::from_value(r["names"].clone()).ok()).unwrap_or_default(); + let names: Vec<&String> = names.iter().filter(|n| unused.contains(n)).collect(); + if names.is_empty() { + return Ok(Value::Null); + } + let r = app.run("symbol.delete", json!({ "names": names })); + if let Err(e) = &r { + app.status(e.clone()); + } + r +} + fn open(app: &mut VectorcraftApp, kind: &str, name: &str, uid: u64) { app.ui.dialog = Some(Dialog::new(kind, json!({ "name": name, "doc": uid }))); } @@ -78,6 +108,9 @@ fn target(d: &Dialog) -> (u64, String) { fn confirm_unused(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { app.ui.dialog = None; let (uid, name) = target(d); + if let Some(names) = d.fields.get("names").and_then(|v| serde_json::from_value::<Vec<String>>(v.clone()).ok()) { + return delete_unused(app, uid, &names); + } match instances(app, uid, &name) { None => Ok(Value::Null), Some(0) => app.run("symbol.delete", json!({ "name": name })), @@ -98,3 +131,17 @@ fn confirm_used(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { } app.run("symbol.delete", json!({ "name": name, "expandInstances": !d.bool("discard") })) } + +#[cfg(test)] +mod tests { + use super::*; + + /// The question for the symbols Select All Unused picked is plural (#4918). + #[test] + fn several_symbols_get_the_plural_question() { + let one = Dialog::new(KIND, json!({"name": "A", "doc": 1})); + let many = Dialog::new(KIND, json!({"names": ["A", "B"], "doc": 1})); + assert_eq!((SPEC.heading)(&one), "Delete the selected symbol?"); + assert_eq!((SPEC.heading)(&many), "Delete the selected symbols?"); + } +} diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index b5b3058954..f54d04ca60 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -201,6 +201,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let names: Vec<String> = doc.symbols.iter().map(|s| s.name.clone()).collect(); let list: bool = pstate(ui.ctx(), "sym-list"); let sel = current(app); + let marked = marked(ui.ctx(), &names); + // The symbols drawn selected: the ones Select All Unused picked, else the current one. + let on = |n: &str| if marked.is_empty() { sel.as_deref() == Some(n) } else { marked.iter().any(|m| m == n) }; let mut clicked: Option<(String, bool)> = None; let list_rect = widgets::list_box(ui, |ui| { ui.set_min_height(110.0); @@ -214,7 +217,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), Sense::click_and_drag()); // Dragged onto the canvas, the symbol is placed there. widgets::drag_source(ui, &resp, || PanelDrag::Symbol(n.clone())); - if sel.as_deref() == Some(n.as_str()) { + if on(n) { ui.painter().rect_filled(r, 0.0, t.row_selected); } else if resp.hovered() { ui.painter().rect_filled(r, 0.0, t.hover); @@ -233,7 +236,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let (r, resp) = ui.allocate_exact_size(vec2(44.0, 44.0), Sense::click_and_drag()); widgets::drag_source(ui, &resp, || PanelDrag::Symbol(n.clone())); chip(ui, &doc, &keys, r.shrink(2.0), n); - let on = sel.as_deref() == Some(n.as_str()); + let on = on(n); ui.painter().rect_stroke( r, 0.0, @@ -258,6 +261,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { app.status(e); } if let Some((n, place)) = clicked { + // A click picks one symbol again. + set_pstate(ui.ctx(), MARKED, Vec::<String>::new()); app.run("symbol.setCurrent", json!({"name": n})).ok(); if place { app.run("symbol.place", json!({"name": n})).ok(); @@ -286,16 +291,16 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { app.run(cmd, p).ok(); } // Alt deletes an unused symbol without asking; a symbol with instances still asks. - if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Symbol"), false, sel.is_some(), 24.0).clicked() - && let Some(n) = &sel - { - crate::dialogs::symbol_delete::ask(app, n, super::alt_held(ui)); + if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Symbol"), false, sel.is_some() || !marked.is_empty(), 24.0).clicked() { + delete(app, &marked, sel.as_deref(), super::alt_held(ui)); } }); } pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let sel = current(app); + let names: Vec<String> = app.session.active().map(|d| d.doc.symbols.iter().map(|s| s.name.clone()).collect()).unwrap_or_default(); + let marked = marked(ui.ctx(), &names); let has_sel = app.session.active().is_some_and(|d| !d.selection.is_empty()); let inst = has_instances_selected(app); let name = json!({"name": sel}); @@ -310,10 +315,8 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } // Asks first, as the panel's button does; the menu item has no Alt shortcut. - if menu_item(ui, tl!("Delete Symbol"), sel.is_some(), false) - && let Some(n) = &sel - { - crate::dialogs::symbol_delete::ask(app, n, false); + if menu_item(ui, tl!("Delete Symbol"), sel.is_some() || !marked.is_empty(), false) { + delete(app, &marked, sel.as_deref(), false); } let items: [(&str, bool, &str, Value); 7] = [ (tl!("Symbol Options…"), sel.is_some(), "ui.symbolOptions", json!({"edit": true, "name": sel})), @@ -330,6 +333,18 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } ui.separator(); + // Select All Unused (#4918): the symbols nothing places show selected, and Delete Symbol + // deletes them all. + if menu_item(ui, tl!("Select All Unused"), !names.is_empty(), false) + && let Ok(r) = app.run("symbol.unused", json!({})) + { + let unused: Vec<String> = serde_json::from_value(r["names"].clone()).unwrap_or_default(); + if unused.is_empty() { + app.status(tl!("No unused symbols")); + } + set_pstate(ui.ctx(), MARKED, unused); + } + ui.separator(); let list: bool = pstate(ui.ctx(), "sym-list"); if menu_item(ui, tl!("Thumbnail View"), true, !list) { set_pstate(ui.ctx(), "sym-list", false); @@ -345,6 +360,27 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// The panel state key of the symbols Select All Unused picked. +const MARKED: &str = "sym-unused"; + +/// The symbols Select All Unused picked that the document still has (`names`). +fn marked(ctx: &egui::Context, names: &[String]) -> Vec<String> { + let mut marked: Vec<String> = pstate(ctx, MARKED); + marked.retain(|m| names.contains(m)); + marked +} + +/// Delete Symbol: the symbols Select All Unused picked (`marked`) when there are any, asked about +/// once unless `now` (Alt), else the current symbol `sel`. +fn delete(app: &mut VectorcraftApp, marked: &[String], sel: Option<&str>, now: bool) { + match (marked, sel) { + ([], Some(n)) => crate::dialogs::symbol_delete::ask(app, n, now), + ([], None) => {} + ([n], _) => crate::dialogs::symbol_delete::ask(app, n, now), + (names, _) => crate::dialogs::symbol_delete::ask_many(app, names, now), + } +} + /// Save Symbol Library… for the document's symbols (`names`: the one selected in the panel). fn save_library(app: &mut VectorcraftApp, names: Vec<String>) { if let Err(e) = app.run("ui.saveSymbolLibrary", json!({ "names": names })) { @@ -598,6 +634,56 @@ mod tests { crate::tests_removeanchors::shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::<Vec<_>>()) } + /// Clicks the menu item labelled `label`. + fn click_menu(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str) { + let labels = menu_frame(ctx, app, vec![]); + let item = labels.iter().find(|(t, _)| t.trim() == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("{label} in the menu")); + menu_frame(ctx, app, vec![egui::Event::PointerMoved(item), button(item, true)]); + menu_frame(ctx, app, vec![button(item, false)]); + } + + /// #4918: Select All Unused picks the symbols nothing places, Delete Symbol asks once and + /// deletes them all in one undo step, and a click on a symbol picks one again. + #[test] + fn select_all_unused_picks_the_unused_symbols_and_delete_deletes_them() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + for (i, name) in ["A", "B", "C"].into_iter().enumerate() { + app.run("shape.rectangle", json!({"x": 10.0 + 40.0 * i as f64, "y": 10, "width": 30, "height": 20})).unwrap(); + let id = app.run("symbol.new", json!({"name": name})).unwrap()["id"].as_u64().unwrap(); + // A and C lose their instances; B keeps its own. + if name != "B" { + app.run("edit.clear", json!({"ids": [id]})).unwrap(); + } + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + click_menu(&ctx, &mut app, "Select All Unused"); + let names = symbols(&mut app); + assert_eq!(marked(&ctx, &names), ["A", "C"]); + let undo = app.session.active().unwrap().history.undo.len(); + click_menu(&ctx, &mut app, "Delete Symbol"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::dialogs::symbol_delete::KIND)); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["names"], json!(["A", "C"]), "asked once, about both"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(symbols(&mut app), ["B"]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert!(marked(&ctx, &symbols(&mut app)).is_empty(), "the deleted ones are no longer picked"); + // Undone, they are back; Select All Unused again, then a click on a symbol picks just it. + app.run("edit.undo", json!({})).unwrap(); + click_menu(&ctx, &mut app, "Select All Unused"); + assert_eq!(marked(&ctx, &symbols(&mut app)).len(), 2); + frame(&ctx, &mut app, vec![]); + let tile = pos2(26.0, 26.0); + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile), button(tile, true)]); + frame(&ctx, &mut app, vec![button(tile, false)]); + assert!(marked(&ctx, &symbols(&mut app)).is_empty()); + // With nothing unused, the item reports it and picks nothing. + app.run("symbol.delete", json!({"names": ["A", "C"]})).unwrap(); + click_menu(&ctx, &mut app, "Select All Unused"); + assert!(marked(&ctx, &symbols(&mut app)).is_empty()); + } + #[test] fn new_symbol_asks_for_symbol_options_before_making_the_symbol() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/docs/mcp.md b/docs/mcp.md index 5905172d33..31f541e064 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1561,7 +1561,8 @@ already walks Image Trace. Short agent entry points: of `symbol.list` carry `nineSlice`: the guides or `null`; `type` is Symbol Type, `static` by default for the command and `dynamic` by default in the Symbol Options dialog), `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}`, `symbol.replace`, `symbol.edit`, `symbol.duplicate`, - `symbol.selectInstances {name}`. `symbol.new` and `symbol.duplicate {name, newName?}` trim the white space around the + `symbol.selectInstances {name}`, `symbol.delete {name | names, expandInstances?}` (`names` deletes several in one + undo step). `symbol.new` and `symbol.duplicate {name, newName?}` trim the white space around the name they are given, as `symbol.options` trims `newName`; a blank one gives "New Symbol" or "<name> copy". - Dynamic symbols: an instance of a symbol whose `type` is `dynamic` changes the appearance of objects in the symbol's art for itself only and stays linked. `symbol.instance.setAppearance {id?, path, fill?, stroke?, opacity?, blend?}` @@ -1577,6 +1578,11 @@ already walks Image Trace. Short agent entry points: ```json {"name":"run_command","arguments":{"command":"symbol.instance.setAppearance","params":{"id":42,"path":[1],"fill":"#d0021b","opacity":80}}} ``` +- The Symbols panel menu's Select All Unused: `symbol.unused` (a query) lists the symbols nothing places, in panel + order, and the panel shows them selected; its Delete Symbol then deletes them all, asked once, in one undo step. + Instances in the art (opacity masks included), graph designs, pattern tiles (with the tiles that pattern editing's + Cancel puts back) and the art of the document's brushes count, and so do the instances in the art of a symbol that + is used; a symbol placed only inside an unused symbol is unused too. - The Brushes panel menu's Select All Unused: `brush.unused` (a query) lists the brushes no stroke paints with, in library order, and the panel selects them. Strokes in the art (opacity masks included), symbols, graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and graphic styles count, and so do the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 20e77f1d18..168c381233 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Area Type Options › Text Flow, #4978; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Symbols panel: Select All Unused, #4918) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -607,6 +607,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Swatch and graphic style libraries, Libraries panel files, presets and plug-ins open wherever they are dropped on the window, as File › Open opens them. - **Symbol libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own, as swatch and graphic style libraries do. The built-in library, Basic Shapes, is original art generated in code (`crates/engine/src/cmd/symbollib.rs`). A click on a symbol adds it to the document's Symbols as one undo step, with its Symbol Options (size, registration, export type, 9-slice guides) and every resource it uses (the symbols it nests, patterns, swatches, brushes, graphic styles, images), and makes it the current symbol; a symbol the document already has is not added again and another symbol of the same name keeps its name, the library's comes in numbered. Thumbnails, in the library panels and the Symbols panel, draw a symbol with the symbols it nests and the patterns and images it uses. Dragging a library symbol onto the canvas also places an instance there, in the same step ([placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)). Save Symbols (the library menu) and Save Symbol Library… (the Symbols panel menu) write the document's symbols as a `.vectorcraft` document holding only them, into the user library folder (listed under User Defined) or a file; Other Library… reads the symbols of any document VectorCraft opens; a file it can't read is an error and opens no panel. Tests: `crates/engine/src/tests/symbollib.rs`, `crates/ui-egui/src/panels/tests_symbol_libraries.rs`, `panels::symbols::tests::thumbnails_show_the_symbols_a_symbol_nests`, `canvas::tests::a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step`. - **Delete Symbol asks first** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Alt-click Delete](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): the Symbols panel's Delete Symbol button and menu item ask "Delete the selected symbol?" with Yes and No for a symbol no instance uses. For a symbol with placed instances they ask with Expand Instances (the instances become ordinary art), Delete Instances and Cancel; either Instances button deletes the symbol in one undo step. Alt-click on the button deletes an unused symbol without asking and still asks about one with instances. A question left open while another document became active deletes nothing. `symbol.delete` itself does not ask. Tests: `panels::symbols::tests::delete_symbol_asks_first_and_alt_click_deletes_an_unused_symbol_at_once`, `the_in_use_question_expands_or_deletes_the_instances`, `a_stale_delete_symbol_question_deletes_nothing`, `the_delete_symbol_questions_show_their_buttons`. + - **Symbols › Select All Unused** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), #4918): the Symbols panel menu's Select All Unused shows the symbols nothing places selected (`symbol.unused`): instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. Delete Symbol, the button or the menu item, then asks "Delete the selected symbols?" once and deletes those still unused in one undo step (`symbol.delete {names}`); Alt-click on the button deletes them without asking, and a click on a symbol picks just it again. Tests: `tests::brushsym::symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several`, `panels::symbols::tests::select_all_unused_picks_the_unused_symbols_and_delete_deletes_them`, `dialogs::symbol_delete::tests::several_symbols_get_the_plural_question`. - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol. A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection), or the view commands on empty canvas. - A right-click over locked objects adds an Unlock submenu to the canvas context menu. The submenu lists up to 20 locked objects under the pointer, topmost first, by the name the Layers panel shows, and choosing one unlocks it (`layer.setProps`). A locked group is listed as one item. Objects on hidden, locked or template layers are not listed. @@ -1432,6 +1433,7 @@ Symbols area (#4938), from the public symbol documentation ([create and place sy | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Symbols panel: Select All Unused (`symbol.unused`) shows the symbols nothing places selected, and Delete Symbol deletes them all, asked once, in one undo step (`symbol.delete {names}`, #4918); scores and hours unchanged | | 2026-11-01 | minor | Type core: Area Type Options › Text Flow (#4978): area type with several rows and columns fills them by columns (the default) or by rows, from the dialog's radio buttons or `text.areaOptions {flow}`; evidence updated; scores unchanged. | | 2026-11-01 | minor | Symbols: dynamic symbols (#4938): Symbol Options › Symbol Type, per-instance appearance for objects of a dynamic symbol's art that stays linked through redefinition, Break Link baking, Reset and Static dropping it; evidence added. Score unchanged at 87% (estimated), hours 5–9 → 4–8. | | 2026-11-01 | minor | Artboard background colors in output (#4937): raster exports (a transparent background too), PDF, SVG and EPS pages, `.ai` files' PDF pages, Export for Screens and print (and its preview) draw each artboard's color behind its art, inside the artboard and in the color's own model; Export for Screens has Include Artboard Fill beside Include Bleed (on by default, remembered; `includeArtboardFill`, also on `document.export` and `file.print`); editing data keeps the color as the artboard's, and Export for Screens' document rows keep it too; evidence updated; scores unchanged. | From 961694cba6d83aee7595323ceb70519f83e8fdb4 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:32:53 +0300 Subject: [PATCH 219/260] Fix #4918: delete nested picks safely, keep picks per document symbol.delete {names} expands every instance of the named symbols, round by round, before it removes any definition, so a symbol and the one placed inside it delete alike in either order. The Symbols panel's picks belong to the document they were made in, and a single picked symbol is deleted only while symbol.unused still lists it. --- crates/engine/src/cmd/brushsym/symbols.rs | 30 +++++++++- crates/engine/src/tests/brushsym.rs | 12 ++++ crates/ui-egui/src/dialogs/symbol_delete.rs | 14 ++++- crates/ui-egui/src/panels/symbols.rs | 66 +++++++++++++++++---- 4 files changed, 105 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index c5518c70b0..556926309e 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -448,6 +448,9 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "name": name, "id": id.0 })) } +/// How many levels of nested instances Delete Symbol expands before it gives up. +const MAX_DELETE_ROUNDS: usize = 256; + pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "symbol.delete"; // `names` deletes several symbols in one undo step (the Symbols panel's Select All Unused, #4918). @@ -475,13 +478,36 @@ pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result<Value> { let expand = switch_or(p, "expandInstances", true, C)?; let label = if names.len() == 1 { "Delete Symbol" } else { "Delete Symbols" }; s.edit(label, |d, _| { - for name in &names { - let inst = instances_of(d, Some(name)); + // Every instance goes before any definition, whatever the order of `names`: expanding an + // instance of one symbol can bring out instances of another being deleted (nested in its + // art), which expand in turn while their definitions are still there. Each round expands + // one level of nesting, so the rounds are capped. + let of_names = |d: &Document| { + let mut v = vec![]; + d.walk(|n| { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind + && names.contains(symbol) + { + v.push(n.id); + } + }); + v + }; + for _ in 0..=MAX_DELETE_ROUNDS { + let inst = of_names(d); + if inst.is_empty() { + break; + } if expand { break_links(d, &inst, true)?; } else { remove_each(d, &inst)?; } + } + if !of_names(d).is_empty() { + return Err(EngineError::Other("the symbols are nested too deeply to expand their instances".into())); + } + for name in &names { d.symbols.retain(|x| &x.name != name); set_natural_size(d, name, None); d.set_symbol_registration(name, SymbolRegistration::CENTER); diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index adfe4ef117..90da1f7f8b 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1483,6 +1483,18 @@ fn symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several() { assert!(unused(&mut s).is_empty()); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(names(&s), ["Placed", "Inner", "Outer", "Nested", "Lonely", "Brushed"]); + // Deleting a symbol and the one placed inside it, in either order, expands every instance + // while both definitions are still there: no instance is left without its symbol. + for order in [["Inner", "Outer"], ["Outer", "Inner"]] { + s.execute("symbol.delete", &json!({"names": order})).unwrap(); + let mut dangling = 0; + s.doc() + .unwrap() + .doc + .walk(|n| dangling += usize::from(matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Inner" || symbol == "Outer"))); + assert_eq!(dangling, 0, "{order:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + } // Bad `names` are refused and change nothing. for bad in [json!({"names": []}), json!({"names": "Placed"}), json!({"names": [1]}), json!({"names": ["Placed", "Nope"]})] { assert!(s.execute("symbol.delete", &bad).is_err(), "{bad}"); diff --git a/crates/ui-egui/src/dialogs/symbol_delete.rs b/crates/ui-egui/src/dialogs/symbol_delete.rs index 77b308b3c9..c515f7274b 100644 --- a/crates/ui-egui/src/dialogs/symbol_delete.rs +++ b/crates/ui-egui/src/dialogs/symbol_delete.rs @@ -20,7 +20,14 @@ pub const KIND: &str = "deleteSymbol"; pub const USED: &str = "deleteUsedSymbol"; pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |d| if d.fields.get("names").is_some() { tl!("Delete the selected symbols?") } else { tl!("Delete the selected symbol?") }.into(), + heading: |d| { + if d.fields.get("names").and_then(Value::as_array).is_some_and(|n| n.len() > 1) { + tl!("Delete the selected symbols?") + } else { + tl!("Delete the selected symbol?") + } + .into() + }, body: |_, _, _| false, confirm: confirm_unused, ok: Some("Yes"), @@ -56,7 +63,8 @@ pub(crate) fn ask(app: &mut VectorcraftApp, name: &str, now: bool) { } /// Delete Symbol for the unused symbols `names` that Select All Unused picked (#4918): asked once -/// ("Delete the selected symbols?"), or at once with `now`. They go in one undo step. +/// ("Delete the selected symbols?", or the singular for one), or at once with `now`. Only those still +/// unused then (`symbol.unused`: brush art, patterns and nested instances count) go, in one undo step. pub(crate) fn ask_many(app: &mut VectorcraftApp, names: &[String], now: bool) { let Some(uid) = app.session.active().map(|st| st.uid) else { return }; if now { @@ -143,5 +151,7 @@ mod tests { let many = Dialog::new(KIND, json!({"names": ["A", "B"], "doc": 1})); assert_eq!((SPEC.heading)(&one), "Delete the selected symbol?"); assert_eq!((SPEC.heading)(&many), "Delete the selected symbols?"); + let picked_one = Dialog::new(KIND, json!({"names": ["A"], "doc": 1})); + assert_eq!((SPEC.heading)(&picked_one), "Delete the selected symbol?"); } } diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index f54d04ca60..968e7a1a36 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -201,7 +201,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let names: Vec<String> = doc.symbols.iter().map(|s| s.name.clone()).collect(); let list: bool = pstate(ui.ctx(), "sym-list"); let sel = current(app); - let marked = marked(ui.ctx(), &names); + let uid = app.session.active().map(|d| d.uid); + let marked = marked(ui.ctx(), uid, &names); // The symbols drawn selected: the ones Select All Unused picked, else the current one. let on = |n: &str| if marked.is_empty() { sel.as_deref() == Some(n) } else { marked.iter().any(|m| m == n) }; let mut clicked: Option<(String, bool)> = None; @@ -262,7 +263,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } if let Some((n, place)) = clicked { // A click picks one symbol again. - set_pstate(ui.ctx(), MARKED, Vec::<String>::new()); + set_pstate(ui.ctx(), MARKED, (uid, Vec::<String>::new())); app.run("symbol.setCurrent", json!({"name": n})).ok(); if place { app.run("symbol.place", json!({"name": n})).ok(); @@ -300,7 +301,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let sel = current(app); let names: Vec<String> = app.session.active().map(|d| d.doc.symbols.iter().map(|s| s.name.clone()).collect()).unwrap_or_default(); - let marked = marked(ui.ctx(), &names); + let uid = app.session.active().map(|d| d.uid); + let marked = marked(ui.ctx(), uid, &names); let has_sel = app.session.active().is_some_and(|d| !d.selection.is_empty()); let inst = has_instances_selected(app); let name = json!({"name": sel}); @@ -342,7 +344,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if unused.is_empty() { app.status(tl!("No unused symbols")); } - set_pstate(ui.ctx(), MARKED, unused); + set_pstate(ui.ctx(), MARKED, (uid, unused)); } ui.separator(); let list: bool = pstate(ui.ctx(), "sym-list"); @@ -363,9 +365,13 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { /// The panel state key of the symbols Select All Unused picked. const MARKED: &str = "sym-unused"; -/// The symbols Select All Unused picked that the document still has (`names`). -fn marked(ctx: &egui::Context, names: &[String]) -> Vec<String> { - let mut marked: Vec<String> = pstate(ctx, MARKED); +/// The symbols Select All Unused picked in the active document (`uid`) that it still has (`names`); +/// none once another document is active. +fn marked(ctx: &egui::Context, uid: Option<u64>, names: &[String]) -> Vec<String> { + let (of, mut marked): (Option<u64>, Vec<String>) = pstate(ctx, MARKED); + if of != uid { + return vec![]; + } marked.retain(|m| names.contains(m)); marked } @@ -376,7 +382,7 @@ fn delete(app: &mut VectorcraftApp, marked: &[String], sel: Option<&str>, now: b match (marked, sel) { ([], Some(n)) => crate::dialogs::symbol_delete::ask(app, n, now), ([], None) => {} - ([n], _) => crate::dialogs::symbol_delete::ask(app, n, now), + // Picked by Select All Unused, even one: deleted only while still unused. (names, _) => crate::dialogs::symbol_delete::ask_many(app, names, now), } } @@ -660,7 +666,7 @@ mod tests { crate::theme::install_fonts(&ctx); click_menu(&ctx, &mut app, "Select All Unused"); let names = symbols(&mut app); - assert_eq!(marked(&ctx, &names), ["A", "C"]); + assert_eq!(marked(&ctx, uid(&app), &names), ["A", "C"]); let undo = app.session.active().unwrap().history.undo.len(); click_menu(&ctx, &mut app, "Delete Symbol"); assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::dialogs::symbol_delete::KIND)); @@ -668,20 +674,54 @@ mod tests { crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(symbols(&mut app), ["B"]); assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); - assert!(marked(&ctx, &symbols(&mut app)).is_empty(), "the deleted ones are no longer picked"); + assert!(marked(&ctx, uid(&app), &symbols(&mut app)).is_empty(), "the deleted ones are no longer picked"); // Undone, they are back; Select All Unused again, then a click on a symbol picks just it. app.run("edit.undo", json!({})).unwrap(); click_menu(&ctx, &mut app, "Select All Unused"); - assert_eq!(marked(&ctx, &symbols(&mut app)).len(), 2); + assert_eq!(marked(&ctx, uid(&app), &symbols(&mut app)).len(), 2); frame(&ctx, &mut app, vec![]); let tile = pos2(26.0, 26.0); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile), button(tile, true)]); frame(&ctx, &mut app, vec![button(tile, false)]); - assert!(marked(&ctx, &symbols(&mut app)).is_empty()); + assert!(marked(&ctx, uid(&app), &symbols(&mut app)).is_empty()); // With nothing unused, the item reports it and picks nothing. app.run("symbol.delete", json!({"names": ["A", "C"]})).unwrap(); click_menu(&ctx, &mut app, "Select All Unused"); - assert!(marked(&ctx, &symbols(&mut app)).is_empty()); + assert!(marked(&ctx, uid(&app), &symbols(&mut app)).is_empty()); + } + + fn uid(app: &VectorcraftApp) -> Option<u64> { + app.session.active().map(|d| d.uid) + } + + /// Picks made in one document don't carry to another with symbols of the same names, and a + /// picked symbol that gained a use since (here in a brush's art) isn't deleted (#4918 review). + #[test] + fn picked_symbols_stay_with_their_document_and_are_rechecked_before_deleting() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let make = |app: &mut VectorcraftApp| { + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let id = app.run("symbol.new", json!({"name": "A"})).unwrap()["id"].as_u64().unwrap(); + app.run("edit.clear", json!({"ids": [id]})).unwrap(); + }; + make(&mut app); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + click_menu(&ctx, &mut app, "Select All Unused"); + assert_eq!(marked(&ctx, uid(&app), &symbols(&mut app)), ["A"]); + make(&mut app); + assert!(marked(&ctx, uid(&app), &symbols(&mut app)).is_empty(), "not in the other document"); + // Back in the first one: A gains a use in a brush's art, then Delete (Alt: no question). + click_menu(&ctx, &mut app, "Select All Unused"); + let id = app.run("symbol.place", json!({"name": "A"})).unwrap()["id"].as_u64().unwrap(); + app.run("brush.new", json!({"type": "art", "name": "B", "ids": [id]})).unwrap(); + app.run("edit.clear", json!({"ids": [id]})).unwrap(); + let names = symbols(&mut app); + let picked = marked(&ctx, uid(&app), &names); + assert_eq!(picked, ["A"]); + delete(&mut app, &picked, None, true); + assert_eq!(symbols(&mut app), ["A"], "still used by the brush, so kept"); } #[test] From 3d8677a71a73af44937383c638f74cc81474ce4c Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 07:17:34 +0700 Subject: [PATCH 220/260] Symbols: catalog rows for deleting several symbols and for no unused symbols --- crates/ui-egui/src/i18n/bg.tsv | 3 +++ crates/ui-egui/src/i18n/bs.tsv | 3 +++ crates/ui-egui/src/i18n/ca.tsv | 3 +++ crates/ui-egui/src/i18n/cs.tsv | 3 +++ crates/ui-egui/src/i18n/da.tsv | 3 +++ crates/ui-egui/src/i18n/de.tsv | 3 +++ crates/ui-egui/src/i18n/el.tsv | 3 +++ crates/ui-egui/src/i18n/es.tsv | 3 +++ crates/ui-egui/src/i18n/fi.tsv | 3 +++ crates/ui-egui/src/i18n/fr.tsv | 3 +++ crates/ui-egui/src/i18n/hu.tsv | 3 +++ crates/ui-egui/src/i18n/id.tsv | 3 +++ crates/ui-egui/src/i18n/it.tsv | 3 +++ crates/ui-egui/src/i18n/ja.tsv | 3 +++ crates/ui-egui/src/i18n/ka.tsv | 3 +++ crates/ui-egui/src/i18n/ko.tsv | 3 +++ crates/ui-egui/src/i18n/nl.tsv | 3 +++ crates/ui-egui/src/i18n/pl.tsv | 3 +++ crates/ui-egui/src/i18n/pt-br.tsv | 3 +++ crates/ui-egui/src/i18n/ru.tsv | 3 +++ crates/ui-egui/src/i18n/sv.tsv | 3 +++ crates/ui-egui/src/i18n/tr.tsv | 3 +++ crates/ui-egui/src/i18n/uk.tsv | 3 +++ crates/ui-egui/src/i18n/vi.tsv | 3 +++ crates/ui-egui/src/i18n/zh-hans.tsv | 3 +++ crates/ui-egui/src/i18n/zh-hant.tsv | 3 +++ 26 files changed, 78 insertions(+) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 8f93990a02..f4bbcda00d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -736,6 +736,9 @@ font-technology Variable Променливи Delete Swatch Изтриване на образец Delete Symbol Изтриване на символ Delete the selected symbol? Да се изтрие ли избраният символ? + Delete the selected symbols? Да се изтрият ли избраните символи? + No unused symbols Няма неизползвани символи + Delete Symbols Изтриване на символи One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Един или повече от символите се използват и не могат да бъдат изтрити, докато екземплярите им не бъдат разширени или изтрити. Expand Instances Разширяване на екземплярите Delete Instances Изтриване на екземплярите diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 943a73609a..ab592a2919 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3068,6 +3068,9 @@ theme Appearance Izgled Delete Brush Izbriši četkicu Delete Symbol Izbriši simbol Delete the selected symbol? Izbrisati odabrani simbol? + Delete the selected symbols? Izbrisati odabrane simbole? + No unused symbols Nema nekorištenih simbola + Delete Symbols Brisanje simbola One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Jedan ili više simbola se koriste i ne mogu se izbrisati dok se njihove instance ne prošire ili izbrišu. Expand Instances Proširi instance Delete Instances Izbriši instance diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index de41f9166f..fe48fb73ac 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1053,6 +1053,9 @@ Delete Swatch Suprimeix la mostra Delete Symbol Suprimeix el símbol Delete the selected symbol? Voleu suprimir el símbol seleccionat? + Delete the selected symbols? Voleu suprimir els símbols seleccionats? + No unused symbols No hi ha símbols sense utilitzar + Delete Symbols Suprimeix els símbols One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Un o més dels símbols estan en ús i no es poden suprimir fins que se n’expandeixin o se’n suprimeixin les instàncies. Expand Instances Expandeix les instàncies Delete Instances Suprimeix les instàncies diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 9f5b98c5e3..2f2892c006 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3099,6 +3099,9 @@ theme Appearance Motiv Delete Brush Odstranit štětec Delete Symbol Odstranit symbol Delete the selected symbol? Odstranit vybraný symbol? + Delete the selected symbols? Odstranit vybrané symboly? + No unused symbols Žádné nepoužité symboly + Delete Symbols Odstranit symboly One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Jeden nebo více symbolů se používá a nelze je odstranit, dokud jejich instance nerozložíte nebo neodstraníte. Expand Instances Rozložit instance Delete Instances Odstranit instance diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 3d74e590bd..056f8c3576 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2855,6 +2855,9 @@ theme Appearance Udseende Delete Brush Slet pensel Delete Symbol Slet symbol Delete the selected symbol? Vil du slette det markerede symbol? + Delete the selected symbols? Vil du slette de markerede symboler? + No unused symbols Ingen ubrugte symboler + Delete Symbols Slet symboler One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Et eller flere af symbolerne er i brug og kan ikke slettes, før deres forekomster er udvidet eller slettet. Expand Instances Udvid forekomster Delete Instances Slet forekomster diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c07cd79adc..23336fb9ff 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -730,6 +730,9 @@ font-technology Variable Variabel Delete Swatch Farbfeld löschen Delete Symbol Symbol löschen Delete the selected symbol? Ausgewähltes Symbol löschen? + Delete the selected symbols? Ausgewählte Symbole löschen? + No unused symbols Keine nicht verwendeten Symbole + Delete Symbols Symbole löschen One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Mindestens eines der Symbole wird verwendet und kann erst gelöscht werden, wenn seine Instanzen umgewandelt oder gelöscht wurden. Expand Instances Instanzen umwandeln Delete Instances Instanzen löschen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 61d187c200..83d50b7527 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -710,6 +710,9 @@ font-technology Variable Μεταβλητές Delete Swatch Διαγραφή δείγματος χρώματος Delete Symbol Διαγραφή συμβόλου Delete the selected symbol? Να διαγραφεί το επιλεγμένο σύμβολο; + Delete the selected symbols? Να διαγραφούν τα επιλεγμένα σύμβολα; + No unused symbols Δεν υπάρχουν αχρησιμοποίητα σύμβολα + Delete Symbols Διαγραφή συμβόλων One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Ένα ή περισσότερα από τα σύμβολα χρησιμοποιούνται και δεν μπορούν να διαγραφούν μέχρι να επεκταθούν ή να διαγραφούν τα στιγμιότυπά τους. Expand Instances Επέκταση στιγμιοτύπων Delete Instances Διαγραφή στιγμιοτύπων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 2884b973cc..a6824a320b 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -751,6 +751,9 @@ font-technology Variable Variables Delete Swatch Eliminar muestra Delete Symbol Eliminar símbolo Delete the selected symbol? ¿Eliminar el símbolo seleccionado? + Delete the selected symbols? ¿Eliminar los símbolos seleccionados? + No unused symbols No hay símbolos sin usar + Delete Symbols Eliminar símbolos One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Uno o más de los símbolos están en uso y no se pueden eliminar hasta que se expandan o eliminen sus instancias. Expand Instances Expandir instancias Delete Instances Eliminar instancias diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 0cfe70c464..87debec2ef 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3038,6 +3038,9 @@ theme Appearance Ulkoasu Delete Brush Poista sivellin Delete Symbol Poista symboli Delete the selected symbol? Poistetaanko valittu symboli? + Delete the selected symbols? Poistetaanko valitut symbolit? + No unused symbols Ei käyttämättömiä symboleja + Delete Symbols Poista symbolit One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Yksi tai useampi symboleista on käytössä, eikä niitä voi poistaa ennen kuin niiden ilmentymät on laajennettu tai poistettu. Expand Instances Laajenna ilmentymät Delete Instances Poista ilmentymät diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4c3423a194..b210563245 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -756,6 +756,9 @@ font-technology Variable Variables Delete Swatch Supprimer la nuance Delete Symbol Supprimer le symbole Delete the selected symbol? Supprimer le symbole sélectionné ? + Delete the selected symbols? Supprimer les symboles sélectionnés ? + No unused symbols Aucun symbole inutilisé + Delete Symbols Supprimer les symboles One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Un ou plusieurs symboles sont utilisés et ne peuvent pas être supprimés tant que leurs instances ne sont pas décomposées ou supprimées. Expand Instances Décomposer les instances Delete Instances Supprimer les instances diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index cbc4ebf1ff..729597666d 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -975,6 +975,9 @@ font-technology Variable Változó Delete Swatch Színminta törlése Delete Symbol Szimbólum törlése Delete the selected symbol? Törli a kijelölt szimbólumot? + Delete the selected symbols? Törli a kijelölt szimbólumokat? + No unused symbols Nincsenek nem használt szimbólumok + Delete Symbols Szimbólumok törlése One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Egy vagy több szimbólum használatban van, és nem törölhető, amíg a példányait ki nem bontja vagy nem törli. Expand Instances Példányok kibontása Delete Instances Példányok törlése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c960dd6ae5..82337045e9 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2855,6 +2855,9 @@ theme Appearance Tampilan Delete Brush Hapus kuas Delete Symbol Hapus simbol Delete the selected symbol? Hapus simbol yang dipilih? + Delete the selected symbols? Hapus simbol yang dipilih? + No unused symbols Tidak ada simbol yang tidak digunakan + Delete Symbols Hapus Simbol One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Satu atau beberapa simbol sedang digunakan dan tidak dapat dihapus sampai instansinya diperluas atau dihapus. Expand Instances Perluas instansi Delete Instances Hapus instansi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b3bd272581..764059d5be 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -751,6 +751,9 @@ font-technology Variable Variabili Delete Swatch Elimina campione Delete Symbol Elimina simbolo Delete the selected symbol? Eliminare il simbolo selezionato? + Delete the selected symbols? Eliminare i simboli selezionati? + No unused symbols Nessun simbolo inutilizzato + Delete Symbols Elimina simboli One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Uno o più simboli sono in uso e non possono essere eliminati finché le loro istanze non vengono espanse o eliminate. Expand Instances Espandi istanze Delete Instances Elimina istanze diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 6a2c6ff4ef..7de9bc5bd6 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1308,6 +1308,9 @@ digits Malayalam マラヤーラム数字 Delete Swatch スウォッチを削除 Delete Symbol シンボルを削除 Delete the selected symbol? 選択したシンボルを削除しますか? + Delete the selected symbols? 選択したシンボルを削除しますか? + No unused symbols 未使用のシンボルはありません + Delete Symbols シンボルを削除 One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. 1 つ以上のシンボルが使用中のため、インスタンスを拡張または削除するまで削除できません。 Expand Instances インスタンスを拡張 Delete Instances インスタンスを削除 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b634eadf88..27be89a18b 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2668,6 +2668,9 @@ theme Appearance იერსახე Delete Brush ფუნჯის წაშლა Delete Symbol სიმბოლოს წაშლა Delete the selected symbol? წაიშალოს მონიშნული სიმბოლო? + Delete the selected symbols? წაიშალოს მონიშნული სიმბოლოები? + No unused symbols გამოუყენებელი სიმბოლოები არ არის + Delete Symbols სიმბოლოების წაშლა One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. ერთი ან მეტი სიმბოლო გამოიყენება და მისი წაშლა შეუძლებელია, სანამ მისი ეგზემპლარები არ გაიშლება ან არ წაიშლება. Expand Instances ეგზემპლარების გაშლა Delete Instances ეგზემპლარების წაშლა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 8cbb908f66..41ddf0a823 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1298,6 +1298,9 @@ digits Malayalam 말라얄람어 Delete Swatch 견본 삭제 Delete Symbol 심볼 삭제 Delete the selected symbol? 선택한 심볼을 삭제하시겠습니까? + Delete the selected symbols? 선택한 심볼을 모두 삭제하시겠습니까? + No unused symbols 사용하지 않는 심볼이 없습니다 + Delete Symbols 심볼 삭제 One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. 하나 이상의 심볼이 사용 중이므로 인스턴스를 확장하거나 삭제하기 전에는 삭제할 수 없습니다. Expand Instances 인스턴스 확장 Delete Instances 인스턴스 삭제 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 8e1401cc04..1434eb8c0e 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2869,6 +2869,9 @@ theme Appearance Vormgeving Delete Brush Penseel verwijderen Delete Symbol Symbool verwijderen Delete the selected symbol? Het geselecteerde symbool verwijderen? + Delete the selected symbols? De geselecteerde symbolen verwijderen? + No unused symbols Geen ongebruikte symbolen + Delete Symbols Symbolen verwijderen One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Een of meer van de symbolen zijn in gebruik en kunnen pas worden verwijderd als hun exemplaren zijn uitgebreid of verwijderd. Expand Instances Exemplaren uitbreiden Delete Instances Exemplaren verwijderen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index e11a11366d..ae48aacfc5 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2978,6 +2978,9 @@ theme Appearance Wygląd Delete Brush Usuń pędzel Delete Symbol Usuń symbol Delete the selected symbol? Usunąć zaznaczony symbol? + Delete the selected symbols? Usunąć zaznaczone symbole? + No unused symbols Brak nieużywanych symboli + Delete Symbols Usuń symbole One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Co najmniej jeden z symboli jest używany i nie można go usunąć, dopóki jego wystąpienia nie zostaną rozszerzone lub usunięte. Expand Instances Rozszerz wystąpienia Delete Instances Usuń wystąpienia diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index be472f5cfc..d1e0475908 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -664,6 +664,9 @@ Delete Swatch Excluir Amostra Delete Symbol Excluir Símbolo Delete the selected symbol? Excluir o símbolo selecionado? + Delete the selected symbols? Excluir os símbolos selecionados? + No unused symbols Nenhum símbolo não utilizado + Delete Symbols Excluir símbolos One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Um ou mais símbolos estão em uso e não podem ser excluídos até que suas instâncias sejam expandidas ou excluídas. Expand Instances Expandir Instâncias Delete Instances Excluir Instâncias diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 50f1057a3d..4d630635b6 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -749,6 +749,9 @@ font-technology Variable Вариативные Delete Swatch Удалить образец Delete Symbol Удалить символ Delete the selected symbol? Удалить выбранный символ? + Delete the selected symbols? Удалить выбранные символы? + No unused symbols Нет неиспользуемых символов + Delete Symbols Удалить символы One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Один или несколько символов используются, и их нельзя удалить, пока их экземпляры не будут разобраны или удалены. Expand Instances Разобрать экземпляры Delete Instances Удалить экземпляры diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index f0a3149f68..61dc8cbd69 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -738,6 +738,9 @@ font-technology Variable Variabla Delete Swatch Radera färgruta Delete Symbol Radera symbol Delete the selected symbol? Vill du radera den markerade symbolen? + Delete the selected symbols? Vill du radera de markerade symbolerna? + No unused symbols Inga oanvända symboler + Delete Symbols Radera symboler One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. En eller flera av symbolerna används och kan inte raderas förrän deras instanser har expanderats eller raderats. Expand Instances Expandera instanser Delete Instances Radera instanser diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 4c1b9eae30..fc59f56764 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -730,6 +730,9 @@ font-technology Variable Değişken Delete Swatch Renk Örneğini Sil Delete Symbol Sembolü Sil Delete the selected symbol? Seçili sembol silinsin mi? + Delete the selected symbols? Seçili semboller silinsin mi? + No unused symbols Kullanılmayan sembol yok + Delete Symbols Sembolleri Sil One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Sembollerden biri veya birkaçı kullanımda ve örnekleri genişletilene ya da silinene kadar silinemez. Expand Instances Örnekleri Genişlet Delete Instances Örnekleri Sil diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 446e45cfbf..a721beb969 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -745,6 +745,9 @@ font-technology Variable Варіативні Delete Swatch Видалити зразок Delete Symbol Видалити символ Delete the selected symbol? Видалити вибраний символ? + Delete the selected symbols? Видалити вибрані символи? + No unused symbols Немає невикористаних символів + Delete Symbols Видалити символи One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Один або кілька символів використовуються, і їх не можна видалити, доки їхні екземпляри не буде розібрано або видалено. Expand Instances Розібрати екземпляри Delete Instances Видалити екземпляри diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index a5ef6b2e0d..de0b1e822c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -871,6 +871,9 @@ font-technology Variable Biến thiên Delete Swatch Xóa mẫu màu Delete Symbol Xóa ký hiệu Delete the selected symbol? Xóa ký hiệu đã chọn? + Delete the selected symbols? Xóa các ký hiệu đã chọn? + No unused symbols Không có ký hiệu nào chưa dùng + Delete Symbols Xóa các ký hiệu One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Một hoặc nhiều ký hiệu đang được sử dụng và không thể xóa cho đến khi các thực thể của chúng được mở rộng hoặc xóa. Expand Instances Mở rộng thực thể Delete Instances Xóa thực thể diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 75d3e9dfdc..f5d3e051bb 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -694,6 +694,9 @@ Delete Swatch 删除色板 Delete Symbol 删除符号 Delete the selected symbol? 要删除所选符号吗? + Delete the selected symbols? 要删除所选的多个符号吗? + No unused symbols 没有未使用的符号 + Delete Symbols 删除符号 One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. 一个或多个符号正在使用中,在扩展或删除其实例之前无法删除。 Expand Instances 扩展实例 Delete Instances 删除实例 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e51a8896e0..7c2ad2ffec 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -713,6 +713,9 @@ font-technology Variable 可變 Delete Swatch 刪除色票 Delete Symbol 刪除符號 Delete the selected symbol? 要刪除選取的符號嗎? + Delete the selected symbols? 要刪除選取的多個符號嗎? + No unused symbols 沒有未使用的符號 + Delete Symbols 刪除符號 One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. 一個或多個符號正在使用中,在展開或刪除其範例之前無法刪除。 Expand Instances 展開範例 Delete Instances 刪除範例 From c492d524c5715ef3d1dd60e3ebf0a55dd23ca841 Mon Sep 17 00:00:00 2001 From: VladimirCeric <215285963+VladimirCeric@users.noreply.github.com> Date: Sat, 31 Oct 2026 20:38:07 +0100 Subject: [PATCH 221/260] Languages: Serbian (Cyrillic, Latin) and Croatian, with their quote marks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Document Setup and Character › Language list Serbian: Cyrillic (sr-Cyrl), Serbian: Latin (sr-Latn) and Croatian (hr). Text tagged Serbian is shaped in it (#4940, #4959), so fonts draw their Serbian forms, the italic б, г, д, п, т. Serbian quotes follow the Pravopis (Matica srpska 2010, т. 168) and CLDR: „…” and ’…’; Croatian per CLDR: „…“ and ‚…‘. Illustrator lists Croatian but not Serbian. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011wCJ9DkszhZKxYL3LgcSfZ --- crates/doc/src/setup.rs | 17 +++++++++++++++++ crates/text/src/features.rs | 19 +++++++++++++++++++ docs/type-parity.md | 5 +++-- 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index 62276ece90..d5abb8562d 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -164,6 +164,11 @@ pub const LANGUAGES: &[(&str, &str, Quotes)] = &[ ("Polish", "pl", Quotes { double: ['„', '”'], single: ['‚', '’'] }), ("Czech", "cs", Quotes { double: ['„', '“'], single: ['‚', '‘'] }), ("Russian", "ru", Quotes { double: ['«', '»'], single: ['„', '“'] }), + // Pravopis srpskoga jezika (Matica srpska, 2010, т. 168) and CLDR: „…” outside, ’…’ inside. + ("Serbian: Cyrillic", "sr-Cyrl", Quotes { double: ['„', '”'], single: ['’', '’'] }), + ("Serbian: Latin", "sr-Latn", Quotes { double: ['„', '”'], single: ['’', '’'] }), + // CLDR: „…“ outside, ‚…‘ inside. + ("Croatian", "hr", Quotes { double: ['„', '“'], single: ['‚', '‘'] }), ("Turkish", "tr", Quotes { double: ['“', '”'], single: ['‘', '’'] }), ("Japanese", "ja", Quotes { double: ['「', '」'], single: ['『', '』'] }), ("Chinese", "zh", Quotes { double: ['“', '”'], single: ['‘', '’'] }), @@ -373,6 +378,11 @@ mod tests { (char_language_name(None), char_language_name(Some("gu")), char_language_name(Some("x-unknown"))), (Some("English: USA"), Some("Gujarati"), None) ); + // Serbian in either script, and Croatian (which Illustrator also lists). + assert_eq!(char_language("Serbian: Cyrillic"), Ok(Some("sr-Cyrl"))); + assert_eq!(char_language("sr-latn"), Ok(Some("sr-Latn"))); + assert_eq!(char_language("Croatian"), Ok(Some("hr"))); + assert_eq!(char_language_name(Some("sr-Cyrl")), Some("Serbian: Cyrillic")); // Every entry has a tag of its own, and a name of its own. for (i, (n, t, _)) in LANGUAGES.iter().enumerate() { assert!(LANGUAGES.iter().skip(i + 1).all(|(n2, t2, _)| n2 != n && t2 != t), "{n} {t}"); @@ -387,6 +397,13 @@ mod tests { let mut prev = Some('('); assert_eq!(german.apply("\"a\"", &mut prev), "„a“"); assert_eq!(prev, Some('“')); + // Serbian closes high (”), with ’ on both sides of an inner quote; Croatian as German. + for name in ["Serbian: Cyrillic", "Serbian: Latin"] { + let mut prev = None; + assert_eq!(language_quotes(name).unwrap().apply("\"a 'b' c\"", &mut prev), "„a ’b’ c”", "{name}"); + } + let mut prev = None; + assert_eq!(language_quotes("croatian").unwrap().apply("\"a 'b' c\"", &mut prev), "„a ‚b‘ c“"); // Converting in pieces keeps the context. let mut prev = None; let a = Quotes::ENGLISH.apply("\"", &mut prev); diff --git a/crates/text/src/features.rs b/crates/text/src/features.rs index dd9c68c756..e2424c59ab 100644 --- a/crates/text/src/features.rs +++ b/crates/text/src/features.rs @@ -313,4 +313,23 @@ mod tests { let per_run: Vec<usize> = (0..2).map(|r| glyphs.iter().filter(|g| g.run == r).count()).collect(); assert_eq!(per_run, [2, 1]); } + + /// Serbian text gets the font's Serbian forms (`locl` for `SRB`): in the bundled Source Sans + /// 3 Italic, б, г, д, п, т differ from the Russian ones, in either Serbian list entry. + #[test] + fn serbian_gets_the_fonts_serbian_forms() { + let st = |language: &str| CharStyle { + font_family: "Source Sans 3".into(), + font_style: "Italic".into(), + language: Some(language.to_string()), + ..Default::default() + }; + let outlines = |language| { + layout(FontDb::global(), &TextObject::point(Point::ZERO, "бгдпт", st(language))).glyphs.into_iter().map(|g| g.outline).collect::<Vec<_>>() + }; + let (serbian, russian) = (outlines("sr-Cyrl"), outlines("ru")); + assert_eq!((serbian.len(), russian.len()), (5, 5)); + assert!(serbian.iter().zip(&russian).all(|(s, r)| s != r), "every letter in its Serbian form"); + assert_eq!(outlines("sr-Latn"), serbian); + } } diff --git a/docs/type-parity.md b/docs/type-parity.md index 6346c1b864..c48a1a208e 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Area Type Options › Text Flow by rows or by columns, #4978; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Serbian in Cyrillic and Latin and Croatian among the languages, with their quote marks; previously minor: Digits: the native digits of the Indic scripts, #4942; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -60,7 +60,7 @@ against Illustrator's public documentation; **estimated** unless noted. | CJK: Proportional Metrics (`palt` in horizontal type, `vpal` in vertical type) | done | #966 | | CJK: manual tate-chu-yoko | done | Character panel menu › Tate-chu-yoko (`text.setFormat` / `text.setRangeStyle {tateChuYoko}`), with Show East Asian Options: marked characters stand side by side across one em of a vertical column, squeezed to the em when wider; two or three half-width digits still do so without the mark; horizontal type keeps the mark and does not move them. Up/Down and Left/Right settings remain. Evidence: `tests_vertical::manual_tate_chu_yoko_sets_marked_characters_across_one_em`, `typecmd::tate_chu_yoko_is_a_character_attribute_saved_only_when_on` | | CJK: ruby, manual tate-chu-yoko | partial | ruby (ふりがな) for live text (`type.ruby`): a reading over a byte range, above (right of the column in vertical type) or below, start/centre/end alignment, size, overhang or squeeze; saved natively, laid out with its line growing, drawn on the canvas, in SVG and PDF (as outlines where ruby is present), in EPS, EMF/WMF and legacy `.ai` (legacy `.ai` writes type with ruby as outlines), and kept by Create Outlines, Expand Appearance and flattening, each glyph where the layout puts it (`typecmd::ruby_tests::create_outlines_keeps_the_ruby_where_it_is_laid_out`); manual tate-chu-yoko missing | #633 | -| Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). Not yet: hyphenation and spelling by it, `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set` | +| Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Serbian: Cyrillic, Serbian: Latin and Croatian, beyond Illustrator's list for Serbian); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). Not yet: hyphenation and spelling by it, `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set` | | No Break | done | Character panel menu (`text.setFormat` / `text.setRangeStyle {noBreak}`): the marked characters stay on one line, including across a space; a run that does not fit after earlier text moves together, and a run longer than the line stays together. Evidence: `layout::wrapping_tests::no_break_keeps_marked_characters_on_one_line`, `tests::no_break_keeps_marked_words_on_one_line`, `typecmd::no_break_is_a_character_attribute_saved_only_when_on` | | CJK: ruby | missing | #633 | | Inline symbols in text | beyond Illustrator | not scored | @@ -72,6 +72,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Serbian: Cyrillic (`sr-Cyrl`), Serbian: Latin (`sr-Latn`) and Croatian (`hr`) in the language list, with their quote marks (Serbian „…” and ’…’ per the Pravopis and CLDR, Croatian „…“ and ‚…‘ per CLDR); Serbian text gets the fonts' Serbian forms (italic б, г, д, п, т). the reference app lists Croatian but not Serbian; scores unchanged | | 2026-11-01 | minor | Area Type Options › Text Flow (#4978): By Rows / By Columns radio buttons and `text.areaOptions {flow}`; area type with several rows and columns fills them across each row first or down each column first (the default, so existing documents are unchanged; saved only when by rows); scores unchanged | | 2026-11-01 | minor | Digits (#4942): the native digits of Devanagari, Bengali, Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada and Malayalam in the Character panel menu › Digits and `{digits}`; scores unchanged | | 2026-11-01 | minor | Language per character (#4946): Character panel › Language, `text.setFormat` / `text.setRangeStyle {language}`, character styles; text is shaped in its language (`locl`, #4940); new type takes the document's; Indian languages in the list (#4943); scores unchanged | From d440b6d32be5d5b4737af9525cf6a17c36fa710f Mon Sep 17 00:00:00 2001 From: VladimirCeric <215285963+VladimirCeric@users.noreply.github.com> Date: Sat, 31 Oct 2026 20:58:45 +0100 Subject: [PATCH 222/260] Languages: cite the quote sources (Pravopis ISBN, CLDR links) From the CodeRabbit review: the Serbian and Croatian quote marks name their sources with the Pravopis's ISBN and links to CLDR's sr and hr data, in the code and in docs/type-parity.md; the quotes test says what it checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011wCJ9DkszhZKxYL3LgcSfZ --- crates/doc/src/setup.rs | 9 +++++++-- docs/type-parity.md | 1 + 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index d5abb8562d..506666a64a 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -164,10 +164,13 @@ pub const LANGUAGES: &[(&str, &str, Quotes)] = &[ ("Polish", "pl", Quotes { double: ['„', '”'], single: ['‚', '’'] }), ("Czech", "cs", Quotes { double: ['„', '“'], single: ['‚', '‘'] }), ("Russian", "ru", Quotes { double: ['«', '»'], single: ['„', '“'] }), - // Pravopis srpskoga jezika (Matica srpska, 2010, т. 168) and CLDR: „…” outside, ’…’ inside. + // „…” outside, ’…’ inside: Pravopis srpskoga jezika (Matica srpska, 2010, ISBN + // 978-86-7946-079-0, т. 168, pp. 133–135) and CLDR + // (https://github.com/unicode-org/cldr/blob/main/common/main/sr.xml, `delimiters`). ("Serbian: Cyrillic", "sr-Cyrl", Quotes { double: ['„', '”'], single: ['’', '’'] }), ("Serbian: Latin", "sr-Latn", Quotes { double: ['„', '”'], single: ['’', '’'] }), - // CLDR: „…“ outside, ‚…‘ inside. + // „…“ outside, ‚…‘ inside: CLDR (https://github.com/unicode-org/cldr/blob/main/common/main/hr.xml, + // `delimiters`). ("Croatian", "hr", Quotes { double: ['„', '“'], single: ['‚', '‘'] }), ("Turkish", "tr", Quotes { double: ['“', '”'], single: ['‘', '’'] }), ("Japanese", "ja", Quotes { double: ['「', '」'], single: ['『', '』'] }), @@ -389,6 +392,8 @@ mod tests { } } + /// Straight quotes become the language's: opening or closing by what comes before, inner + /// quotes as single ones, and the context carried across pieces converted apart. #[test] fn quotes_open_and_close_by_context() { let mut prev = None; diff --git a/docs/type-parity.md b/docs/type-parity.md index c48a1a208e..c306ac0f56 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -72,6 +72,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Serbian: Cyrillic (`sr-Cyrl`), Serbian: Latin (`sr-Latn`) and Croatian (`hr`) in the language list, with their quote marks (Serbian „…” and ’…’ per the Pravopis srpskoga jezika, Matica srpska 2010, ISBN 978-86-7946-079-0, т. 168, and [CLDR `sr`](https://github.com/unicode-org/cldr/blob/main/common/main/sr.xml); Croatian „…“ and ‚…‘ per [CLDR `hr`](https://github.com/unicode-org/cldr/blob/main/common/main/hr.xml)); Serbian text gets the fonts' Serbian forms (italic б, г, д, п, т). Illustrator lists Croatian but not Serbian; scores unchanged | | 2026-11-01 | minor | Serbian: Cyrillic (`sr-Cyrl`), Serbian: Latin (`sr-Latn`) and Croatian (`hr`) in the language list, with their quote marks (Serbian „…” and ’…’ per the Pravopis and CLDR, Croatian „…“ and ‚…‘ per CLDR); Serbian text gets the fonts' Serbian forms (italic б, г, д, п, т). the reference app lists Croatian but not Serbian; scores unchanged | | 2026-11-01 | minor | Area Type Options › Text Flow (#4978): By Rows / By Columns radio buttons and `text.areaOptions {flow}`; area type with several rows and columns fills them across each row first or down each column first (the default, so existing documents are unchanged; saved only when by rows); scores unchanged | | 2026-11-01 | minor | Digits (#4942): the native digits of Devanagari, Bengali, Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada and Malayalam in the Character panel menu › Digits and `{digits}`; scores unchanged | From 13dd4f9086fb65ae5ede1df0bc0a65d75e2caf95 Mon Sep 17 00:00:00 2001 From: VladimirCeric <215285963+VladimirCeric@users.noreply.github.com> Date: Sat, 31 Oct 2026 23:31:46 +0100 Subject: [PATCH 223/260] Languages: keep other apps' names out of the comments and docs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011wCJ9DkszhZKxYL3LgcSfZ --- crates/doc/src/setup.rs | 2 +- docs/type-parity.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index 506666a64a..c269181536 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -381,7 +381,7 @@ mod tests { (char_language_name(None), char_language_name(Some("gu")), char_language_name(Some("x-unknown"))), (Some("English: USA"), Some("Gujarati"), None) ); - // Serbian in either script, and Croatian (which Illustrator also lists). + // Serbian in either script, and Croatian. assert_eq!(char_language("Serbian: Cyrillic"), Ok(Some("sr-Cyrl"))); assert_eq!(char_language("sr-latn"), Ok(Some("sr-Latn"))); assert_eq!(char_language("Croatian"), Ok(Some("hr"))); diff --git a/docs/type-parity.md b/docs/type-parity.md index c306ac0f56..4d53b630df 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -60,7 +60,7 @@ against Illustrator's public documentation; **estimated** unless noted. | CJK: Proportional Metrics (`palt` in horizontal type, `vpal` in vertical type) | done | #966 | | CJK: manual tate-chu-yoko | done | Character panel menu › Tate-chu-yoko (`text.setFormat` / `text.setRangeStyle {tateChuYoko}`), with Show East Asian Options: marked characters stand side by side across one em of a vertical column, squeezed to the em when wider; two or three half-width digits still do so without the mark; horizontal type keeps the mark and does not move them. Up/Down and Left/Right settings remain. Evidence: `tests_vertical::manual_tate_chu_yoko_sets_marked_characters_across_one_em`, `typecmd::tate_chu_yoko_is_a_character_attribute_saved_only_when_on` | | CJK: ruby, manual tate-chu-yoko | partial | ruby (ふりがな) for live text (`type.ruby`): a reading over a byte range, above (right of the column in vertical type) or below, start/centre/end alignment, size, overhang or squeeze; saved natively, laid out with its line growing, drawn on the canvas, in SVG and PDF (as outlines where ruby is present), in EPS, EMF/WMF and legacy `.ai` (legacy `.ai` writes type with ruby as outlines), and kept by Create Outlines, Expand Appearance and flattening, each glyph where the layout puts it (`typecmd::ruby_tests::create_outlines_keeps_the_ruby_where_it_is_laid_out`); manual tate-chu-yoko missing | #633 | -| Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Serbian: Cyrillic, Serbian: Latin and Croatian, beyond Illustrator's list for Serbian); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). Not yet: hyphenation and spelling by it, `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set` | +| Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Serbian: Cyrillic, Serbian: Latin and Croatian); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). Not yet: hyphenation and spelling by it, `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set` | | No Break | done | Character panel menu (`text.setFormat` / `text.setRangeStyle {noBreak}`): the marked characters stay on one line, including across a space; a run that does not fit after earlier text moves together, and a run longer than the line stays together. Evidence: `layout::wrapping_tests::no_break_keeps_marked_characters_on_one_line`, `tests::no_break_keeps_marked_words_on_one_line`, `typecmd::no_break_is_a_character_attribute_saved_only_when_on` | | CJK: ruby | missing | #633 | | Inline symbols in text | beyond Illustrator | not scored | @@ -72,6 +72,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Serbian: Cyrillic (`sr-Cyrl`), Serbian: Latin (`sr-Latn`) and Croatian (`hr`) in the language list, with their quote marks (Serbian „…” and ’…’ per the Pravopis srpskoga jezika, Matica srpska 2010, ISBN 978-86-7946-079-0, т. 168, and [CLDR `sr`](https://github.com/unicode-org/cldr/blob/main/common/main/sr.xml); Croatian „…“ and ‚…‘ per [CLDR `hr`](https://github.com/unicode-org/cldr/blob/main/common/main/hr.xml)); Serbian text gets the fonts' Serbian forms (italic б, г, д, п, т); scores unchanged | | 2026-11-01 | minor | Serbian: Cyrillic (`sr-Cyrl`), Serbian: Latin (`sr-Latn`) and Croatian (`hr`) in the language list, with their quote marks (Serbian „…” and ’…’ per the Pravopis srpskoga jezika, Matica srpska 2010, ISBN 978-86-7946-079-0, т. 168, and [CLDR `sr`](https://github.com/unicode-org/cldr/blob/main/common/main/sr.xml); Croatian „…“ and ‚…‘ per [CLDR `hr`](https://github.com/unicode-org/cldr/blob/main/common/main/hr.xml)); Serbian text gets the fonts' Serbian forms (italic б, г, д, п, т). Illustrator lists Croatian but not Serbian; scores unchanged | | 2026-11-01 | minor | Serbian: Cyrillic (`sr-Cyrl`), Serbian: Latin (`sr-Latn`) and Croatian (`hr`) in the language list, with their quote marks (Serbian „…” and ’…’ per the Pravopis and CLDR, Croatian „…“ and ‚…‘ per CLDR); Serbian text gets the fonts' Serbian forms (italic б, г, д, п, т). the reference app lists Croatian but not Serbian; scores unchanged | | 2026-11-01 | minor | Area Type Options › Text Flow (#4978): By Rows / By Columns radio buttons and `text.areaOptions {flow}`; area type with several rows and columns fills them across each row first or down each column first (the default, so existing documents are unchanged; saved only when by rows); scores unchanged | From 7d0c0b589ed21cfd20c7d1f1eddb3a9500c7dc1d Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 07:19:41 +0700 Subject: [PATCH 224/260] docs: type-parity keeps one status line and one revision row for the Serbian and Croatian languages after the rebase --- docs/type-parity.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/type-parity.md b/docs/type-parity.md index 4d53b630df..50f4e44bce 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Serbian in Cyrillic and Latin and Croatian among the languages, with their quote marks; previously minor: Digits: the native digits of the Indic scripts, #4942; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Serbian in Cyrillic and Latin and Croatian among the languages, with their quote marks; previously minor: Area Type Options › Text Flow by rows or by columns, #4978; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -73,8 +73,6 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| | 2026-11-01 | minor | Serbian: Cyrillic (`sr-Cyrl`), Serbian: Latin (`sr-Latn`) and Croatian (`hr`) in the language list, with their quote marks (Serbian „…” and ’…’ per the Pravopis srpskoga jezika, Matica srpska 2010, ISBN 978-86-7946-079-0, т. 168, and [CLDR `sr`](https://github.com/unicode-org/cldr/blob/main/common/main/sr.xml); Croatian „…“ and ‚…‘ per [CLDR `hr`](https://github.com/unicode-org/cldr/blob/main/common/main/hr.xml)); Serbian text gets the fonts' Serbian forms (italic б, г, д, п, т); scores unchanged | -| 2026-11-01 | minor | Serbian: Cyrillic (`sr-Cyrl`), Serbian: Latin (`sr-Latn`) and Croatian (`hr`) in the language list, with their quote marks (Serbian „…” and ’…’ per the Pravopis srpskoga jezika, Matica srpska 2010, ISBN 978-86-7946-079-0, т. 168, and [CLDR `sr`](https://github.com/unicode-org/cldr/blob/main/common/main/sr.xml); Croatian „…“ and ‚…‘ per [CLDR `hr`](https://github.com/unicode-org/cldr/blob/main/common/main/hr.xml)); Serbian text gets the fonts' Serbian forms (italic б, г, д, п, т). Illustrator lists Croatian but not Serbian; scores unchanged | -| 2026-11-01 | minor | Serbian: Cyrillic (`sr-Cyrl`), Serbian: Latin (`sr-Latn`) and Croatian (`hr`) in the language list, with their quote marks (Serbian „…” and ’…’ per the Pravopis and CLDR, Croatian „…“ and ‚…‘ per CLDR); Serbian text gets the fonts' Serbian forms (italic б, г, д, п, т). the reference app lists Croatian but not Serbian; scores unchanged | | 2026-11-01 | minor | Area Type Options › Text Flow (#4978): By Rows / By Columns radio buttons and `text.areaOptions {flow}`; area type with several rows and columns fills them across each row first or down each column first (the default, so existing documents are unchanged; saved only when by rows); scores unchanged | | 2026-11-01 | minor | Digits (#4942): the native digits of Devanagari, Bengali, Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada and Malayalam in the Character panel menu › Digits and `{digits}`; scores unchanged | | 2026-11-01 | minor | Language per character (#4946): Character panel › Language, `text.setFormat` / `text.setRangeStyle {language}`, character styles; text is shaped in its language (`locl`, #4940); new type takes the document's; Indian languages in the list (#4943); scores unchanged | From ef80709e168b26e916f5f97297be385102471687 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 07:17:08 +0700 Subject: [PATCH 225/260] Fix #4925: Randomize Opacity gives each selected object a random opacity in a range --- ROADMAP.md | 4 +- crates/engine/src/cmd/addons/arrange.rs | 43 +++++++++- crates/engine/src/cmd/addons/arrange/tests.rs | 82 ++++++++++++++++++- crates/engine/tests/command_sweep.rs | 3 + crates/ui-egui/src/addons/arrange.rs | 35 ++++++-- crates/ui-egui/src/addons/arrange/tests.rs | 31 ++++++- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/i18n/bg.tsv | 7 ++ crates/ui-egui/src/i18n/bs.tsv | 7 ++ crates/ui-egui/src/i18n/ca.tsv | 7 ++ crates/ui-egui/src/i18n/cs.tsv | 7 ++ crates/ui-egui/src/i18n/da.tsv | 7 ++ crates/ui-egui/src/i18n/de.tsv | 7 ++ crates/ui-egui/src/i18n/el.tsv | 7 ++ crates/ui-egui/src/i18n/es.tsv | 7 ++ crates/ui-egui/src/i18n/fi.tsv | 7 ++ crates/ui-egui/src/i18n/fr.tsv | 7 ++ crates/ui-egui/src/i18n/hu.tsv | 7 ++ crates/ui-egui/src/i18n/id.tsv | 7 ++ crates/ui-egui/src/i18n/it.tsv | 7 ++ crates/ui-egui/src/i18n/ja.tsv | 7 ++ crates/ui-egui/src/i18n/ka.tsv | 7 ++ crates/ui-egui/src/i18n/ko.tsv | 7 ++ crates/ui-egui/src/i18n/nl.tsv | 7 ++ crates/ui-egui/src/i18n/pl.tsv | 7 ++ crates/ui-egui/src/i18n/pt-br.tsv | 7 ++ crates/ui-egui/src/i18n/ru.tsv | 7 ++ crates/ui-egui/src/i18n/sv.tsv | 7 ++ crates/ui-egui/src/i18n/tr.tsv | 7 ++ crates/ui-egui/src/i18n/uk.tsv | 7 ++ crates/ui-egui/src/i18n/vi.tsv | 7 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 7 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 7 ++ docs/mcp.md | 7 +- docs/target-app-parity.md | 7 +- docs/ui-parity.md | 4 +- 36 files changed, 383 insertions(+), 17 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 0206168ac1..4c33d5d169 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -9,7 +9,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Document Tools add-on's New Symbols from Layers; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Arrange Tools add-on's Randomize Opacity; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<name>_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. @@ -208,6 +209,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Randomize Opacity (#4925); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Document Tools add-on's New Symbols from Layers (#4927); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Document Tools add-on's Save a Timestamped Copy (#4926); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for Divide into Dashes (Path Precision Tools add-on, #4950); headline numbers unchanged. | diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 986016213e..0a7d168d06 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -3,8 +3,9 @@ //! Replace with Top Object puts a copy of the topmost selected object in place of each of the //! others; and Set Size of Each gives every selected object an exact width and height. Places and //! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the -//! objects whose visual bounds overlap. Its submenu (Object › Plug-ins › Arrange -//! Tools), its dialogs and Zoom to Selection (a view command) are the UI's. +//! objects whose visual bounds overlap, and Randomize Opacity gives each selected object a random +//! opacity. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection (a +//! view command) are the UI's. #[cfg(test)] mod tests; @@ -12,14 +13,16 @@ mod tests; use std::sync::Arc; use serde_json::{Value, json}; +use vectorcraft_color::recolor::Rng; use vectorcraft_doc::{Node, NodeId, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect}; use vectorcraft_render::effects; use super::super::edit::selected_roots; +use super::super::menucmds::whole_or; use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns}; use super::super::typecmd::refresh_bounds_of; -use super::super::{CommandSpec, bad, cmd, has_doc, has_multi, has_selection, number_or, switch_or}; +use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_multi, has_selection, number_or, switch_or}; use crate::{EngineError, Result, Session}; /// The largest gap, width or height (pt) the commands take. @@ -78,6 +81,15 @@ pub fn specs() -> Vec<CommandSpec> { has_multi, group_overlapping ), + cmd!( + "addon.arrange.randomizeOpacity", + "Randomize Opacity", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step; it is the object's opacity, as the Transparency panel sets it → {count}", + has_selection, + randomize_opacity + ), ] } @@ -356,3 +368,28 @@ fn group_overlapping(s: &mut Session, _: &Value) -> Result<Value> { })?; Ok(json!({ "groups": groups.iter().map(|i| i.0).collect::<Vec<_>>(), "grouped": grouped.len() })) } + +fn randomize_opacity(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "addon.arrange.randomizeOpacity"; + let min = number_in(p, "min", 30.0, (0.0, 100.0), C)?; + let max = number_in(p, "max", 100.0, (0.0, 100.0), C)?; + if min > max { + return Err(bad(C, "`min` is greater than `max`")); + } + let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); + let ids = checked_ids_or_selection(s, p, C)?; + if ids.is_empty() { + return Ok(json!({ "count": 0 })); + } + let (lo, hi) = ((min / 100.0) as f32, (max / 100.0) as f32); + s.edit("Randomize Opacity", |d, _| { + for id in &ids { + let o = rng.range(lo, hi); + if let Some(n) = d.node_mut(*id) { + n.opacity = o; + } + } + Ok(()) + })?; + Ok(json!({ "count": ids.len() })) +} diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 48f9ae4ec9..e19969f2e4 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -256,7 +256,14 @@ fn off_without_a_selection() { let mut s = session(); rect(&mut s, 0.0, 0.0, 20.0, 10.0); s.execute("select.none", &json!({})).unwrap(); - for c in ["addon.arrange.grid", "addon.arrange.swap", "addon.arrange.replace", "addon.arrange.size", "addon.arrange.groupOverlapping"] { + for c in [ + "addon.arrange.grid", + "addon.arrange.swap", + "addon.arrange.replace", + "addon.arrange.size", + "addon.arrange.groupOverlapping", + "addon.arrange.randomizeOpacity", + ] { assert!(!enabled(&s, c), "{c}"); } assert!(!enabled(&Session::new(), "addon.arrange.swap")); @@ -336,3 +343,76 @@ fn group_overlapping_is_off_with_one_object_and_scales_to_many() { assert_eq!(sets.len(), 2000); assert!(sets.iter().all(|s| s.len() == 2 && s[1] == s[0] + 1)); } + +fn opacity(s: &Session, id: NodeId) -> f32 { + s.doc().unwrap().doc.node(id).unwrap().opacity +} + +#[test] +fn randomize_opacity_gives_each_object_its_own_opacity_within_the_range() { + let mut s = session(); + let ids: Vec<NodeId> = (0..20).map(|i| rect(&mut s, i as f64 * 10.0, 0.0, 5.0, 5.0)).collect(); + select(&mut s, &ids); + let n = steps(&s); + let r = s.execute("addon.arrange.randomizeOpacity", &json!({"min": 30, "max": 60, "seed": 7})).unwrap(); + assert_eq!(r["count"], json!(20)); + assert_eq!(steps(&s), n + 1, "one undo step"); + let first: Vec<f32> = ids.iter().map(|id| opacity(&s, *id)).collect(); + assert!(first.iter().all(|o| (0.3..=0.6).contains(o)), "{first:?}"); + assert!(first.windows(2).any(|w| w[0] != w[1]), "each its own: {first:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(ids.iter().all(|id| opacity(&s, *id) == 1.0), "undone"); + // The same seed repeats them; another seed doesn't. + s.execute("addon.arrange.randomizeOpacity", &json!({"min": 30, "max": 60, "seed": 7})).unwrap(); + assert_eq!(ids.iter().map(|id| opacity(&s, *id)).collect::<Vec<_>>(), first); + s.execute("addon.arrange.randomizeOpacity", &json!({"min": 30, "max": 60, "seed": 8})).unwrap(); + assert_ne!(ids.iter().map(|id| opacity(&s, *id)).collect::<Vec<_>>(), first); + // Defaults 30 to 100; min = max gives every object that opacity. + s.execute("addon.arrange.randomizeOpacity", &json!({})).unwrap(); + assert!(ids.iter().all(|id| (0.3..=1.0).contains(&opacity(&s, *id)))); + s.execute("addon.arrange.randomizeOpacity", &json!({"min": 45, "max": 45})).unwrap(); + assert!(ids.iter().all(|id| opacity(&s, *id) == 0.45)); +} + +#[test] +fn randomize_opacity_takes_ids_and_leaves_the_rest() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 5.0, 5.0); + let b = rect(&mut s, 10.0, 0.0, 5.0, 5.0); + select(&mut s, &[a, b]); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let c = rect(&mut s, 20.0, 0.0, 5.0, 5.0); + s.execute("select.none", &json!({})).unwrap(); + assert!(!enabled(&s, "addon.arrange.randomizeOpacity")); + s.execute("addon.arrange.randomizeOpacity", &json!({"ids": [c.0], "min": 10, "max": 10})).unwrap(); + assert_eq!((opacity(&s, a), opacity(&s, b), opacity(&s, c)), (1.0, 1.0, 0.1)); + // A group takes one opacity of its own; the objects inside keep theirs. + select(&mut s, &[g]); + s.execute("addon.arrange.randomizeOpacity", &json!({"min": 20, "max": 20})).unwrap(); + assert_eq!((opacity(&s, g), opacity(&s, a), opacity(&s, b)), (0.2, 1.0, 1.0)); +} + +#[test] +fn randomize_opacity_refuses_bad_params() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0); + select(&mut s, &[a]); + refuses( + &mut s, + "addon.arrange.randomizeOpacity", + &[ + json!({"min": -1}), + json!({"max": 101}), + json!({"min": 80, "max": 20}), + json!({"min": 1e308}), + json!({"max": "50"}), + json!({"seed": -1}), + json!({"seed": 1.5}), + json!({"seed": "x"}), + json!({"ids": [999_999]}), + json!({"ids": "x"}), + ], + ); + let e = s.execute("addon.arrange.randomizeOpacity", &json!({"min": 80, "max": 20})).unwrap_err().to_string(); + assert!(e.contains("`min` is greater than `max`"), "{e}"); +} diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index fd879a301e..06046338fa 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -589,6 +589,9 @@ fn structured_junk() { ("addon.arrange.size", json!({"width": 1e6, "height": 0.001, "reference": 8, "scaleStrokes": true})), ("addon.arrange.size", json!({"width": 0.001, "proportional": true, "reference": u64::MAX})), ("addon.arrange.groupOverlapping", json!({"ids": "x", "junk": f64::MAX})), + ("addon.arrange.randomizeOpacity", json!({"min": 0, "max": 100, "seed": u64::MAX})), + ("addon.arrange.randomizeOpacity", json!({"min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})), + ("addon.arrange.randomizeOpacity", json!({"min": 100, "max": 0, "seed": 1e308, "ids": []})), ("addon.pathtools.divideDashes", json!({"dash": 1e-308, "gap": -1e308, "fit": "x"})), ("addon.pathtools.divideDashes", json!({"dash": 0.01, "gap": 1e6, "fit": true, "removeGaps": false})), ("addon.pathtools.divideDashes", json!({"dash": f64::MAX, "gap": [0], "removeGaps": null})), diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index f33757cee6..f251aa69da 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -1,7 +1,7 @@ //! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of -//! Arrange in Grid, Replace with Top Object and Set Size of Each, which preview on the canvas and -//! run their `addon.arrange.*` command on OK; Group Overlapping Objects; and Zoom to Selection ([`ZOOM`]), which fits the -//! active view to the selection. +//! Arrange in Grid, Replace with Top Object, Set Size of Each and Randomize Opacity, which preview +//! on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping Objects; and Zoom +//! to Selection ([`ZOOM`]), which fits the active view to the selection. use egui::Ui; use serde_json::{Value, json}; @@ -18,15 +18,19 @@ pub const ZOOM: &str = "addon.arrange.zoomSelection"; pub const GRID: &str = "arrangeGrid"; pub const REPLACE: &str = "arrangeReplace"; pub const SIZE: &str = "arrangeSize"; +pub const OPACITY: &str = "arrangeOpacity"; /// Each dialog's kind, command and heading. -const DIALOGS: [(&str, &str, &str); 3] = [ +const DIALOGS: [(&str, &str, &str); 4] = [ (GRID, "addon.arrange.grid", "Arrange in Grid"), (REPLACE, "addon.arrange.replace", "Replace with Top Object"), (SIZE, "addon.arrange.size", "Set Size of Each"), + (OPACITY, "addon.arrange.randomizeOpacity", "Randomize Opacity"), ]; /// The widths and heights Set Size of Each takes (pt), and the gaps Arrange in Grid takes. const SIZES: std::ops::RangeInclusive<f64> = 0.001..=1e6; const GAPS: std::ops::RangeInclusive<f64> = -1e6..=1e6; +/// The seeds the Randomize Opacity dialog offers. +const SEEDS: u64 = 1_000_000; const LABEL_W: f32 = 110.0; const FIELD_W: f32 = 90.0; @@ -39,6 +43,7 @@ pub fn menu() -> Vec<Item> { Item::Cmd("Replace with Top Object…", "addon.arrange.replace", Value::Null), Item::Cmd("Set Size of Each…", "addon.arrange.size", Value::Null), Item::Cmd("Group Overlapping Objects", "addon.arrange.groupOverlapping", json!({})), + Item::Cmd("Randomize Opacity…", "addon.arrange.randomizeOpacity", Value::Null), Item::Sep, Item::Cmd("Zoom to Selection", ZOOM, json!({})), ] @@ -57,6 +62,8 @@ pub(crate) fn dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static str, Va "gapX": 10, "gapY": 10, "centerOnArtboard": false, }), REPLACE => json!({ "fit": "keep", "keep": false, "scaleStrokes": strokes }), + // A new seed each time the document has changed, so running it again varies the result. + OPACITY => json!({ "min": 30, "max": 100, "seed": st.revision % SEEDS }), // The first selected object's size, as the command measures it (a side it lacks: the least). _ => { let b = st.selection.objects.first().and_then(|id| app.session.transform_box(&[*id])).map_or((100.0, 100.0), |b| { @@ -76,7 +83,11 @@ pub(crate) const SPEC: DialogSpec = DialogSpec { confirm, preview: true, min_width: 320.0, - ok_enabled: Some(|_, d| d.kind != SIZE || d.bool("__width") || d.bool("__height")), + ok_enabled: Some(|_, d| match d.kind.as_str() { + SIZE => d.bool("__width") || d.bool("__height"), + OPACITY => d.f64("min", 0.0) <= d.f64("max", 100.0), + _ => true, + }), ..DialogSpec::FORM }; @@ -126,6 +137,20 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { form::check(ui, d, "keep", tl!("Keep Original")); form::check(ui, d, "scaleStrokes", tl!("Scale Strokes & Effects")); } + OPACITY => { + for (key, label) in [("min", tl!("Minimum:")), ("max", tl!("Maximum:"))] { + widgets::label_row(ui, label, LABEL_W, |ui| { + if let Some(v) = widgets::range_field(ui, ("arrange", key), d.f64(key, 0.0), 0.0..=100.0, "%", 0, FIELD_W) { + d.fields.insert(key.into(), json!(v)); + } + }); + } + widgets::label_row(ui, tl!("Seed:"), LABEL_W, |ui| { + if let Some(v) = widgets::range_field(ui, ("arrange", "seed"), d.f64("seed", 0.0), 0.0..=(SEEDS - 1) as f64, "", 0, FIELD_W) { + d.fields.insert("seed".into(), json!(v as u64)); + } + }); + } _ => { egui::Grid::new("arrange-size").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { for (side, tick, label) in [("width", "__width", tl!("Width:")), ("height", "__height", tl!("Height:"))] { diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 72411f3889..6aa8646738 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -2,7 +2,7 @@ use serde_json::json; use vectorcraft_doc::NodeId; use vectorcraft_engine::Session; -use super::{GRID, REPLACE, SIZE, ZOOM}; +use super::{GRID, OPACITY, REPLACE, SIZE, ZOOM}; use crate::tests_labels::painted_text; use crate::{VectorcraftApp, menus}; @@ -41,6 +41,7 @@ fn the_plugins_submenu_lists_the_tools() { ("Replace with Top Object…", "addon.arrange.replace"), ("Set Size of Each…", "addon.arrange.size"), ("Group Overlapping Objects", "addon.arrange.groupOverlapping"), + ("Randomize Opacity…", "addon.arrange.randomizeOpacity"), ("Zoom to Selection", ZOOM), ] { assert_eq!(under(label).and_then(|e| e.command.as_deref()), Some(id), "{label}"); @@ -139,3 +140,31 @@ fn group_overlapping_objects_runs_directly() { assert_eq!(doc.parent_of(c), Some(g), "a and c overlap: grouped"); assert_ne!(doc.parent_of(b), Some(g), "b is left alone"); } + +#[test] +fn randomize_opacity_opens_its_dialog_and_runs_on_ok() { + let (mut app, a, b) = app(); + click(&mut app, "Randomize Opacity…"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(OPACITY)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Randomize Opacity", "Minimum:", "Maximum:", "Seed:", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((&d.fields["min"], &d.fields["max"]), (&json!(30), &json!(100))); + // Minimum above maximum: OK is off. + d.fields.insert("min".into(), json!(80)); + d.fields.insert("max".into(), json!(20)); + assert!(!(crate::addons::arrange::SPEC.ok_enabled.unwrap())(&app, app.ui.dialog.as_ref().unwrap())); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("min".into(), json!(40)); + d.fields.insert("max".into(), json!(60)); + let n = app.session.doc().unwrap().history.undo.len(); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1); + let doc = &app.session.doc().unwrap().doc; + for id in [a, b] { + assert!((0.4..=0.6).contains(&doc.node(id).unwrap().opacity), "{id:?}"); + } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index f9da884c40..371c02695d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -400,7 +400,7 @@ registry! { RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC, PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC, DivideDashes: [crate::addons::pathtools::dashes::KIND] => crate::addons::pathtools::dashes::SPEC, - ArrangeTools: [crate::addons::arrange::GRID, crate::addons::arrange::REPLACE, crate::addons::arrange::SIZE] => crate::addons::arrange::SPEC, + ArrangeTools: [crate::addons::arrange::GRID, crate::addons::arrange::REPLACE, crate::addons::arrange::SIZE, crate::addons::arrange::OPACITY] => crate::addons::arrange::SPEC, ShortcutImport: [shortcut_import::KIND] => DialogSpec::window(shortcut_import::show, shortcut_import::confirm), } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index f4bbcda00d..01896f2ed9 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5999,3 +5999,10 @@ breakText Glyphs Глифи Text Flow Поток на текста By Rows По редове By Columns По колони +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Произволна непрозрачност… + Randomize Opacity Произволна непрозрачност + Minimum: Минимум: + Maximum: Максимум: + Seed: Начално число: +@msg `min` is greater than `max` `min` е по-голямо от `max` diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index ab592a2919..e32201e97e 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6032,3 +6032,10 @@ shape Open Otvoren Text Flow Tok teksta By Rows Po redovima By Columns Po kolonama +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Nasumična neprozirnost… + Randomize Opacity Nasumična neprozirnost + Minimum: Minimum: + Maximum: Maksimum: + Seed: Početna vrijednost: +@msg `min` is greater than `max` `min` je veće od `max` diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index fe48fb73ac..e5ec3feb60 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6105,3 +6105,10 @@ breakText Glyphs Glifs Text Flow Flux del text By Rows Per files By Columns Per columnes +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Opacitat aleatòria… + Randomize Opacity Opacitat aleatòria + Minimum: Mínim: + Maximum: Màxim: + Seed: Llavor: +@msg `min` is greater than `max` `min` és més gran que `max` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 2f2892c006..0efefa092b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6115,3 +6115,10 @@ breakText Glyphs Glyfy Text Flow Tok textu By Rows Po řádcích By Columns Po sloupcích +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Náhodné krytí… + Randomize Opacity Náhodné krytí + Minimum: Minimum: + Maximum: Maximum: + Seed: Počáteční hodnota: +@msg `min` is greater than `max` `min` je větší než `max` diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 056f8c3576..f4d16eef28 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6014,3 +6014,10 @@ breakText Glyphs Glyffer Text Flow Tekstflow By Rows Efter rækker By Columns Efter kolonner +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Tilfældig opacitet… + Randomize Opacity Tilfældig opacitet + Minimum: Minimum: + Maximum: Maksimum: + Seed: Startværdi: +@msg `min` is greater than `max` `min` er større end `max` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 23336fb9ff..18ea74459d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5700,3 +5700,10 @@ breakText Glyphs Glyphen Text Flow Textfluss By Rows Nach Zeilen By Columns Nach Spalten +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Zufällige Deckkraft… + Randomize Opacity Zufällige Deckkraft + Minimum: Minimum: + Maximum: Maximum: + Seed: Startwert: +@msg `min` is greater than `max` `min` ist größer als `max` diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 83d50b7527..15c008eb8e 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6067,3 +6067,10 @@ breakText Glyphs Γλύφοι Text Flow Ροή κειμένου By Rows Κατά γραμμές By Columns Κατά στήλες +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Τυχαία αδιαφάνεια… + Randomize Opacity Τυχαία αδιαφάνεια + Minimum: Ελάχιστο: + Maximum: Μέγιστο: + Seed: Αρχική τιμή: +@msg `min` is greater than `max` Το `min` είναι μεγαλύτερο από το `max` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a6824a320b..f69b7bec9c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6057,3 +6057,10 @@ breakText Glyphs Glifos Text Flow Flujo de texto By Rows Por filas By Columns Por columnas +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Opacidad aleatoria… + Randomize Opacity Opacidad aleatoria + Minimum: Mínimo: + Maximum: Máximo: + Seed: Semilla: +@msg `min` is greater than `max` `min` es mayor que `max` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 87debec2ef..fc76393f68 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6145,3 +6145,10 @@ breakText Glyphs Merkit Text Flow Tekstin kulku By Rows Riveittäin By Columns Sarakkeittain +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Satunnainen peittävyys… + Randomize Opacity Satunnainen peittävyys + Minimum: Pienin: + Maximum: Suurin: + Seed: Siemen: +@msg `min` is greater than `max` `min` on suurempi kuin `max` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index b210563245..24a3a59ad9 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6112,3 +6112,10 @@ breakText Glyphs Glyphes Text Flow Flux du texte By Rows Par lignes By Columns Par colonnes +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Opacité aléatoire… + Randomize Opacity Opacité aléatoire + Minimum: Minimum : + Maximum: Maximum : + Seed: Graine : +@msg `min` is greater than `max` `min` est supérieur à `max` diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 729597666d..29305857e7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6101,3 +6101,10 @@ breakText Glyphs Glifák Text Flow Szövegfolyás By Rows Soronként By Columns Oszloponként +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Véletlenszerű átlátszatlanság… + Randomize Opacity Véletlenszerű átlátszatlanság + Minimum: Minimum: + Maximum: Maximum: + Seed: Kezdőérték: +@msg `min` is greater than `max` `min` nagyobb, mint `max` diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 82337045e9..b682c757f9 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6014,3 +6014,10 @@ breakText Glyphs Glif Text Flow Alur teks By Rows Per baris By Columns Per kolom +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Opasitas acak… + Randomize Opacity Opasitas acak + Minimum: Minimum: + Maximum: Maksimum: + Seed: Benih: +@msg `min` is greater than `max` `min` lebih besar dari `max` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 764059d5be..74fcfb60c7 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5734,3 +5734,10 @@ breakText Glyphs Glifi Text Flow Flusso del testo By Rows Per righe By Columns Per colonne +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Opacità casuale… + Randomize Opacity Opacità casuale + Minimum: Minimo: + Maximum: Massimo: + Seed: Seme: +@msg `min` is greater than `max` `min` è maggiore di `max` diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 7de9bc5bd6..69ee5fd860 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5801,3 +5801,10 @@ breakText Glyphs 字形 Text Flow テキストの流れ By Rows 行方向 By Columns 列方向 +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… 不透明度をランダム化… + Randomize Opacity 不透明度をランダム化 + Minimum: 最小: + Maximum: 最大: + Seed: シード: +@msg `min` is greater than `max` `min` が `max` より大きくなっています diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 27be89a18b..07fc51fb93 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6104,3 +6104,10 @@ breakText Glyphs გლიფები Text Flow ტექსტის დინება By Rows სტრიქონების მიხედვით By Columns სვეტების მიხედვით +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… შემთხვევითი გაუმჭვირვალობა… + Randomize Opacity შემთხვევითი გაუმჭვირვალობა + Minimum: მინიმუმი: + Maximum: მაქსიმუმი: + Seed: საწყისი რიცხვი: +@msg `min` is greater than `max` `min` მეტია, ვიდრე `max` diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 41ddf0a823..022d194942 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5697,3 +5697,10 @@ breakText Glyphs 글리프 Text Flow 텍스트 흐름 By Rows 행 방향 By Columns 열 방향 +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… 불투명도 무작위화… + Randomize Opacity 불투명도 무작위화 + Minimum: 최소: + Maximum: 최대: + Seed: 시드: +@msg `min` is greater than `max` `min`이(가) `max`보다 큽니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 1434eb8c0e..a1ace51902 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6058,3 +6058,10 @@ breakText Glyphs Glyphs Text Flow Tekstdoorloop By Rows Per rij By Columns Per kolom +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Willekeurige dekking… + Randomize Opacity Willekeurige dekking + Minimum: Minimum: + Maximum: Maximum: + Seed: Startwaarde: +@msg `min` is greater than `max` `min` is groter dan `max` diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index ae48aacfc5..fc4cb57487 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5970,3 +5970,10 @@ breakText Glyphs Glify Text Flow Przepływ tekstu By Rows Wierszami By Columns Kolumnami +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Losowe krycie… + Randomize Opacity Losowe krycie + Minimum: Minimum: + Maximum: Maksimum: + Seed: Ziarno: +@msg `min` is greater than `max` `min` jest większe niż `max` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index d1e0475908..bf70bd2fdd 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6189,3 +6189,10 @@ swatch Yellow Green Verde-amarelado Text Flow Fluxo do texto By Rows Por linhas By Columns Por colunas +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Opacidade aleatória… + Randomize Opacity Opacidade aleatória + Minimum: Mínimo: + Maximum: Máximo: + Seed: Semente: +@msg `min` is greater than `max` `min` é maior que `max` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 4d630635b6..566cd78a22 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6092,3 +6092,10 @@ breakText Glyphs Глифы Text Flow Поток текста By Rows По строкам By Columns По столбцам +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Случайная непрозрачность… + Randomize Opacity Случайная непрозрачность + Minimum: Минимум: + Maximum: Максимум: + Seed: Начальное число: +@msg `min` is greater than `max` `min` больше, чем `max` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 61dc8cbd69..e93c877feb 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6167,3 +6167,10 @@ breakText Glyphs Glyfer Text Flow Textflöde By Rows Radvis By Columns Kolumnvis +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Slumpmässig opacitet… + Randomize Opacity Slumpmässig opacitet + Minimum: Minimum: + Maximum: Maximum: + Seed: Startvärde: +@msg `min` is greater than `max` `min` är större än `max` diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index fc59f56764..9fdffe5446 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6072,3 +6072,10 @@ breakText Glyphs Glifler Text Flow Metin Akışı By Rows Satırlara Göre By Columns Sütunlara Göre +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Rastgele Opaklık… + Randomize Opacity Rastgele Opaklık + Minimum: En Az: + Maximum: En Çok: + Seed: Başlangıç Değeri: +@msg `min` is greater than `max` `min`, `max` değerinden büyük diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index a721beb969..f0fed9fb4e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5714,3 +5714,10 @@ breakText Glyphs Гліфи Text Flow Потік тексту By Rows За рядками By Columns За стовпцями +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Випадкова непрозорість… + Randomize Opacity Випадкова непрозорість + Minimum: Мінімум: + Maximum: Максимум: + Seed: Початкове число: +@msg `min` is greater than `max` `min` більше за `max` diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index de0b1e822c..7cb29ce4f9 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5717,3 +5717,10 @@ breakText Glyphs Glyph Text Flow Luồng văn bản By Rows Theo hàng By Columns Theo cột +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… Độ mờ ngẫu nhiên… + Randomize Opacity Độ mờ ngẫu nhiên + Minimum: Tối thiểu: + Maximum: Tối đa: + Seed: Giá trị khởi đầu: +@msg `min` is greater than `max` `min` lớn hơn `max` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f5d3e051bb..b160639b04 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5957,3 +5957,10 @@ breakText Glyphs 字形 Text Flow 文本流向 By Rows 按行 By Columns 按列 +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… 随机不透明度… + Randomize Opacity 随机不透明度 + Minimum: 最小值: + Maximum: 最大值: + Seed: 种子: +@msg `min` is greater than `max` `min` 大于 `max` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 7c2ad2ffec..aefdbb3665 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5754,3 +5754,10 @@ breakText Glyphs 字符 Text Flow 文字流向 By Rows 依列 By Columns 依欄 +# Arrange Tools add-on: Randomize Opacity. + Randomize Opacity… 隨機不透明度… + Randomize Opacity 隨機不透明度 + Minimum: 最小值: + Maximum: 最大值: + Seed: 種子: +@msg `min` is greater than `max` `min` 大於 `max` diff --git a/docs/mcp.md b/docs/mcp.md index 31f541e064..2a8210444a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6341,12 +6341,13 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | +| `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. → `{count}` | Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, -and fails with nothing selected. Arrange in Grid…, Replace with Top Object… and Set Size of Each… open dialogs -(`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace` and `arrangeSize`) whose fields are the -command's parameters, with Preview; Set Size of Each's `__width` and `__height` say which sizes OK applies. +and fails with nothing selected. Arrange in Grid…, Replace with Top Object…, Set Size of Each… and Randomize Opacity… open dialogs +(`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace`, `arrangeSize` and `arrangeOpacity`) whose +fields are the command's parameters, with Preview (Randomize Opacity's seed starts new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies. ```json {"name":"run_command","arguments":{"command":"addon.arrange.grid","params":{"columns":4,"gapX":12,"gapY":12}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 168c381233..55872ac361 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Symbols panel: Select All Unused, #4918) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Arrange Tools add-on: Randomize Opacity, #4925; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -1413,6 +1413,10 @@ dialogs, Preview and Cancel, Zoom to Selection) and `command_sweep`. Commands: ` A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the top-level selected objects wherever their visual bounds overlap or touch, chains included (A overlapping B and B overlapping C makes one group of three), only among objects of the same layer or group; objects that overlap nothing stay as they are, each new group takes its frontmost member's place in the stacking order, and the groups and the loose objects stay selected. One undo step; at most 20000 objects, compared by a sweep along x with union-find. Tests: `group_overlapping_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (chains, loners, stacking order, layers kept apart, visual bounds, no step when nothing overlaps, many objects), `group_overlapping_objects_runs_directly` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +## Arrange Tools add-on: Randomize Opacity (2026-11-01) + +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each top-level selected object (or each of `ids`) its own object opacity, picked at random and evenly between a minimum and a maximum percent (30 to 100 by default); a seed (0 by default; the dialog starts with a new one whenever the document has changed) repeats a result exactly. A group takes one opacity of its own and the objects inside keep theirs. One undo step; a minimum above the maximum, a percent outside 0 to 100 or a seed that is not a whole number is refused without a change. Tests: `randomize_opacity_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (range, one undo step, same and different seeds, defaults, `ids`, groups, bad params), `randomize_opacity_opens_its_dialog_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. + ## Path Precision Tools add-on: Divide into Dashes (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Divide into Dashes… cuts the selected paths into separate open paths along the curve (arc length, not straight distance): each `dash` long (0.01 to 1000000 pt, 10 by default) with `gap` between them (0 by default: the pieces touch); the gap pieces are left out unless Remove Gaps is off. With direct-selected segments (or anchors) only those runs are divided, the pattern running on across segments that follow one another, and the rest of such a path stays as pieces of its own. Fit to Corners and Ends gives every run between corners and ends a whole number of dashes, all stretched or squeezed alike so it starts and ends on a dash (a closed path without corners holds whole periods); otherwise the lengths are exact and each run's last piece is what is left. Every piece keeps the path's appearance and is selected; one undo step; at most 100000 pieces (more is refused). The dialog takes lengths in any unit and previews on the canvas. Tests: `dashes::tests` in `vectorcraft-pathops` (exact and fitted lengths, curves measured along them, picked segments on open and closed paths, the piece cap and bad patterns), `divide_into_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (gaps removed or kept, fitted lengths, the stroke kept, one undo step, selected segments only, bad params and too many pieces refused), `divide_into_dashes_opens_its_dialog_previews_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. @@ -1433,6 +1437,7 @@ Symbols area (#4938), from the public symbol documentation ([create and place sy | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Randomize Opacity (#4925); evidence added; scores unchanged. | | 2026-11-01 | minor | Symbols panel: Select All Unused (`symbol.unused`) shows the symbols nothing places selected, and Delete Symbol deletes them all, asked once, in one undo step (`symbol.delete {names}`, #4918); scores and hours unchanged | | 2026-11-01 | minor | Type core: Area Type Options › Text Flow (#4978): area type with several rows and columns fills them by columns (the default) or by rows, from the dialog's radio buttons or `text.areaOptions {flow}`; evidence updated; scores unchanged. | | 2026-11-01 | minor | Symbols: dynamic symbols (#4938): Symbol Options › Symbol Type, per-instance appearance for objects of a dynamic symbol's art that stays linked through redefinition, Break Link baking, Reset and Static dropping it; evidence added. Score unchanged at 87% (estimated), hours 5–9 → 4–8. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c1feab7e4b..bc788b8f0b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Blob Brush and Eraser show their tip's outline at the pointer, #4977) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Arrange Tools add-on: Randomize Opacity, #4925) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -334,6 +334,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `<name>_YYYY-MM-DD_HH-MM.<ext>` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › New Symbols from Layers makes a symbol of each layer's art named after the layer (the highlighted layers when two or more are, else all); Convert Layers to Symbols also replaces each layer's art with an instance in place; empty layers skipped, one undo step | done | #4927; `addon.document.symbolsFromLayers`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | @@ -389,6 +390,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Randomize Opacity (#4925); scores and estimates unchanged | | 2026-11-01 | minor | Blob Brush and Eraser: the tip's outline (size, angle, roundness, at the zoom) follows the pointer before and while painting, around a small centre dot, updating at once with `[` / `]` and Tool Options; precise cursors (Caps Lock) show only the crosshair (#4977); scores and estimates unchanged (estimated) | | 2026-11-01 | minor | Layers panel: an open blend lists its spine as a `<Path>` row below its key objects, and a click selects the blend so Direct Selection edits the spine (#4820); scores and estimates unchanged | | 2026-11-01 | minor | Pen with Cmd/Ctrl held: the lent Selection tool no longer scales the path being drawn by bounding-box handles the canvas hides while its end anchor is selected (a flat path did nothing under a resize pointer); a Cmd drag moves the path instead, and with Direct Selection moves anchors and segments, one undo step each (#4980); scores and estimates unchanged | From cd277d5d8410539855bf1684e1f2afb9ca35ecae Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 08:08:41 +0700 Subject: [PATCH 226/260] Fix #4917: Sort Objects sorts the selection by one attribute and applies that order to another Squashed from #5017 onto main. --- ROADMAP.md | 4 +- crates/engine/src/cmd/addons/arrange.rs | 148 +++++++++++++++++- crates/engine/src/cmd/addons/arrange/tests.rs | 146 +++++++++++++++++ crates/engine/tests/command_sweep.rs | 5 + crates/ui-egui/src/addons/arrange.rs | 37 ++++- crates/ui-egui/src/addons/arrange/tests.rs | 24 ++- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/i18n/bg.tsv | 12 ++ crates/ui-egui/src/i18n/bs.tsv | 12 ++ crates/ui-egui/src/i18n/ca.tsv | 12 ++ crates/ui-egui/src/i18n/cs.tsv | 12 ++ crates/ui-egui/src/i18n/da.tsv | 12 ++ crates/ui-egui/src/i18n/de.tsv | 12 ++ crates/ui-egui/src/i18n/el.tsv | 12 ++ crates/ui-egui/src/i18n/es.tsv | 12 ++ crates/ui-egui/src/i18n/fi.tsv | 12 ++ crates/ui-egui/src/i18n/fr.tsv | 12 ++ crates/ui-egui/src/i18n/hu.tsv | 12 ++ crates/ui-egui/src/i18n/id.tsv | 12 ++ crates/ui-egui/src/i18n/it.tsv | 12 ++ crates/ui-egui/src/i18n/ja.tsv | 12 ++ crates/ui-egui/src/i18n/ka.tsv | 12 ++ crates/ui-egui/src/i18n/ko.tsv | 12 ++ crates/ui-egui/src/i18n/nl.tsv | 12 ++ crates/ui-egui/src/i18n/pl.tsv | 12 ++ crates/ui-egui/src/i18n/pt-br.tsv | 12 ++ crates/ui-egui/src/i18n/ru.tsv | 12 ++ crates/ui-egui/src/i18n/sv.tsv | 12 ++ crates/ui-egui/src/i18n/tr.tsv | 12 ++ crates/ui-egui/src/i18n/uk.tsv | 12 ++ crates/ui-egui/src/i18n/vi.tsv | 12 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 12 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 12 ++ docs/mcp.md | 7 +- docs/target-app-parity.md | 7 +- docs/ui-parity.md | 4 +- 36 files changed, 680 insertions(+), 16 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 4c33d5d169..cbce1fbfaa 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -9,7 +9,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Arrange Tools add-on's Randomize Opacity; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Arrange Tools add-on's Sort Objects; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -130,6 +130,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). +- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<name>_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. @@ -210,6 +211,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| | 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Randomize Opacity (#4925); headline numbers unchanged. | +| 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Sort Objects (#4917); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Document Tools add-on's New Symbols from Layers (#4927); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Document Tools add-on's Save a Timestamped Copy (#4926); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for Divide into Dashes (Path Precision Tools add-on, #4950); headline numbers unchanged. | diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 0a7d168d06..9b11a71153 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -3,13 +3,15 @@ //! Replace with Top Object puts a copy of the topmost selected object in place of each of the //! others; and Set Size of Each gives every selected object an exact width and height. Places and //! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the -//! objects whose visual bounds overlap, and Randomize Opacity gives each selected object a random -//! opacity. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection (a -//! view command) are the UI's. +//! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random +//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in +//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection +//! (a view command) are the UI's. #[cfg(test)] mod tests; +use std::collections::HashMap; use std::sync::Arc; use serde_json::{Value, json}; @@ -31,8 +33,10 @@ const LIMIT: f64 = 1e6; const LEAST: f64 = 0.001; /// The most columns Arrange in Grid takes. const MAX_COLUMNS: u64 = 10_000; -/// The most objects Group Overlapping Objects looks at. +/// The most objects Group Overlapping Objects and Sort Objects look at. const MAX_OBJECTS: usize = 20_000; +/// The attributes Sort Objects sorts by and gives (`addon.arrange.sort`). +pub const SORT_KEYS: [&str; 7] = ["width", "height", "area", "x", "y", "opacity", "stacking"]; pub fn specs() -> Vec<CommandSpec> { vec![ @@ -90,6 +94,15 @@ pub fn specs() -> Vec<CommandSpec> { has_selection, randomize_opacity ), + cmd!( + "addon.arrange.sort", + "Sort Objects", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. A run that changes nothing makes no step → {count}", + has_multi, + sort + ), ] } @@ -393,3 +406,130 @@ fn randomize_opacity(s: &mut Session, p: &Value) -> Result<Value> { })?; Ok(json!({ "count": ids.len() })) } + +/// An object Sort Objects sorts: its layer or group, its place in it, its box as +/// `object.setBounds` measures it and its opacity (%). +struct Sorted { + id: NodeId, + parent: Option<NodeId>, + slot: usize, + b: OrientedBox, + opacity: f64, +} + +/// Attribute `key` (one of [`SORT_KEYS`]) of `o`, the `i`th of the objects in stacking order. +fn attribute(key: &str, o: &Sorted, i: usize) -> f64 { + let r = o.b.rect; + // The top-left corner where `object.setBounds` places it (reference point 0). + let corner = o.b.to_doc() * Point::new(r.x0, r.y0); + match key { + "width" => r.width(), + "height" => r.height(), + "area" => r.width() * r.height(), + "x" => corner.x, + "y" => corner.y, + "opacity" => o.opacity, + _ => i as f64, + } +} + +fn sort(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "addon.arrange.sort"; + let by = choice(p, C, "by", &SORT_KEYS)?.unwrap_or("area"); + let apply = choice(p, C, "apply", &SORT_KEYS)?.unwrap_or("stacking"); + let order = choice(p, C, "order", &["ascending", "descending", "random"])?.unwrap_or("ascending"); + let distribute = switch_or(p, "distribute", false, C)?; + let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); + let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let ids = checked_ids_or_selection(s, p, C)?; + if ids.len() > MAX_OBJECTS { + return Err(bad(C, "too many objects selected (at most 20000)")); + } + let d = &s.doc()?.doc; + // The objects in stacking order, from the back (their index paths, found in one walk). + let paths = d.index_paths(ids.iter().copied()); + let mut placed: Vec<(&Vec<usize>, NodeId)> = ids.iter().filter_map(|id| Some((paths.get(id)?, *id))).collect(); + placed.sort_by(|a, b| a.0.cmp(b.0)); + let items: Vec<Sorted> = placed + .into_iter() + .filter_map(|(path, id)| { + let (&slot, up) = path.split_last()?; + let parent = if up.is_empty() { None } else { Some(d.node_at(up)?.id) }; + Some(Sorted { id, parent, slot, b: s.transform_box(&[id])?, opacity: f64::from(d.node(id)?.opacity) * 100.0 }) + }) + .collect(); + let keys: Vec<f64> = items.iter().enumerate().map(|(i, o)| attribute(by, o, i)).collect(); + // The objects in sorted order; equal keys keep their stacking order. + let mut rank: Vec<usize> = (0..items.len()).collect(); + match order { + "random" => rng.shuffle(&mut rank), + "descending" => rank.sort_by(|a, b| keys[*b].total_cmp(&keys[*a])), + _ => rank.sort_by(|a, b| keys[*a].total_cmp(&keys[*b])), + } + let count = json!({ "count": items.len() }); + if apply == "stacking" { + // Each layer or group's objects take its objects' places, from the back, in sorted order. + let mut groups: HashMap<Option<NodeId>, Vec<usize>> = HashMap::new(); + for o in rank.iter().filter_map(|i| items.get(*i)) { + groups.entry(o.parent).or_default().push(o.slot); + } + if groups.values().all(|slots| slots.is_sorted()) { + return Ok(count); + } + s.edit("Sort Objects", |d, _| { + for (parent, from) in groups { + let ch = d.children_mut(parent)?; + let nodes: Vec<Arc<Node>> = from.iter().filter_map(|i| ch.get(*i).cloned()).collect(); + let mut to = from; + to.sort_unstable(); + for (slot, n) in to.into_iter().zip(nodes) { + if let Some(c) = ch.get_mut(slot) { + *c = n; + } + } + } + Ok(()) + })?; + return Ok(count); + } + // The values the objects get, smallest first: theirs, or evenly from the smallest to the largest. + let mut values: Vec<f64> = items.iter().enumerate().map(|(i, o)| attribute(apply, o, i)).collect(); + values.sort_by(f64::total_cmp); + if let (true, Some(&lo), Some(&hi)) = (distribute && values.len() > 1, values.first(), values.last()) { + let steps = (values.len() - 1) as f64; + values = (0..values.len()).map(|j| lo + (hi - lo) * j as f64 / steps).collect(); + } + let wanted: Vec<(&Sorted, f64)> = rank.iter().filter_map(|i| items.get(*i)).zip(values).collect(); + if apply == "opacity" { + if wanted.iter().all(|(o, v)| (o.opacity - v).abs() < 1e-6) { + return Ok(count); + } + s.edit("Sort Objects", |d, _| { + for (o, v) in &wanted { + if let Some(n) = d.node_mut(o.id) { + n.opacity = (v / 100.0) as f32; + } + } + Ok(()) + })?; + return Ok(count); + } + let mut xfs = Vec::with_capacity(wanted.len()); + for (o, v) in wanted { + let q = match apply { + "x" => json!({ "x": v, "reference": 0 }), + "y" => json!({ "y": v, "reference": 0 }), + "width" => json!({ "width": v, "strokes": strokes }), + "height" => json!({ "height": v, "strokes": strokes }), + // An area: both sides in proportion; an object without one keeps its size. + _ => { + let (w, h) = (o.b.rect.width(), o.b.rect.height()); + let k = if w * h > 1e-12 { (v / (w * h)).sqrt() } else { 1.0 }; + json!({ "width": w * k, "height": h * k, "strokes": strokes }) + } + }; + xfs.push((o.id, object_bounds_transform(s, &q, o.id)?)); + } + transform_each(s, "Sort Objects", strokes, &xfs)?; + Ok(count) +} diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index e19969f2e4..85191935b2 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -263,6 +263,7 @@ fn off_without_a_selection() { "addon.arrange.size", "addon.arrange.groupOverlapping", "addon.arrange.randomizeOpacity", + "addon.arrange.sort", ] { assert!(!enabled(&s, c), "{c}"); } @@ -416,3 +417,148 @@ fn randomize_opacity_refuses_bad_params() { let e = s.execute("addon.arrange.randomizeOpacity", &json!({"min": 80, "max": 20})).unwrap_err().to_string(); assert!(e.contains("`min` is greater than `max`"), "{e}"); } + +fn layer_order(s: &Session) -> Vec<NodeId> { + s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +/// Three squares: `a` 30 wide at x 0, `b` 10 wide at x 100, `c` 20 wide at x 200, all selected. +fn squares(s: &mut Session) -> (NodeId, NodeId, NodeId) { + let a = rect(s, 0.0, 0.0, 30.0, 30.0); + let b = rect(s, 100.0, 0.0, 10.0, 10.0); + let c = rect(s, 200.0, 0.0, 20.0, 20.0); + select(s, &[a, b, c]); + (a, b, c) +} + +#[test] +fn sort_by_area_lines_objects_up_along_x() { + let mut s = session(); + let (a, b, c) = squares(&mut s); + let n = steps(&s); + let r = s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "x"})).unwrap(); + assert_eq!(r["count"], json!(3)); + assert_eq!(steps(&s), n + 1, "one undo step"); + // Smallest first: b, c, a take the left edges 0, 100, 200; y stays. + assert!(near(bounds(&s, b), (0.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, b)); + assert!(near(bounds(&s, c), (100.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, c)); + assert!(near(bounds(&s, a), (200.0, 0.0, 30.0, 30.0)), "{:?}", bounds(&s, a)); + // Large to small: a, c, b. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "x", "order": "descending"})).unwrap(); + assert_eq!((bounds(&s, a).x0, bounds(&s, c).x0, bounds(&s, b).x0), (0.0, 100.0, 200.0)); + // Already in order: no step. + let n = steps(&s); + s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "x", "order": "descending"})).unwrap(); + assert_eq!(steps(&s), n); +} + +#[test] +fn sort_distributes_values_evenly() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 10.0, 50.0, 10.0, 50.0); + let c = rect(&mut s, 200.0, 0.0, 10.0, 20.0); + select(&mut s, &[a, b, c]); + // Left edges 0, 10, 200 step evenly: 0, 100, 200. + s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "x", "distribute": true})).unwrap(); + assert_eq!((bounds(&s, a).x0, bounds(&s, b).x0, bounds(&s, c).x0), (0.0, 100.0, 200.0)); + // Heights that step evenly with x (10 to 50), each about its centre. + s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "height", "distribute": true})).unwrap(); + assert!(near(bounds(&s, a), (0.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (100.0, 60.0, 10.0, 30.0)), "{:?}", bounds(&s, b)); + assert!(near(bounds(&s, c), (200.0, -15.0, 10.0, 50.0)), "{:?}", bounds(&s, c)); +} + +#[test] +fn sort_restacks_within_each_layer() { + let mut s = session(); + let (a, b, c) = squares(&mut s); + // Largest at the back. + s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "stacking", "order": "descending"})).unwrap(); + assert_eq!(layer_order(&s), [a, c, b]); + s.execute("addon.arrange.sort", &json!({})).unwrap(); + assert_eq!(layer_order(&s), [b, c, a], "by area, small to large, into the stacking order by default"); + // An object in another layer keeps its layer; the others trade places among themselves. + s.execute("layer.new", &json!({})).unwrap(); + let big = rect(&mut s, 0.0, 100.0, 50.0, 50.0); + select(&mut s, &[a, b, c, big]); + s.execute("addon.arrange.sort", &json!({"order": "descending"})).unwrap(); + assert_eq!(layer_order(&s), [a, c, b]); + let doc = &s.doc().unwrap().doc; + assert_ne!(doc.layer_of(big), doc.layer_of(a), "left in its own layer"); +} + +#[test] +fn sort_by_stacking_and_opacity() { + let mut s = session(); + let (a, b, c) = squares(&mut s); + // Back to front a, b, c; reversed: c, b, a take the left edges 0, 100, 200. + s.execute("addon.arrange.sort", &json!({"by": "stacking", "apply": "x", "order": "descending"})).unwrap(); + assert_eq!((bounds(&s, c).x0, bounds(&s, b).x0, bounds(&s, a).x0), (0.0, 100.0, 200.0)); + for (id, o) in [(a, 20), (b, 80), (c, 50)] { + s.execute("object.setProps", &json!({"ids": [id.0], "opacity": o})).unwrap(); + } + select(&mut s, &[a, b, c]); + let opacity = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().opacity; + // By x, large to small: a (x 200) gets the least opacity, then b, then c. + s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "opacity", "order": "descending"})).unwrap(); + assert_eq!((opacity(&s, a), opacity(&s, b), opacity(&s, c)), (0.2, 0.5, 0.8)); + // By opacity into the stacking order, large to small: the most opaque at the back. + s.execute("addon.arrange.sort", &json!({"by": "opacity", "order": "descending"})).unwrap(); + assert_eq!(layer_order(&s), [c, b, a]); +} + +#[test] +fn sort_by_area_into_areas_scales_in_proportion() { + let mut s = session(); + let (a, b, c) = squares(&mut s); + // Areas 900, 100, 400 by x: a (x 0) 100, b 500, c 900. + s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "area", "distribute": true})).unwrap(); + let side = |s: &Session, id| bounds(s, id).width(); + assert!((side(&s, a) - 10.0).abs() < 1e-6 && (side(&s, b) - 500f64.sqrt()).abs() < 1e-6 && (side(&s, c) - 30.0).abs() < 1e-6); + assert!((bounds(&s, b).height() - 500f64.sqrt()).abs() < 1e-6, "in proportion"); +} + +#[test] +fn sort_in_random_order_repeats_with_a_seed() { + let mut s = session(); + let ids: Vec<NodeId> = (0..12).map(|i| rect(&mut s, i as f64 * 10.0, 0.0, 5.0, 5.0)).collect(); + select(&mut s, &ids); + s.execute("addon.arrange.sort", &json!({"order": "random", "seed": 5})).unwrap(); + let first = layer_order(&s); + assert_ne!(first, ids, "shuffled"); + let mut sorted = first.clone(); + sorted.sort_by_key(|i| i.0); + assert_eq!(sorted, ids, "the same objects"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(layer_order(&s), ids); + s.execute("addon.arrange.sort", &json!({"order": "random", "seed": 5})).unwrap(); + assert_eq!(layer_order(&s), first, "the same seed, the same order"); +} + +#[test] +fn sort_takes_ids_and_refuses_bad_params() { + let mut s = session(); + let (a, b, c) = squares(&mut s); + select(&mut s, &[a]); + assert!(!enabled(&s, "addon.arrange.sort")); + s.execute("addon.arrange.sort", &json!({"ids": [b.0, a.0], "apply": "x"})).unwrap(); + assert_eq!((bounds(&s, b).x0, bounds(&s, a).x0, bounds(&s, c).x0), (0.0, 100.0, 200.0), "c is left alone"); + select(&mut s, &[a, b, c]); + refuses( + &mut s, + "addon.arrange.sort", + &[ + json!({"by": "color"}), + json!({"apply": 3}), + json!({"order": "up"}), + json!({"distribute": "yes"}), + json!({"seed": -1}), + json!({"seed": 0.5}), + json!({"scaleStrokes": 1}), + json!({"ids": "x"}), + json!({"ids": [999_999]}), + ], + ); +} diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 06046338fa..330fd45405 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -592,6 +592,11 @@ fn structured_junk() { ("addon.arrange.randomizeOpacity", json!({"min": 0, "max": 100, "seed": u64::MAX})), ("addon.arrange.randomizeOpacity", json!({"min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})), ("addon.arrange.randomizeOpacity", json!({"min": 100, "max": 0, "seed": 1e308, "ids": []})), + ("addon.arrange.sort", json!({"by": "area", "apply": "area", "distribute": true, "scaleStrokes": true})), + ("addon.arrange.sort", json!({"by": "stacking", "apply": "stacking", "order": "random", "seed": u64::MAX})), + ("addon.arrange.sort", json!({"by": "opacity", "apply": "y", "order": "descending", "ids": [u64::MAX]})), + ("addon.arrange.sort", json!({"by": "x", "apply": "opacity", "distribute": true, "seed": 1e308, "ids": []})), + ("addon.arrange.sort", json!({"by": "nope", "apply": null, "order": 3, "distribute": "x"})), ("addon.pathtools.divideDashes", json!({"dash": 1e-308, "gap": -1e308, "fit": "x"})), ("addon.pathtools.divideDashes", json!({"dash": 0.01, "gap": 1e6, "fit": true, "removeGaps": false})), ("addon.pathtools.divideDashes", json!({"dash": f64::MAX, "gap": [0], "removeGaps": null})), diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index f251aa69da..d024799f81 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -1,7 +1,7 @@ //! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of -//! Arrange in Grid, Replace with Top Object, Set Size of Each and Randomize Opacity, which preview -//! on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping Objects; and Zoom -//! to Selection ([`ZOOM`]), which fits the active view to the selection. +//! Arrange in Grid, Replace with Top Object, Set Size of Each, Randomize Opacity and Sort Objects, +//! which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping +//! Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection. use egui::Ui; use serde_json::{Value, json}; @@ -19,12 +19,14 @@ pub const GRID: &str = "arrangeGrid"; pub const REPLACE: &str = "arrangeReplace"; pub const SIZE: &str = "arrangeSize"; pub const OPACITY: &str = "arrangeOpacity"; +pub const SORT: &str = "arrangeSort"; /// Each dialog's kind, command and heading. -const DIALOGS: [(&str, &str, &str); 4] = [ +const DIALOGS: [(&str, &str, &str); 5] = [ (GRID, "addon.arrange.grid", "Arrange in Grid"), (REPLACE, "addon.arrange.replace", "Replace with Top Object"), (SIZE, "addon.arrange.size", "Set Size of Each"), (OPACITY, "addon.arrange.randomizeOpacity", "Randomize Opacity"), + (SORT, "addon.arrange.sort", "Sort Objects"), ]; /// The widths and heights Set Size of Each takes (pt), and the gaps Arrange in Grid takes. const SIZES: std::ops::RangeInclusive<f64> = 0.001..=1e6; @@ -44,6 +46,7 @@ pub fn menu() -> Vec<Item> { Item::Cmd("Set Size of Each…", "addon.arrange.size", Value::Null), Item::Cmd("Group Overlapping Objects", "addon.arrange.groupOverlapping", json!({})), Item::Cmd("Randomize Opacity…", "addon.arrange.randomizeOpacity", Value::Null), + Item::Cmd("Sort Objects…", "addon.arrange.sort", Value::Null), Item::Sep, Item::Cmd("Zoom to Selection", ZOOM, json!({})), ] @@ -64,6 +67,11 @@ pub(crate) fn dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static str, Va REPLACE => json!({ "fit": "keep", "keep": false, "scaleStrokes": strokes }), // A new seed each time the document has changed, so running it again varies the result. OPACITY => json!({ "min": 30, "max": 100, "seed": st.revision % SEEDS }), + // The random order's seed (not shown): new whenever the document has changed, so each run + // shuffles anew while Preview and OK agree. + SORT => json!({ + "by": "area", "apply": "stacking", "order": "ascending", "distribute": false, "seed": st.revision % SEEDS, "scaleStrokes": strokes, + }), // The first selected object's size, as the command measures it (a side it lacks: the least). _ => { let b = st.selection.objects.first().and_then(|id| app.session.transform_box(&[*id])).map_or((100.0, 100.0), |b| { @@ -151,6 +159,27 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { } }); } + SORT => { + let attributes = [ + ("width", "Width"), + ("height", "Height"), + ("area", "Area"), + ("x", "X Position"), + ("y", "Y Position"), + ("opacity", "Opacity"), + ("stacking", "Stacking Order"), + ]; + form::choice(ui, d, "by", tl!("Sort By:"), widths, &attributes); + form::choice(ui, d, "apply", tl!("Apply To:"), widths, &attributes); + let orders = [("ascending", "Small to Large"), ("descending", "Large to Small"), ("random", "Random")]; + form::choice(ui, d, "order", tl!("Order:"), widths, &orders); + // Stacking order only trades places; only sizes scale strokes. + let apply = d.str("apply"); + ui.add_enabled_ui(apply != "stacking", |ui| form::check(ui, d, "distribute", tl!("Distribute Evenly"))); + ui.add_enabled_ui(matches!(apply.as_str(), "width" | "height" | "area"), |ui| { + form::check(ui, d, "scaleStrokes", tl!("Scale Strokes & Effects")); + }); + } _ => { egui::Grid::new("arrange-size").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { for (side, tick, label) in [("width", "__width", tl!("Width:")), ("height", "__height", tl!("Height:"))] { diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 6aa8646738..40e5eb0f8a 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -2,7 +2,7 @@ use serde_json::json; use vectorcraft_doc::NodeId; use vectorcraft_engine::Session; -use super::{GRID, OPACITY, REPLACE, SIZE, ZOOM}; +use super::{GRID, OPACITY, REPLACE, SIZE, SORT, ZOOM}; use crate::tests_labels::painted_text; use crate::{VectorcraftApp, menus}; @@ -42,6 +42,7 @@ fn the_plugins_submenu_lists_the_tools() { ("Set Size of Each…", "addon.arrange.size"), ("Group Overlapping Objects", "addon.arrange.groupOverlapping"), ("Randomize Opacity…", "addon.arrange.randomizeOpacity"), + ("Sort Objects…", "addon.arrange.sort"), ("Zoom to Selection", ZOOM), ] { assert_eq!(under(label).and_then(|e| e.command.as_deref()), Some(id), "{label}"); @@ -168,3 +169,24 @@ fn randomize_opacity_opens_its_dialog_and_runs_on_ok() { assert!((0.4..=0.6).contains(&doc.node(id).unwrap().opacity), "{id:?}"); } } + +#[test] +fn sort_objects_opens_its_dialog_and_runs_on_ok() { + let (mut app, a, b) = app(); + click(&mut app, "Sort Objects…"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(SORT)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Sort Objects", "Sort By:", "Apply To:", "Order:", "Area", "Stacking Order", "Small to Large", "Distribute Evenly", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((&d.fields["by"], &d.fields["apply"], &d.fields["order"]), (&json!("area"), &json!("stacking"), &json!("ascending"))); + // Large to small along x: b (the larger) takes the left edge 0, a the left edge 100. + d.fields.insert("apply".into(), json!("x")); + d.fields.insert("order".into(), json!("descending")); + let n = app.session.doc().unwrap().history.undo.len(); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1); + assert_eq!((bounds(&app, b).x0, bounds(&app, a).x0), (0.0, 100.0)); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 371c02695d..b0210026a9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -400,7 +400,7 @@ registry! { RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC, PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC, DivideDashes: [crate::addons::pathtools::dashes::KIND] => crate::addons::pathtools::dashes::SPEC, - ArrangeTools: [crate::addons::arrange::GRID, crate::addons::arrange::REPLACE, crate::addons::arrange::SIZE, crate::addons::arrange::OPACITY] => crate::addons::arrange::SPEC, + ArrangeTools: [crate::addons::arrange::GRID, crate::addons::arrange::REPLACE, crate::addons::arrange::SIZE, crate::addons::arrange::OPACITY, crate::addons::arrange::SORT] => crate::addons::arrange::SPEC, ShortcutImport: [shortcut_import::KIND] => DialogSpec::window(shortcut_import::show, shortcut_import::confirm), } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 01896f2ed9..f2389f4b81 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6006,3 +6006,15 @@ breakText Glyphs Глифи Maximum: Максимум: Seed: Начално число: @msg `min` is greater than `max` `min` е по-голямо от `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Сортиране на обекти… + Sort Objects Сортиране на обекти + Sort By: Сортиране по: + Apply To: Прилагане към: + Area Площ + X Position Позиция по X + Y Position Позиция по Y + Stacking Order Ред на подреждане + Small to Large От малко към голямо + Large to Small От голямо към малко + Distribute Evenly Равномерно разпределение diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index e32201e97e..2e9b5fd554 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6039,3 +6039,15 @@ shape Open Otvoren Maximum: Maksimum: Seed: Početna vrijednost: @msg `min` is greater than `max` `min` je veće od `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Sortiraj objekte… + Sort Objects Sortiraj objekte + Sort By: Sortiraj po: + Apply To: Primijeni na: + Area Površina + X Position Položaj X + Y Position Položaj Y + Stacking Order Redoslijed slaganja + Small to Large Od manjeg prema većem + Large to Small Od većeg prema manjem + Distribute Evenly Rasporedi ravnomjerno diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e5ec3feb60..0c2238de16 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6112,3 +6112,15 @@ breakText Glyphs Glifs Maximum: Màxim: Seed: Llavor: @msg `min` is greater than `max` `min` és més gran que `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Ordena els objectes… + Sort Objects Ordena els objectes + Sort By: Ordena per: + Apply To: Aplica a: + Area Àrea + X Position Posició X + Y Position Posició Y + Stacking Order Ordre d’apilament + Small to Large De petit a gran + Large to Small De gran a petit + Distribute Evenly Distribueix uniformement diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 0efefa092b..d8d77feefb 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6122,3 +6122,15 @@ breakText Glyphs Glyfy Maximum: Maximum: Seed: Počáteční hodnota: @msg `min` is greater than `max` `min` je větší než `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Seřadit objekty… + Sort Objects Seřadit objekty + Sort By: Seřadit podle: + Apply To: Použít na: + Area Plocha + X Position Poloha X + Y Position Poloha Y + Stacking Order Pořadí vrstvení + Small to Large Od nejmenšího po největší + Large to Small Od největšího po nejmenší + Distribute Evenly Rozmístit rovnoměrně diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index f4d16eef28..7a1740223a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6021,3 +6021,15 @@ breakText Glyphs Glyffer Maximum: Maksimum: Seed: Startværdi: @msg `min` is greater than `max` `min` er større end `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Sortér objekter… + Sort Objects Sortér objekter + Sort By: Sortér efter: + Apply To: Anvend på: + Area Areal + X Position X-position + Y Position Y-position + Stacking Order Stablingsrækkefølge + Small to Large Fra lille til stor + Large to Small Fra stor til lille + Distribute Evenly Fordel jævnt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 18ea74459d..48e587d88c 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5707,3 +5707,15 @@ breakText Glyphs Glyphen Maximum: Maximum: Seed: Startwert: @msg `min` is greater than `max` `min` ist größer als `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Objekte sortieren… + Sort Objects Objekte sortieren + Sort By: Sortieren nach: + Apply To: Anwenden auf: + Area Fläche + X Position X-Position + Y Position Y-Position + Stacking Order Stapelreihenfolge + Small to Large Von klein nach groß + Large to Small Von groß nach klein + Distribute Evenly Gleichmäßig verteilen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 15c008eb8e..bec866697a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6074,3 +6074,15 @@ breakText Glyphs Γλύφοι Maximum: Μέγιστο: Seed: Αρχική τιμή: @msg `min` is greater than `max` Το `min` είναι μεγαλύτερο από το `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Ταξινόμηση αντικειμένων… + Sort Objects Ταξινόμηση αντικειμένων + Sort By: Ταξινόμηση κατά: + Apply To: Εφαρμογή σε: + Area Εμβαδόν + X Position Θέση X + Y Position Θέση Y + Stacking Order Σειρά στοίβαξης + Small to Large Από μικρό σε μεγάλο + Large to Small Από μεγάλο σε μικρό + Distribute Evenly Ομοιόμορφη κατανομή diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f69b7bec9c..d5a6640298 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6064,3 +6064,15 @@ breakText Glyphs Glifos Maximum: Máximo: Seed: Semilla: @msg `min` is greater than `max` `min` es mayor que `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Ordenar objetos… + Sort Objects Ordenar objetos + Sort By: Ordenar por: + Apply To: Aplicar a: + Area Área + X Position Posición X + Y Position Posición Y + Stacking Order Orden de apilamiento + Small to Large De menor a mayor + Large to Small De mayor a menor + Distribute Evenly Distribuir uniformemente diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index fc76393f68..f1badd4853 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6152,3 +6152,15 @@ breakText Glyphs Merkit Maximum: Suurin: Seed: Siemen: @msg `min` is greater than `max` `min` on suurempi kuin `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Lajittele objektit… + Sort Objects Lajittele objektit + Sort By: Lajitteluperuste: + Apply To: Käytä kohteeseen: + Area Pinta-ala + X Position X-sijainti + Y Position Y-sijainti + Stacking Order Pinoamisjärjestys + Small to Large Pienestä suureen + Large to Small Suuresta pieneen + Distribute Evenly Jaa tasaisesti diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 24a3a59ad9..be6e4d1ae0 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6119,3 +6119,15 @@ breakText Glyphs Glyphes Maximum: Maximum : Seed: Graine : @msg `min` is greater than `max` `min` est supérieur à `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Trier les objets… + Sort Objects Trier les objets + Sort By: Trier par : + Apply To: Appliquer à : + Area Surface + X Position Position X + Y Position Position Y + Stacking Order Ordre d’empilement + Small to Large Du plus petit au plus grand + Large to Small Du plus grand au plus petit + Distribute Evenly Répartir uniformément diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 29305857e7..7243f3dee4 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6108,3 +6108,15 @@ breakText Glyphs Glifák Maximum: Maximum: Seed: Kezdőérték: @msg `min` is greater than `max` `min` nagyobb, mint `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Objektumok rendezése… + Sort Objects Objektumok rendezése + Sort By: Rendezés alapja: + Apply To: Alkalmazás erre: + Area Terület + X Position X pozíció + Y Position Y pozíció + Stacking Order Halmozási sorrend + Small to Large Kicsitől a nagyig + Large to Small Nagytól a kicsiig + Distribute Evenly Egyenletes elosztás diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index b682c757f9..84e58c69be 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6021,3 +6021,15 @@ breakText Glyphs Glif Maximum: Maksimum: Seed: Benih: @msg `min` is greater than `max` `min` lebih besar dari `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Urutkan objek… + Sort Objects Urutkan objek + Sort By: Urutkan menurut: + Apply To: Terapkan ke: + Area Luas + X Position Posisi X + Y Position Posisi Y + Stacking Order Urutan tumpukan + Small to Large Kecil ke besar + Large to Small Besar ke kecil + Distribute Evenly Distribusikan merata diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 74fcfb60c7..6845ed74e1 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5741,3 +5741,15 @@ breakText Glyphs Glifi Maximum: Massimo: Seed: Seme: @msg `min` is greater than `max` `min` è maggiore di `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Ordina oggetti… + Sort Objects Ordina oggetti + Sort By: Ordina per: + Apply To: Applica a: + Area Area + X Position Posizione X + Y Position Posizione Y + Stacking Order Ordine di sovrapposizione + Small to Large Dal più piccolo al più grande + Large to Small Dal più grande al più piccolo + Distribute Evenly Distribuisci uniformemente diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 69ee5fd860..cfe312e9e8 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5808,3 +5808,15 @@ breakText Glyphs 字形 Maximum: 最大: Seed: シード: @msg `min` is greater than `max` `min` が `max` より大きくなっています +# Arrange Tools add-on: Sort Objects. + Sort Objects… オブジェクトを並べ替え… + Sort Objects オブジェクトを並べ替え + Sort By: 並べ替えの基準: + Apply To: 適用先: + Area 面積 + X Position X 位置 + Y Position Y 位置 + Stacking Order 重ね順 + Small to Large 小さい順 + Large to Small 大きい順 + Distribute Evenly 均等に分布 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 07fc51fb93..d6f951f6eb 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6111,3 +6111,15 @@ breakText Glyphs გლიფები Maximum: მაქსიმუმი: Seed: საწყისი რიცხვი: @msg `min` is greater than `max` `min` მეტია, ვიდრე `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… ობიექტების დალაგება… + Sort Objects ობიექტების დალაგება + Sort By: დალაგება: + Apply To: გამოყენება: + Area ფართობი + X Position X პოზიცია + Y Position Y პოზიცია + Stacking Order დაწყობის რიგი + Small to Large პატარიდან დიდისკენ + Large to Small დიდიდან პატარისკენ + Distribute Evenly თანაბრად განაწილება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 022d194942..2df53a0989 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5704,3 +5704,15 @@ breakText Glyphs 글리프 Maximum: 최대: Seed: 시드: @msg `min` is greater than `max` `min`이(가) `max`보다 큽니다 +# Arrange Tools add-on: Sort Objects. + Sort Objects… 개체 정렬… + Sort Objects 개체 정렬 + Sort By: 정렬 기준: + Apply To: 적용 대상: + Area 면적 + X Position X 위치 + Y Position Y 위치 + Stacking Order 쌓는 순서 + Small to Large 작은 것부터 + Large to Small 큰 것부터 + Distribute Evenly 균등 분포 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a1ace51902..0591d4042a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6065,3 +6065,15 @@ breakText Glyphs Glyphs Maximum: Maximum: Seed: Startwaarde: @msg `min` is greater than `max` `min` is groter dan `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Objecten sorteren… + Sort Objects Objecten sorteren + Sort By: Sorteren op: + Apply To: Toepassen op: + Area Oppervlakte + X Position X-positie + Y Position Y-positie + Stacking Order Stapelvolgorde + Small to Large Van klein naar groot + Large to Small Van groot naar klein + Distribute Evenly Gelijkmatig verdelen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index fc4cb57487..6acc18ccfb 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5977,3 +5977,15 @@ breakText Glyphs Glify Maximum: Maksimum: Seed: Ziarno: @msg `min` is greater than `max` `min` jest większe niż `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Sortuj obiekty… + Sort Objects Sortuj obiekty + Sort By: Sortuj według: + Apply To: Zastosuj do: + Area Pole + X Position Położenie X + Y Position Położenie Y + Stacking Order Kolejność ułożenia + Small to Large Od najmniejszego do największego + Large to Small Od największego do najmniejszego + Distribute Evenly Rozmieść równomiernie diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index bf70bd2fdd..f55b23cf29 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6196,3 +6196,15 @@ swatch Yellow Green Verde-amarelado Maximum: Máximo: Seed: Semente: @msg `min` is greater than `max` `min` é maior que `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Classificar objetos… + Sort Objects Classificar objetos + Sort By: Classificar por: + Apply To: Aplicar a: + Area Área + X Position Posição X + Y Position Posição Y + Stacking Order Ordem de empilhamento + Small to Large Do menor para o maior + Large to Small Do maior para o menor + Distribute Evenly Distribuir uniformemente diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 566cd78a22..038c380a3f 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6099,3 +6099,15 @@ breakText Glyphs Глифы Maximum: Максимум: Seed: Начальное число: @msg `min` is greater than `max` `min` больше, чем `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Сортировать объекты… + Sort Objects Сортировать объекты + Sort By: Сортировать по: + Apply To: Применить к: + Area Площадь + X Position Положение по X + Y Position Положение по Y + Stacking Order Порядок наложения + Small to Large От меньшего к большему + Large to Small От большего к меньшему + Distribute Evenly Распределить равномерно diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e93c877feb..91c94e58e2 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6174,3 +6174,15 @@ breakText Glyphs Glyfer Maximum: Maximum: Seed: Startvärde: @msg `min` is greater than `max` `min` är större än `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Sortera objekt… + Sort Objects Sortera objekt + Sort By: Sortera efter: + Apply To: Tillämpa på: + Area Area + X Position X-position + Y Position Y-position + Stacking Order Staplingsordning + Small to Large Från liten till stor + Large to Small Från stor till liten + Distribute Evenly Fördela jämnt diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9fdffe5446..43682accab 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6079,3 +6079,15 @@ breakText Glyphs Glifler Maximum: En Çok: Seed: Başlangıç Değeri: @msg `min` is greater than `max` `min`, `max` değerinden büyük +# Arrange Tools add-on: Sort Objects. + Sort Objects… Nesneleri Sırala… + Sort Objects Nesneleri Sırala + Sort By: Sıralama Ölçütü: + Apply To: Uygulanacak Değer: + Area Alan + X Position X Konumu + Y Position Y Konumu + Stacking Order İstifleme Sırası + Small to Large Küçükten Büyüğe + Large to Small Büyükten Küçüğe + Distribute Evenly Eşit Dağıt diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index f0fed9fb4e..d6610c36b2 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5721,3 +5721,15 @@ breakText Glyphs Гліфи Maximum: Максимум: Seed: Початкове число: @msg `min` is greater than `max` `min` більше за `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Сортувати об’єкти… + Sort Objects Сортувати об’єкти + Sort By: Сортувати за: + Apply To: Застосувати до: + Area Площа + X Position Положення за X + Y Position Положення за Y + Stacking Order Порядок накладання + Small to Large Від меншого до більшого + Large to Small Від більшого до меншого + Distribute Evenly Розподілити рівномірно diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 7cb29ce4f9..5315376b90 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5724,3 +5724,15 @@ breakText Glyphs Glyph Maximum: Tối đa: Seed: Giá trị khởi đầu: @msg `min` is greater than `max` `min` lớn hơn `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… Sắp xếp đối tượng… + Sort Objects Sắp xếp đối tượng + Sort By: Sắp xếp theo: + Apply To: Áp dụng cho: + Area Diện tích + X Position Vị trí X + Y Position Vị trí Y + Stacking Order Thứ tự xếp chồng + Small to Large Từ nhỏ đến lớn + Large to Small Từ lớn đến nhỏ + Distribute Evenly Phân bố đều diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b160639b04..156b250848 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5964,3 +5964,15 @@ breakText Glyphs 字形 Maximum: 最大值: Seed: 种子: @msg `min` is greater than `max` `min` 大于 `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… 排序对象… + Sort Objects 排序对象 + Sort By: 排序依据: + Apply To: 应用于: + Area 面积 + X Position X 位置 + Y Position Y 位置 + Stacking Order 堆叠顺序 + Small to Large 从小到大 + Large to Small 从大到小 + Distribute Evenly 均匀分布 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index aefdbb3665..33406bd06c 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5761,3 +5761,15 @@ breakText Glyphs 字符 Maximum: 最大值: Seed: 種子: @msg `min` is greater than `max` `min` 大於 `max` +# Arrange Tools add-on: Sort Objects. + Sort Objects… 排序物件… + Sort Objects 排序物件 + Sort By: 排序依據: + Apply To: 套用至: + Area 面積 + X Position X 位置 + Y Position Y 位置 + Stacking Order 堆疊順序 + Small to Large 從小到大 + Large to Small 從大到小 + Distribute Evenly 均勻分佈 diff --git a/docs/mcp.md b/docs/mcp.md index 2a8210444a..e95d5d1826 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6342,12 +6342,13 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. → `{count}` | +| `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, -and fails with nothing selected. Arrange in Grid…, Replace with Top Object…, Set Size of Each… and Randomize Opacity… open dialogs -(`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace`, `arrangeSize` and `arrangeOpacity`) whose -fields are the command's parameters, with Preview (Randomize Opacity's seed starts new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies. +and fails with nothing selected. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs +(`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace`, `arrangeSize`, `arrangeOpacity` and `arrangeSort`) whose +fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies. ```json {"name":"run_command","arguments":{"command":"addon.arrange.grid","params":{"columns":4,"gapX":12,"gapY":12}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 55872ac361..231426c8e9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Arrange Tools add-on: Randomize Opacity, #4925; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Arrange Tools add-on: Sort Objects, #4917; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -1417,6 +1417,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each top-level selected object (or each of `ids`) its own object opacity, picked at random and evenly between a minimum and a maximum percent (30 to 100 by default); a seed (0 by default; the dialog starts with a new one whenever the document has changed) repeats a result exactly. A group takes one opacity of its own and the objects inside keep theirs. One undo step; a minimum above the maximum, a percent outside 0 to 100 or a seed that is not a whole number is refused without a change. Tests: `randomize_opacity_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (range, one undo step, same and different seeds, defaults, `ids`, groups, bad params), `randomize_opacity_opens_its_dialog_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +## Arrange Tools add-on: Sort Objects (2026-11-01) + +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Sort Objects… sorts the top-level selected objects (or `ids`, at most 20000) by one attribute (width, height, area, x or y position, opacity or stacking order; small to large, large to small, or a random order from a seed) and gives them another in that order, the first the smallest value: the objects trade the values they have, or with Distribute Evenly the values step evenly from the smallest to the largest. Lining objects up left to right by size, restacking them so the largest is at the back, or giving them heights that step with their x position are each one run. Sizes and places are measured and set as `object.setBounds` measures them (Use Preview Bounds); a width, height or area changes about each object's centre (an area in proportion), and stacking order trades places only among objects of the same layer or group. One undo step; no step when nothing changes. Tests: `sort_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each attribute sorted by and applied, both directions, distribute, layers kept apart, the seeded random order, `ids`, no step when in order, bad params), `sort_objects_opens_its_dialog_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. + ## Path Precision Tools add-on: Divide into Dashes (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Divide into Dashes… cuts the selected paths into separate open paths along the curve (arc length, not straight distance): each `dash` long (0.01 to 1000000 pt, 10 by default) with `gap` between them (0 by default: the pieces touch); the gap pieces are left out unless Remove Gaps is off. With direct-selected segments (or anchors) only those runs are divided, the pattern running on across segments that follow one another, and the rest of such a path stays as pieces of its own. Fit to Corners and Ends gives every run between corners and ends a whole number of dashes, all stretched or squeezed alike so it starts and ends on a dash (a closed path without corners holds whole periods); otherwise the lengths are exact and each run's last piece is what is left. Every piece keeps the path's appearance and is selected; one undo step; at most 100000 pieces (more is refused). The dialog takes lengths in any unit and previews on the canvas. Tests: `dashes::tests` in `vectorcraft-pathops` (exact and fitted lengths, curves measured along them, picked segments on open and closed paths, the piece cap and bad patterns), `divide_into_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (gaps removed or kept, fitted lengths, the stroke kept, one undo step, selected segments only, bad params and too many pieces refused), `divide_into_dashes_opens_its_dialog_previews_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. @@ -1438,6 +1442,7 @@ Symbols area (#4938), from the public symbol documentation ([create and place sy | Date | Change | Summary | |---|---|---| | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Randomize Opacity (#4925); evidence added; scores unchanged. | +| 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Sort Objects (#4917); evidence added; scores unchanged. | | 2026-11-01 | minor | Symbols panel: Select All Unused (`symbol.unused`) shows the symbols nothing places selected, and Delete Symbol deletes them all, asked once, in one undo step (`symbol.delete {names}`, #4918); scores and hours unchanged | | 2026-11-01 | minor | Type core: Area Type Options › Text Flow (#4978): area type with several rows and columns fills them by columns (the default) or by rows, from the dialog's radio buttons or `text.areaOptions {flow}`; evidence updated; scores unchanged. | | 2026-11-01 | minor | Symbols: dynamic symbols (#4938): Symbol Options › Symbol Type, per-instance appearance for objects of a dynamic symbol's art that stays linked through redefinition, Break Link baking, Reset and Static dropping it; evidence added. Score unchanged at 87% (estimated), hours 5–9 → 4–8. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index bc788b8f0b..6dc32fc855 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Arrange Tools add-on: Randomize Opacity, #4925) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Arrange Tools add-on: Sort Objects, #4917) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -335,6 +335,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `<name>_YYYY-MM-DD_HH-MM.<ext>` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › New Symbols from Layers makes a symbol of each layer's art named after the layer (the highlighted layers when two or more are, else all); Convert Layers to Symbols also replaces each layer's art with an instance in place; empty layers skipped, one undo step | done | #4927; `addon.document.symbolsFromLayers`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | @@ -391,6 +392,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Randomize Opacity (#4925); scores and estimates unchanged | +| 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Sort Objects (#4917); scores and estimates unchanged | | 2026-11-01 | minor | Blob Brush and Eraser: the tip's outline (size, angle, roundness, at the zoom) follows the pointer before and while painting, around a small centre dot, updating at once with `[` / `]` and Tool Options; precise cursors (Caps Lock) show only the crosshair (#4977); scores and estimates unchanged (estimated) | | 2026-11-01 | minor | Layers panel: an open blend lists its spine as a `<Path>` row below its key objects, and a click selects the blend so Direct Selection edits the spine (#4820); scores and estimates unchanged | | 2026-11-01 | minor | Pen with Cmd/Ctrl held: the lent Selection tool no longer scales the path being drawn by bounding-box handles the canvas hides while its end anchor is selected (a flat path did nothing under a resize pointer); a Cmd drag moves the path instead, and with Direct Selection moves anchors and segments, one undo step each (#4980); scores and estimates unchanged | From 6b4ced2b962b1fac4e3c4a98ad2c37468c5042dd Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 18:03:19 -0700 Subject: [PATCH 227/260] Tests: the backtick menu test passes on macOS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit menus_and_tooltips_show_the_backtick_key_as_it_types put Edit › Clear on Cmd+~. craft-keymap reserves Cmd+` on macOS, so the override is refused there and the menu kept Delete. The test now uses Alt+~, which no platform reserves. --- crates/ui-egui/src/shortcut_editor.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index c048421c3d..f1d5cabb0d 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1225,17 +1225,18 @@ mod tests { #[test] fn menus_and_tooltips_show_the_backtick_key_as_it_types() { let mut ui = UiState::default(); - crate::keymap::set_override(&mut ui.shortcut_overrides, "edit.clear", "Cmd+~"); + // Not Cmd+~: macOS reserves it, so the override would leave Edit › Clear on Delete there. + crate::keymap::set_override(&mut ui.shortcut_overrides, "edit.clear", "Alt+~"); crate::keymap::set_override(&mut ui.shortcut_overrides, "tool:measure", "~"); sync(&ui); let measure = vectorcraft_tools::tool_info("measure").unwrap(); let press = |key| egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: Modifiers::NONE }; let clear = || menus::shown_shortcut(menus::shortcut_of("edit.clear").unwrap()); note_backtick_text(&[press(Key::Backtick), egui::Event::Text("`".into())]); - assert_eq!(clear(), menus::pretty_shortcut("Cmd+~")); + assert_eq!(clear(), menus::pretty_shortcut("Alt+~")); assert!(crate::toolbar::tip(measure).ends_with("(~)")); note_backtick_text(&[press(Key::Backtick), egui::Event::Text("\"".into())]); - assert_eq!(clear(), menus::pretty_shortcut("Cmd+\"")); + assert_eq!(clear(), menus::pretty_shortcut("Alt+\"")); assert!(crate::toolbar::tip(measure).ends_with("(\")"), "{}", crate::toolbar::tip(measure)); assert_eq!(menus::shown_shortcut("Shift+~"), menus::pretty_shortcut("Shift+~")); sync(&UiState::default()); From 2f26d4012b4cc00e5729370f9827a10eaa7c7eec Mon Sep 17 00:00:00 2001 From: FredApps <FredApps@users.noreply.github.com> Date: Sun, 1 Nov 2026 00:01:23 +0100 Subject: [PATCH 228/260] ci: i18n report without a rebuild; PR print runs stop saving caches - xtask ci: the i18n report selects the whole workspace as the test stage did. With `-p vectorcraft-ui-egui` alone cargo resolved features differently and recompiled for about 3.5 minutes. `cargo xtask i18n-report` on its own still builds only that crate. - print.yml: only main saves the desktop-print cache. Each PR saved its own 1.3 GB cache that only that PR can read (6.3 GB across five PRs), pushing the repository past its 10 GB limit and evicting caches main's gate restores. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .github/workflows/print.yml | 4 ++++ xtask/src/main.rs | 11 ++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/.github/workflows/print.yml b/.github/workflows/print.yml index 400a819442..b805725f28 100644 --- a/.github/workflows/print.yml +++ b/.github/workflows/print.yml @@ -26,9 +26,13 @@ jobs: with: toolchain: stable components: clippy + # Pull requests restore but never save: a PR's cache (about 1.3 GB) is visible only to that + # PR, and with the repository at its 10 GB limit each one evicted caches main's gate uses. + # A manual run on main seeds the cache every PR can restore. - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: key: desktop-print + save-if: ${{ github.ref == 'refs/heads/main' }} - run: cargo clippy --locked -p vectorcraft --all-targets -- -D warnings - run: cargo test --locked -p vectorcraft - name: Check pending submission and queue refusal feedback diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 0516321abc..efb80daa7f 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -294,7 +294,7 @@ fn cmd_ci() -> Result<(), String> { ("assets", Box::new(|| assets::run(&root()))), ("brands", Box::new(|| brands::run(&root()))), ("cursors", Box::new(|| cursors::run(&root()))), - ("i18n-report", Box::new(cmd_i18n_report)), + ("i18n-report", Box::new(cmd_ci_i18n_report)), ("layers", Box::new(cmd_layers)), ("wasm", Box::new(cmd_wasm)), ]; @@ -349,3 +349,12 @@ fn cmd_i18n_report() -> Result<(), String> { c.args(["test", "-p", "vectorcraft-ui-egui", "--lib", "--", "i18n::tests::untranslated_report", "--exact", "--nocapture"]); run(c, "cargo test -p vectorcraft-ui-egui --lib -- i18n::tests::untranslated_report --exact --nocapture") } + +/// [`cmd_i18n_report`] in `ci`, selecting the whole workspace as the test stage did: with +/// `-p vectorcraft-ui-egui` alone cargo resolves features differently and recompiled for about +/// 3.5 minutes. Every other lib test binary runs with no test matching the filter. +fn cmd_ci_i18n_report() -> Result<(), String> { + let mut c = cargo(); + c.args(["test", "--workspace", "--lib", "--quiet", "--", "i18n::tests::untranslated_report", "--exact", "--nocapture"]); + run(c, "cargo test --workspace --lib --quiet -- i18n::tests::untranslated_report --exact --nocapture") +} From 123e770e41ec6b3d4cc061d829cd4a8e2e71afe2 Mon Sep 17 00:00:00 2001 From: FredApps <FredApps@users.noreply.github.com> Date: Sun, 1 Nov 2026 00:17:40 +0100 Subject: [PATCH 229/260] ci(xtask): i18n report selects the test run's targets too Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> The test run builds --lib --bins --tests; a binary target's dependencies (the desktop app's eframe features) could still resolve differently under --lib alone. Match the selection exactly, and drop --quiet so a rebuild would show in the log. --- xtask/src/main.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index efb80daa7f..de6ff58154 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -350,11 +350,12 @@ fn cmd_i18n_report() -> Result<(), String> { run(c, "cargo test -p vectorcraft-ui-egui --lib -- i18n::tests::untranslated_report --exact --nocapture") } -/// [`cmd_i18n_report`] in `ci`, selecting the whole workspace as the test stage did: with -/// `-p vectorcraft-ui-egui` alone cargo resolves features differently and recompiled for about -/// 3.5 minutes. Every other lib test binary runs with no test matching the filter. +/// [`cmd_i18n_report`] in `ci`, selecting the packages and targets the test stage did so it +/// reuses that build: with `-p vectorcraft-ui-egui --lib` alone cargo resolves features +/// differently and recompiled for about 3.5 minutes. Every other test binary runs with no test +/// matching the filter. fn cmd_ci_i18n_report() -> Result<(), String> { let mut c = cargo(); - c.args(["test", "--workspace", "--lib", "--quiet", "--", "i18n::tests::untranslated_report", "--exact", "--nocapture"]); - run(c, "cargo test --workspace --lib --quiet -- i18n::tests::untranslated_report --exact --nocapture") + c.args(["test", "--workspace", "--lib", "--bins", "--tests", "--", "i18n::tests::untranslated_report", "--exact", "--nocapture"]); + run(c, "cargo test --workspace --lib --bins --tests -- i18n::tests::untranslated_report --exact --nocapture") } From b0294122e80e8a90e4325fad09a42d6bf28b0633 Mon Sep 17 00:00:00 2001 From: FredApps <FredApps@users.noreply.github.com> Date: Sun, 1 Nov 2026 02:20:34 +0100 Subject: [PATCH 230/260] ci: leave print.yml unchanged print.yml still runs its own jobs, and CLAUDE.md (CI workflows) keeps additions out of such files. The cache churn it causes goes to craft-common-actions instead. This PR is now the xtask change only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .github/workflows/print.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.github/workflows/print.yml b/.github/workflows/print.yml index b805725f28..400a819442 100644 --- a/.github/workflows/print.yml +++ b/.github/workflows/print.yml @@ -26,13 +26,9 @@ jobs: with: toolchain: stable components: clippy - # Pull requests restore but never save: a PR's cache (about 1.3 GB) is visible only to that - # PR, and with the repository at its 10 GB limit each one evicted caches main's gate uses. - # A manual run on main seeds the cache every PR can restore. - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: key: desktop-print - save-if: ${{ github.ref == 'refs/heads/main' }} - run: cargo clippy --locked -p vectorcraft --all-targets -- -D warnings - run: cargo test --locked -p vectorcraft - name: Check pending submission and queue refusal feedback From d0834e68349eb5e8a825e2b306d772ac672d4b7c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 11:01:44 -0700 Subject: [PATCH 231/260] Transparency: a layer on top gives its topmost object as the opacity mask Make Opacity Mask took the topmost target as the mask. When that target was a layer (a targeted layer above the art, or `ids` ending in a layer id), the whole layer was removed from the layer tree and became the mask art. A layer on top now stands for its visible, unlocked art, as a layer below the mask already does: its topmost object is the mask and the rest of its art is masked with the art below. A top layer with no such art is refused and the document is left unchanged. --- crates/engine/src/cmd/opacitymask.rs | 74 +++++++++++++++++++++++----- 1 file changed, 63 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/opacitymask.rs b/crates/engine/src/cmd/opacitymask.rs index 8d65308600..d16eab4971 100644 --- a/crates/engine/src/cmd/opacitymask.rs +++ b/crates/engine/src/cmd/opacitymask.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> { "Make Opacity Mask", ["Window", "Transparency"], None, - "{ids?, clip?, invert?} the topmost of the selected objects (or of `ids`) becomes the mask of the others (grouped if several, a layer among several by its art). One object gets an empty mask and enters mask editing: draw the mask, then transparency.stopEditingOpacityMask; one target (an object or a layer) is refused in isolation mode and in pattern editing mode → {id, editing}", + "{ids?, clip?, invert?} the topmost of the selected objects (or of `ids`) becomes the mask of the others (grouped if several; a layer among several stands for its art, so the topmost object of a layer on top is the mask). One object gets an empty mask and enters mask editing: draw the mask, then transparency.stopEditingOpacityMask; one target (an object or a layer) is refused in isolation mode and in pattern editing mode → {id, editing}", can_make, make ), @@ -185,7 +185,7 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> { if d.mask_edit.is_some() { return Err(bad(C, "stop editing the opacity mask first")); } - let ids = match ids_param(p, "ids") { + let mut ids = match ids_param(p, "ids") { Some(ids) => { if let Some(id) = ids.iter().find(|id| d.node(**id).is_none()) { return Err(EngineError::NoNode(*id)); @@ -194,6 +194,25 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> { } None => super::appearance::subject_roots(s)?, }; + // A layer among several targets stands for its visible, unlocked art. A hidden, locked or + // template layer gives none. + let art_of = |id: NodeId| match d.node(id) { + Some(n) if n.is_layer() && (!n.visible || n.locked || n.is_template()) => vec![], + Some(n) if n.is_layer() => n.layer_art(true), + _ => vec![id], + }; + // A layer on top: the topmost object of its art is the mask, and the rest of it is masked. + if ids.len() > 1 + && let Some(&top) = ids.last() + && d.node(top).is_some_and(Node::is_layer) + { + let top_art = super::edit::outermost(d, d.paint_order(art_of(top))); + if top_art.is_empty() { + return Err(bad(C, "select the art and, on top of it, the mask object")); + } + ids.pop(); + ids.extend(top_art); + } let Some((&top, below)) = ids.split_last() else { return Err(bad(C, "select the art and, on top of it, the mask object")) }; // One target gets an empty mask and enters mask editing, which isolation mode and pattern // editing mode do not allow. @@ -206,17 +225,10 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> { let invert = bool_or(p, "invert", s.menu.new_masks_inverted); // Several objects: the top one is the mask. One: an empty mask, drawn in mask editing. let (art, mask_id) = if below.is_empty() { (&ids[..], None) } else { (below, Some(top)) }; - // Several objects go into a new group, and a layer can't: a layer among them stands for its - // visible, unlocked art, which the group takes from it. A hidden, locked or template layer - // gives none. + // Several objects go into a new group, and a layer can't: the group takes a layer's art. let contents; let art = if art.len() > 1 && art.iter().any(|id| d.node(*id).is_some_and(Node::is_layer)) { - let objects = art.iter().flat_map(|id| match d.node(*id) { - Some(n) if n.is_layer() && (!n.visible || n.locked || n.is_template()) => vec![], - Some(n) if n.is_layer() => n.layer_art(true), - _ => vec![*id], - }); - contents = super::edit::outermost(d, d.paint_order(objects)); + contents = super::edit::outermost(d, d.paint_order(art.iter().flat_map(|id| art_of(*id)))); if contents.is_empty() { return Err(bad(C, "the layers hold no art to mask")); } @@ -549,6 +561,46 @@ mod tests { assert_eq!((d.parent_of(NodeId(b)), d.parent_of(NodeId(b2))), (Some(NodeId(l2)), Some(NodeId(l2)))); } + #[test] + fn make_takes_the_mask_from_the_art_of_a_layer_on_top() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let rect = |s: &mut Session, x: u64| { + s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let l1 = s.doc().unwrap().doc.layers[0].id.0; + let (a, a2) = (rect(&mut s, 0), rect(&mut s, 30)); + let l2 = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap(); + let (b, b2) = (rect(&mut s, 60), rect(&mut s, 90)); + let l3 = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap(); + let top = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 150, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let before = s.doc().unwrap().doc.layers.clone(); + let layer_ids: Vec<u64> = before.iter().map(|l| l.id.0).collect(); + // The topmost object of the top layer is the mask, and the rest of that layer's art is + // masked with the art below it. No layer leaves the layer tree. + for (ids, mask, grouped) in [(vec![a, l3], top, None), (vec![l1, l2], b2, Some(vec![a, a2, b])), (vec![a, l2], b2, Some(vec![a, b]))] { + let r = s.execute("transparency.makeOpacityMask", &json!({ "ids": ids })).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + assert_eq!(r["editing"], false, "{ids:?}"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| l.id.0).collect::<Vec<_>>(), layer_ids, "{ids:?}: every layer stays"); + assert!(d.node(NodeId(mask)).is_none(), "{ids:?}: the mask art left the layer tree"); + let n = d.node(id).unwrap(); + assert_eq!(n.extras().mask.as_ref().unwrap().art.id, NodeId(mask), "{ids:?}"); + match grouped { + Some(g) => assert_eq!(n.children().unwrap().iter().map(|c| c.id.0).collect::<Vec<_>>(), g, "{ids:?}"), + None => assert_eq!(id, NodeId(a), "{ids:?}"), + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, before, "{ids:?}: undo"); + } + // A top layer without art gives no mask, and nothing changes. + s.execute("layer.setProps", &json!({"id": l3, "visible": false})).unwrap(); + let hidden = s.doc().unwrap().doc.layers.clone(); + assert!(s.execute("transparency.makeOpacityMask", &json!({ "ids": [a, l3] })).is_err()); + assert_eq!(s.doc().unwrap().doc.layers, hidden); + } + #[test] fn release_restores_mask_art_and_undo_restores_mask() { let (mut s, a, b) = session_with_two(); From 482c011233b2d1a6fbc1ca25620a249bed7972ee Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 18:11:28 -0700 Subject: [PATCH 232/260] Transparency: a layer's art on a locked artboard or in a hidden or locked parent is not taken for an opacity mask Make Opacity Mask expands a layer among its targets to the art that can be edited: an object in a sublayer of a hidden or locked layer, or on a locked artboard, is neither the mask nor masked, so it stays where it is. --- crates/engine/src/cmd/opacitymask.rs | 39 +++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/opacitymask.rs b/crates/engine/src/cmd/opacitymask.rs index d16eab4971..f3e25b19e2 100644 --- a/crates/engine/src/cmd/opacitymask.rs +++ b/crates/engine/src/cmd/opacitymask.rs @@ -194,11 +194,13 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> { } None => super::appearance::subject_roots(s)?, }; - // A layer among several targets stands for its visible, unlocked art. A hidden, locked or - // template layer gives none. + // A layer among several targets stands for its art that can be edited: visible and unlocked, + // with every layer it is in, and not on a locked artboard. A hidden, locked or template layer + // gives none. + let editable = d.editable(); let art_of = |id: NodeId| match d.node(id) { Some(n) if n.is_layer() && (!n.visible || n.locked || n.is_template()) => vec![], - Some(n) if n.is_layer() => n.layer_art(true), + Some(n) if n.is_layer() => n.layer_art(true).into_iter().filter(|c| editable(*c)).collect(), _ => vec![id], }; // A layer on top: the topmost object of its art is the mask, and the rest of it is masked. @@ -236,6 +238,7 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> { } else { art }; + drop(editable); let (id, layer) = s.edit("Make Opacity Mask", |d, sel| { let mask_art = match mask_id { Some(m) => (*d.remove(m)?).clone(), @@ -601,6 +604,36 @@ mod tests { assert_eq!(s.doc().unwrap().doc.layers, hidden); } + #[test] + fn make_leaves_out_layer_art_that_cannot_be_edited() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let rect = |s: &mut Session, x: u64, y: u64| { + s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let a = rect(&mut s, 300, 10); + // A visible sublayer of a hidden layer holds no art that can be edited. + let l2 = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap(); + let sub = s.execute("layer.newSublayer", &json!({"parent": l2})).unwrap()["id"].as_u64().unwrap(); + let inner = rect(&mut s, 300, 40); + assert_eq!(s.doc().unwrap().doc.parent_of(NodeId(inner)), Some(NodeId(sub))); + s.execute("layer.setProps", &json!({"id": l2, "visible": false})).unwrap(); + let before = s.doc().unwrap().doc.layers.clone(); + assert!(s.execute("transparency.makeOpacityMask", &json!({ "ids": [a, sub] })).is_err()); + assert_eq!(s.doc().unwrap().doc.layers, before, "the hidden layer's art stays"); + // Art on a locked artboard acts as locked: the topmost object off it is the mask. + let l3 = s.execute("layer.new", &json!({"top": true})).unwrap()["id"].as_u64().unwrap(); + let off = rect(&mut s, 300, 70); + let on = rect(&mut s, 10, 10); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let r = s.execute("transparency.makeOpacityMask", &json!({ "ids": [a, l3] })).unwrap(); + let d = &s.doc().unwrap().doc; + let n = d.node(NodeId(r["id"].as_u64().unwrap())).unwrap(); + assert_eq!(n.id, NodeId(a)); + assert_eq!(n.extras().mask.as_ref().unwrap().art.id, NodeId(off)); + assert_eq!(d.parent_of(NodeId(on)), Some(NodeId(l3)), "the object on the locked artboard stays"); + } + #[test] fn release_restores_mask_art_and_undo_restores_mask() { let (mut s, a, b) = session_with_two(); From ac896cfe3da03084895213f9391ad9448fa5ba7d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 14:43:37 -0700 Subject: [PATCH 233/260] PDF export: a Perceptual gradient of one spot ink's tints keeps its ink A Perceptual linear or radial gradient was always written as an image, so a gradient of spot ink tints lost its plate, and no warning named the spot ink. PDF export now writes a Perceptual gradient whose stops are tints of one spot color (and paper white) as a Separation shading in that ink. Its tints follow the gradient's curve: at each stop the renderer places on the curve, the tint with the OKLab lightness of the color there. Dithered fills, freeform gradients and Perceptual gradients that mix a spot color with other colors are still images, and the export now warns when such a gradient has stops linked to a spot swatch that its spot colors are written in process colors. --- crates/color/src/gradient.rs | 45 +++++++++++++++ crates/color/src/gradient/tests.rs | 31 ++++++++++ crates/engine/src/cmd/gradient.rs | 2 +- crates/engine/src/tests/linked_stops.rs | 75 +++++++++++++++++++++++++ crates/pdf/src/export/nodes.rs | 5 +- crates/pdf/src/export/paint.rs | 50 ++++++++++++++++- docs/target-app-parity.md | 2 + 7 files changed, 206 insertions(+), 4 deletions(-) diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 528d560336..bde5fc8099 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -78,6 +78,14 @@ const PERCEPTUAL_TOLERANCE: f32 = 0.4 / 255.0; /// Most times each half of a Perceptual gradient's segment (either side of its midpoint) is /// halved to keep within [`PERCEPTUAL_TOLERANCE`]. const PERCEPTUAL_DEPTH: u32 = 10; +/// How many times [`Gradient::ink_tints`] halves the range of tints it searches: to within +/// 1/65536 of a tint, finer than the 1/255 steps PDF writes. +const TINT_STEPS: u32 = 16; +/// The least OKLab lightness by which an ink at 100% must differ from paper white for +/// [`Gradient::ink_tints`] to tell its tints apart by lightness. +const MIN_INK_LIGHTNESS_SPAN: f64 = 1.0 / 255.0; +/// Most stops on a gradient's curve that [`Gradient::ink_tints`] finds tints for. +const MAX_INK_TINTS: usize = 4096; /// The mix positions (0..1, after `v0`, before `v1`) between which display RGB mixed linearly /// stays within [`PERCEPTUAL_TOLERANCE`] of the perceptual mix of `a` and `b`: the span halved @@ -284,6 +292,43 @@ impl Gradient { std::iter::once((s.offset, s.color, s.opacity, None)).chain(classic).chain(perceptual.into_iter().flatten()) }) } + /// A gradient of tints of one ink `ink` (its color at 100%; paper white is 0% of it) as + /// (offset, tint, opacity) at each of [`Self::expanded_stops`]: the tint (0..1) whose OKLab + /// lightness is the lightness of the color there, found to [`TINT_STEPS`] halvings. Mixed + /// linearly between them, the tints follow a Perceptual gradient's curve. `None` when the + /// ink's lightness is within [`MIN_INK_LIGHTNESS_SPAN`] of paper white's (a white or nearly + /// white ink), so lightness does not tell its tints apart, and when the curve has more than + /// [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]). + pub fn ink_tints(&self, ink: &Color) -> Option<Vec<(f32, f32, f32)>> { + use crate::libraries::srgb_to_oklab; + let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0]; + if lightness(&ink.tinted(0.0)) - lightness(ink) < MIN_INK_LIGHTNESS_SPAN { + return None; + } + let curve: Vec<_> = self.expanded().take(MAX_INK_TINTS + 1).collect(); + if curve.len() > MAX_INK_TINTS { + return None; + } + let tint = |c: &Color| { + let want = lightness(c); + let (mut lo, mut hi) = (0.0f32, 1.0f32); + for _ in 0..TINT_STEPS { + let mid = (lo + hi) / 2.0; + if lightness(&ink.tinted(mid)) > want { + lo = mid; + } else { + hi = mid; + } + } + (lo + hi) / 2.0 + }; + Some(curve.into_iter().map(|(t, c, o, _)| (t, tint(&c), o)).collect()) + } + /// Does the gradient's curve ([`Self::expanded`]) have at most [`MAX_INK_TINTS`] stops, so + /// [`Self::ink_tints`] finds tints for it? + pub fn fits_ink_tints(&self) -> bool { + self.expanded().nth(MAX_INK_TINTS).is_none() + } /// The same ramp the other way round: the stops in reverse order at mirrored offsets, each /// segment's midpoint mirrored with it. pub fn reverse(&mut self) { diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index 19e9f44fc7..c2d7d23d74 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -455,3 +455,34 @@ fn perceptual_gradients_draw_as_pixels() { assert!(GradientPaint::new(radial).draws_as_pixels(fill)); } } + +/// A Perceptual gradient of an ink's tints as tints: its stops keep their tints, and each tint on +/// the curve has the lightness of the color mixed there, so the tints between the stops are not +/// a straight line. +#[test] +fn ink_tints_follow_the_perceptual_curve() { + use crate::libraries::srgb_to_oklab; + let ink = Color::cmyk(0.0, 1.0, 0.0, 0.0); + let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, ink.tinted(0.8)), GradientStop::new(1.0, Color::WHITE)]); + g.method = GradientMethod::Perceptual; + assert!(g.fits_ink_tints()); + let tints = g.ink_tints(&ink).expect("a magenta ink's tints differ in lightness"); + assert!(tints.len() > 2, "the curve's stops: {tints:?}"); + let (first, last) = (tints[0], tints[tints.len() - 1]); + assert!((first.0, last.0) == (0.0, 1.0) && (first.1 - 0.8).abs() < 1e-4 && last.1 < 1e-4, "{tints:?}"); + assert!(tints.windows(2).all(|w| w[0].0 <= w[1].0 && w[0].1 >= w[1].1), "in order, lighter along the way: {tints:?}"); + let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0]; + for (t, tint, _) in &tints { + let want = lightness(&g.sample(*t).0); + assert!((lightness(&ink.tinted(*tint)) - want).abs() < 1e-3, "at {t}: tint {tint}"); + } + let mid = tints.iter().find(|s| (s.0 - 0.5).abs() < 1e-6).expect("the midpoint"); + assert!((mid.1 - 0.4).abs() > 0.01, "not halfway in tint: {mid:?}"); + // A white ink's tints all have paper white's lightness: no tints by lightness. + assert_eq!(g.ink_tints(&Color::WHITE), None); + // More stops on the curve than MAX_INK_TINTS: no tints. + let n = MAX_INK_TINTS + 1; + g.stops = (0..n).map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { ink } else { Color::WHITE })).collect(); + assert_eq!(g.ink_tints(&ink), None); + assert!(!g.fits_ink_tints()); +} diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 92ce8723bc..ccaf3eeee0 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even, which SVG and PDF exports draw as an image; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even, which SVG and PDF exports draw as an image, except that PDF writes one made of tints of one spot color in that ink; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", has_doc, edit_gradient ), diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index 33c622ec7e..5adffe77cf 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -192,3 +192,78 @@ fn linked_stops_round_trip() { assert_eq!(old, GradientStop::new(0.5, Color::rgb(1.0, 0.0, 0.0))); assert!(!serde_json::to_string(&old).unwrap().contains("tint")); } + +/// `stops` with `extra` (method, dither…) as a gradient edit. +fn with(mut stops: Value, extra: Value) -> Value { + if let (Some(g), Some(e)) = (stops.as_object_mut(), extra.as_object()) { + g.extend(e.clone()); + } + stops +} + +#[test] +fn perceptual_spot_gradients_export_as_separation_shadings() { + let (mut s, _) = setup(); + let ink_to_tint = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "swatch": "Ink", "tint": 20}]}); + for (what, stops) in [("Ink → paper", ink_to_white(80.0)), ("Ink → Ink 20 %", ink_to_tint)] { + run(&mut s, "paint.editGradient", with(stops, json!({"method": "perceptual"}))); + let (pdf, warnings) = pdf_of(&s); + assert!(!pdf.contains("/Subtype/Image"), "{what}: no image"); + assert!(pdf.contains("/ShadingType 2") && pdf.contains("/Separation/Ink/DeviceCMYK"), "{what}: a Separation shading"); + // The curve's stops: a stitching function of more than the two ends. + assert!(pdf.contains("/FunctionType 3"), "{what}: tints on the curve"); + assert!(!warnings.iter().any(|w| w.contains("spot")), "{what}: {warnings:?}"); + } + // A radial one, and one on a stroke, too. + run(&mut s, "paint.editGradient", with(ink_to_white(100.0), json!({"method": "perceptual", "kind": "radial"}))); + let (pdf, _) = pdf_of(&s); + assert!(!pdf.contains("/Subtype/Image") && pdf.contains("/Separation/Ink/DeviceCMYK"), "radial"); + run(&mut s, "paint.setFill", json!({"color": "#ffffff"})); + run(&mut s, "paint.setStroke", json!({"color": "#000000"})); + run(&mut s, "stroke.set", json!({"weight": 6})); + run(&mut s, "paint.editGradient", with(ink_to_white(100.0), json!({"method": "perceptual", "stroke": true}))); + let (pdf, _) = pdf_of(&s); + assert!(!pdf.contains("/Subtype/Image") && pdf.contains("/Separation/Ink/DeviceCMYK"), "stroke"); + // A white spot ink has paper white's lightness at every tint: the stops keep their own tints. + run(&mut s, "swatch.new", json!({"name": "Opaque", "color": "#ffffff", "spot": true})); + run(&mut s, "paint.setStroke", json!({"none": true})); + let white = + json!({"stops": [{"offset": 0, "swatch": "Opaque"}, {"offset": 1, "swatch": "Opaque", "tint": 40}], "method": "perceptual", "stroke": false}); + run(&mut s, "paint.editGradient", white); + let (pdf, _) = pdf_of(&s); + let at = pdf.find("/FunctionType").unwrap_or(0); + assert!(!pdf.contains("/Subtype/Image") && pdf.contains("/Separation/Opaque"), "white ink: {}", &pdf[at..(at + 200).min(pdf.len())]); + assert!(pdf.contains("/C0[1]") && pdf.contains("/C1[0.4"), "white ink at 100% to 40%: {}", &pdf[at..(at + 200).min(pdf.len())]); +} + +#[test] +fn spot_gradients_drawn_as_images_warn() { + let (mut s, _) = setup(); + let spot_warning = |w: &[String]| w.iter().any(|w| w.contains("spot colors in gradients exported as images")); + let ink_to_cyan = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": {"c": 1, "m": 0, "y": 0, "k": 0}}]}); + // More stops than the export finds tints for: an image, as before. + let n = 4097; + let stops: Vec<Value> = (0..n) + .map(|i| { + let offset = i as f64 / (n - 1) as f64; + if i % 2 == 0 { json!({"offset": offset, "swatch": "Ink"}) } else { json!({"offset": offset, "color": "#ffffff"}) } + }) + .collect(); + for (what, edit) in [ + ("Perceptual Ink → cyan", with(ink_to_cyan, json!({"method": "perceptual"}))), + ("dithered Classic Ink → paper", with(ink_to_white(100.0), json!({"dither": true, "method": "classic"}))), + ("dithered Perceptual Ink → paper", with(ink_to_white(100.0), json!({"dither": true, "method": "perceptual"}))), + ("Perceptual Ink and paper, 4,097 stops", json!({"stops": stops, "dither": false, "method": "perceptual"})), + ] { + run(&mut s, "paint.editGradient", edit); + let (pdf, warnings) = pdf_of(&s); + assert!(pdf.contains("/Subtype/Image"), "{what}: an image"); + assert!(spot_warning(&warnings), "{what}: {warnings:?}"); + } + // A Perceptual gradient without spot inks is an image, without the warning. + let blue_yellow = json!({"stops": [{"offset": 0, "color": "#0000ff"}, {"offset": 1, "color": "#ffff00"}]}); + run(&mut s, "paint.editGradient", with(blue_yellow, json!({"method": "perceptual", "dither": false}))); + let (pdf, warnings) = pdf_of(&s); + assert!(pdf.contains("/Subtype/Image") && !pdf.contains("/Separation"), "a process Perceptual gradient"); + assert!(!spot_warning(&warnings), "{warnings:?}"); +} diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index c7090e8e20..5dc0a73af7 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -348,11 +348,12 @@ impl Exporter<'_> { /// Is `p` a paint PDF has no paint for when it paints a fill (`fill`) or a stroke, which /// [`Self::area`] draws as art: a pattern swatch or a gradient drawn as pixels - /// ([`vectorcraft_color::GradientPaint::draws_as_pixels`])? + /// ([`vectorcraft_color::GradientPaint::draws_as_pixels`]), but not a Perceptual one of tints + /// of one spot ink ([`Self::perceptual_spot`])? pub(super) fn area_paint(&self, p: &Paint, fill: bool) -> bool { match p { Paint::Pattern { pattern, .. } => self.doc.pattern(pattern).is_some(), - Paint::Gradient(g) => g.draws_as_pixels(fill), + Paint::Gradient(g) => g.draws_as_pixels(fill) && !self.perceptual_spot(g, fill), _ => false, } } diff --git a/crates/pdf/src/export/paint.rs b/crates/pdf/src/export/paint.rs index b7c3034879..dc2b3b5500 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -195,7 +195,10 @@ impl Exporter<'_> { Paint::Solid { color: c, swatch, tint } => Some(self.solid(c, swatch.as_deref(), *tint).into()), Paint::Gradient(g) => { let geom = g.resolve(bounds); - let spot = (g.gradient.kind != GradientKind::Freeform).then(|| self.spot_stops(&g.gradient)).flatten(); + let spot = match g.gradient.kind { + GradientKind::Freeform => None, + _ => self.perceptual_spot_stops(&g.gradient).or_else(|| self.spot_stops(&g.gradient)), + }; let colored = match spot { Some(v) => v, None => { @@ -333,6 +336,50 @@ impl Exporter<'_> { Some(krilla::paint::Pattern { stream: sb.finish(), transform: xf(at), width: pw as f32, height: ph as f32 }.into()) } + /// The spot swatch whose tints are every stop of `g` that isn't paper white, unlinked; `None` + /// when no stop is linked to a spot swatch or a stop has another color. + fn one_spot_ink<'g>(&self, g: &'g vectorcraft_color::Gradient) -> Option<&'g str> { + let spot = |s: &'g vectorcraft_color::GradientStop| s.swatch.as_deref().filter(|n| self.doc.swatch(n).is_some_and(|w| w.spot)); + let ink = g.stops.iter().find_map(spot)?; + let paper = |s: &vectorcraft_color::GradientStop| s.swatch.is_none() && s.color.to_rgba8(1.0)[..3] == [255; 3]; + g.stops.iter().all(|s| spot(s) == Some(ink) || paper(s)).then_some(ink) + } + + /// Is `g` a Perceptual linear or radial gradient of tints of one spot ink that paints a fill + /// (`fill`) without dither or a stroke, with a curve short enough for + /// [`vectorcraft_color::Gradient::fits_ink_tints`], which [`Self::perceptual_spot_stops`] + /// writes as a Separation shading rather than an image? + pub(super) fn perceptual_spot(&self, g: &vectorcraft_color::GradientPaint, fill: bool) -> bool { + let gr = &g.gradient; + !gr.method.is_classic() && gr.kind != GradientKind::Freeform && !(fill && gr.dither) && self.one_spot_ink(gr).is_some() && gr.fits_ink_tints() + } + + /// The stops of a Perceptual gradient of tints of one spot ink (or paper white, 0% of it) as + /// tints of that ink, a Separation shading: the stops on its curve with the tints whose + /// lightness is the curve's there ([`vectorcraft_color::Gradient::ink_tints`]). `None` for + /// other gradients, and for an ink too light for lightness to tell its tints apart, which + /// [`Self::spot_stops`] then writes with the stops' own tints. + fn perceptual_spot_stops(&mut self, g: &vectorcraft_color::Gradient) -> Option<Vec<(f32, krilla::color::Color, f32)>> { + if g.method.is_classic() { + return None; + } + let ink = self.one_spot_ink(g)?; + let doc = self.doc; + let full = doc.linked_color(doc.swatch(ink)?.paint.color()?, true); + let space = self.separation(ink)?; + Some(g.ink_tints(&full)?.into_iter().map(|(o, t, a)| (o, SepColor::new(q(t), space.clone()).into(), a)).collect()) + } + + /// Warn when gradient `g`, drawn as an image, has stops linked to a spot swatch: the image is + /// in process colors, so the spot inks have no plate of their own. + fn warn_spot_image(&mut self, g: &vectorcraft_color::GradientPaint) { + let doc = self.doc; + let from_stops = g.gradient.kind != GradientKind::Freeform || g.freeform.is_none(); + if from_stops && g.gradient.stops.iter().any(|s| s.swatch.as_deref().is_some_and(|n| doc.swatch(n).is_some_and(|w| w.spot))) { + self.warn("spot colors in gradients exported as images (freeform, dithered or Perceptual gradients that mix inks) are written in process colors"); + } + } + /// Draw gradient `g`, placed on `bounds`, as an image over `area`, sampled at the document's /// raster effects resolution where it is drawn (`area` as the current transform sizes it, so /// scaled type gets its pixels too): a freeform gradient's colour field (at most @@ -349,6 +396,7 @@ impl Exporter<'_> { if !(long > 1e-9 && long.is_finite()) { return; } + self.warn_spot_image(g); let freeform = g.gradient.kind == GradientKind::Freeform; let max = if freeform { MAX_FIELD_PX } else { MAX_GRADIENT_PX }; let k = (self.doc.raster_effects_ppi / 72.0).min(max / long); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 231426c8e9..9d6e87405a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1265,6 +1265,8 @@ applies to fills). Tests: `color::gradient::tests` (perceptual midpoint, expansi `pdf::tests::dithered_perceptual_gradients_export_as_images_with_noise_on_the_fill` and the Gradient panel's `the_method_menu_makes_the_gradient_perceptual`. Scores and hours unchanged. +PDF export writes a Perceptual linear or radial gradient whose stops are tints of one spot color (and paper white) as a Separation shading in that ink instead of an image, so the ink keeps its plate ([swatches](https://helpx.adobe.com/illustrator/using/using-creating-swatches.html): "Gradient colors can be assigned as CMYK process colors, RGB colors, or a Spot color."; [separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html): "a separate plate is created for each spot color"). Its tints follow the curve's stops, each the tint with the OKLab lightness of the color there (VectorCraft's own rule). Dithered fills, freeform gradients and Perceptual gradients that mix a spot color with other colors are still images, and the export warns that their spot colors are written in process colors. Tests: `color::gradient::tests::ink_tints_follow_the_perceptual_curve`, `engine::tests::linked_stops::perceptual_spot_gradients_export_as_separation_shadings` and `spot_gradients_drawn_as_images_warn`. + ## Artwork Cleanup add-on (2026-10-30) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Artwork Cleanup and its From ece78f052fc090cb58df739ddc24b9285f48c93c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 18:03:21 -0700 Subject: [PATCH 234/260] Type: Standard Vertical Roman Alignment stands half-width characters upright in vertical type Character panel menu > Standard Vertical Roman Alignment, with Show East Asian Options, is now a check item. It sets a new character attribute, `standardVerticalRoman` (text.setFormat, text.setRangeStyle), off by default and saved only when on. In vertical type the marked Latin letters, digits and other characters that would lie on their side stand upright one below the other, each in its upright cell. Spaces keep their width and tate-chu-yoko blocks stay across the column. Horizontal type keeps the mark and does not change. A combining mark shaped as its own glyph turns with its letter, in Latin and CJK upright type alike. Character Style Options labels the Character Alignment row "Character Alignment" and gives Standard Vertical Roman Alignment its own checkbox. Reset Panel turns the attribute off. PDF and SVG export place the glyphs from the layout and need no change. --- crates/doc/src/text/char_style.rs | 9 +++ crates/engine/src/cmd/panelcmds.rs | 6 +- crates/engine/src/cmd/textedit.rs | 10 ++- crates/engine/src/cmd/textstyles.rs | 1 + crates/engine/src/cmd/typecmd/area_tests.rs | 38 ++++++++++ crates/text/src/layout.rs | 52 ++++++++++--- crates/text/src/layout/driver.rs | 1 + crates/text/src/layout/vertical.rs | 8 +- crates/text/src/layout/wrapping_tests.rs | 1 + crates/text/src/shape.rs | 6 ++ crates/text/src/tests/vertical.rs | 54 ++++++++++++++ .../ui-egui/src/dialogs/char_style_options.rs | 73 ++++++++++++++++--- crates/ui-egui/src/panels/character.rs | 17 +++-- crates/ui-egui/src/panels/character/tests.rs | 45 +++++++++++- docs/mcp.md | 2 +- docs/target-app-parity.md | 1 + docs/type-parity.md | 1 + 17 files changed, 290 insertions(+), 35 deletions(-) diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index d53c99e6c6..dd84912f09 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -104,6 +104,14 @@ pub struct CharStyle { /// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html> #[serde(default, rename = "tateChuYoko", skip_serializing_if = "crate::skip::is_default")] pub tate_chu_yoko: bool, + /// Standard Vertical Roman Alignment (Character panel menu, East Asian options): in vertical + /// type the half-width characters among these (Latin letters, digits and other characters that + /// would lie on their side) stand upright one below the other instead of being rotated + /// individually. Spaces and tate-chu-yoko blocks do not change, and horizontal type keeps the + /// mark and does not change. + /// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html> + #[serde(default, rename = "standardVerticalRoman", skip_serializing_if = "crate::skip::is_default")] + pub standard_vertical_roman: bool, /// Digits (Character panel menu, Middle Eastern options): the numeral system the digits of /// these characters are drawn in, whatever digits were typed. #[serde(default, skip_serializing_if = "crate::skip::is_default")] @@ -369,6 +377,7 @@ impl Default for CharStyle { char_direction: None, proportional_metrics: false, tate_chu_yoko: false, + standard_vertical_roman: false, small_caps: None, digits: Digits::Default, no_break: false, diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 163d543772..7f504dcc4f 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", has_doc, set_format ), @@ -370,6 +370,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { "charDirection", "proportionalMetrics", "tateChuYoko", + "standardVerticalRoman", "noBreak", "digits", "language", @@ -535,6 +536,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { if let Some(v) = flag("tateChuYoko") { st.tate_chu_yoko = v; } + if let Some(v) = flag("standardVerticalRoman") { + st.standard_vertical_roman = v; + } if let Some(v) = flag("noBreak") { st.no_break = v; } diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 1797873ae3..8cfdaf47f4 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -319,6 +319,7 @@ pub(crate) struct CharChange { char_direction: Option<Option<vectorcraft_doc::ParaDirection>>, proportional_metrics: Option<bool>, tate_chu_yoko: Option<bool>, + standard_vertical_roman: Option<bool>, no_break: Option<bool>, digits: Option<vectorcraft_doc::Digits>, /// The language to set: a tag, or `None` for the default. @@ -471,7 +472,7 @@ impl CharChange { /// `setup` gives the superscript, subscript and small caps proportions. pub(crate) fn parse(p: &Value, cmd: &str, setup: &vectorcraft_doc::DocSetup) -> Result<Self> { check_numbers(p, &["size", "tracking", "baselineShift", "hScale", "vScale", "rotation", "strokeWidth"], cmd)?; - check_switches(p, &["underline", "strikethrough", "allCaps", "proportionalMetrics", "tateChuYoko", "noBreak"], cmd)?; + check_switches(p, &["underline", "strikethrough", "allCaps", "proportionalMetrics", "tateChuYoko", "standardVerticalRoman", "noBreak"], cmd)?; let num = |k: &str| p.get(k).and_then(Value::as_f64); let (position, small_caps) = super::docsetup::script_params(p, setup, cmd)?; let flag = |k: &str| p.get(k).and_then(Value::as_bool); @@ -517,6 +518,7 @@ impl CharChange { char_direction: char_direction_param(p, cmd)?, proportional_metrics: flag("proportionalMetrics"), tate_chu_yoko: flag("tateChuYoko"), + standard_vertical_roman: flag("standardVerticalRoman"), no_break: flag("noBreak"), digits: digits_param(p, cmd)?, language: language_param(p, cmd)?, @@ -563,6 +565,7 @@ impl CharChange { && self.char_direction.is_none() && self.proportional_metrics.is_none() && self.tate_chu_yoko.is_none() + && self.standard_vertical_roman.is_none() && self.no_break.is_none() && self.digits.is_none() && self.language.is_none() @@ -668,6 +671,9 @@ impl CharChange { if let Some(v) = self.tate_chu_yoko { st.tate_chu_yoko = v; } + if let Some(v) = self.standard_vertical_roman { + st.standard_vertical_roman = v; + } if let Some(v) = self.no_break { st.no_break = v; } diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index e70af82a08..5995c490d8 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -175,6 +175,7 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> { ("charDirection", json!(v.char_direction)), ("proportionalMetrics", json!(v.proportional_metrics)), ("tateChuYoko", json!(v.tate_chu_yoko)), + ("standardVerticalRoman", json!(v.standard_vertical_roman)), ("noBreak", json!(v.no_break)), ("digits", json!(v.digits)), ("language", json!(v.language)), diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index 1dae041d90..65febdf0bd 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -1206,6 +1206,44 @@ fn tate_chu_yoko_is_a_character_attribute_saved_only_when_on() { assert!(runs(&s).iter().all(|r| !r.style.tate_chu_yoko)); } +/// Standard Vertical Roman Alignment (Character panel menu, East Asian options): a character +/// attribute, off by default and saved only when on. Documents written before it read as off; a +/// character style captured from the characters carries it. +#[test] +fn standard_vertical_roman_is_a_character_attribute_saved_only_when_on() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "ABC年"})).unwrap()["id"].as_u64().unwrap(); + let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("text"), + }; + assert!(!runs(&s)[0].style.standard_vertical_roman); + assert!(serde_json::to_value(&runs(&s)[0].style).unwrap().get("standardVerticalRoman").is_none()); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("text.setFormat", &json!({"standardVerticalRoman": true})).unwrap(); + assert!(runs(&s).iter().all(|r| r.style.standard_vertical_roman)); + assert_eq!(serde_json::to_value(&runs(&s)[0].style).unwrap()["standardVerticalRoman"], true); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!runs(&s)[0].style.standard_vertical_roman); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 3, "standardVerticalRoman": true})).unwrap(); + let on: Vec<_> = runs(&s).iter().map(|r| (r.text.clone(), r.style.standard_vertical_roman)).collect(); + assert_eq!(on, [("ABC".to_string(), true), ("年".to_string(), false)]); + let old = serde_json::to_value(&runs(&s)[1].style).unwrap(); + assert!(old.get("standardVerticalRoman").is_none()); + assert!(!serde_json::from_value::<vectorcraft_doc::CharStyle>(old).unwrap().standard_vertical_roman); + // Saved and reopened as it was. + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") }; + let reopened: Vec<_> = t.runs.iter().map(|r| (r.text.clone(), r.style.standard_vertical_roman)).collect(); + assert_eq!(reopened, on); + assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[0].style)["standardVerticalRoman"], true); + assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[1].style)["standardVerticalRoman"], false); + assert!(s.execute("text.setRangeStyle", &json!({"id": id, "standardVerticalRoman": "true"})).is_err()); + s.execute("text.setFormat", &json!({"standardVerticalRoman": false})).unwrap(); + assert!(runs(&s).iter().all(|r| !r.style.standard_vertical_roman)); +} + /// No Break is a character attribute, saved only when on. #[test] fn no_break_is_a_character_attribute_saved_only_when_on() { diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 66cdaf304d..f217eaa3a3 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -41,6 +41,12 @@ use vertical::{stands_upright, tate_chu_yoko, upright_cell, upright_centre, whol const EPS: f64 = 1e-6; +/// Is glyph `g` a later glyph of the cluster of glyph `prev` before it (a combining mark the shaper +/// set as a glyph of its own)? A list marker's glyphs stand for no character and are not. +fn continues_cluster(prev: Option<&SGlyph>, g: Option<&SGlyph>) -> bool { + prev.zip(g).is_some_and(|(a, b)| a.len > 0 && b.len > 0 && a.byte == b.byte) +} + struct Ctx<'a> { on_path: bool, db: &'a FontDb, @@ -58,6 +64,10 @@ struct Ctx<'a> { system_layout: bool, /// Character panel menu › Fractional Widths. Off, positive advances are whole points. fractional_widths: bool, + /// Vertical type: the upright glyph [`Self::emit`] placed last, as (its byte, the index the + /// next glyph of its cluster would take, the turn it got, the line-space x that next glyph is + /// set after), so that a combining mark shaped into the same cluster turns with it. + upright_cluster: Option<(usize, usize, Affine, f64)>, out: TextLayout, } @@ -108,8 +118,11 @@ impl Ctx<'_> { }); // An upright glyph advances down the column by its vertical advance (the font's vertical // metrics; without them at least one em, as CJK fonts' is), centred across it: a narrow - // mark like § must not overlap its neighbours. - for g in v.iter_mut().filter(|g| g.adv > 0.0 && stands_upright(g)) { + // mark like § must not overlap its neighbours. A combining mark shaped into the cluster + // of the glyph before it takes no cell of its own: it turns with that glyph (`emit`). + for i in 0..v.len() { + let continues = continues_cluster(i.checked_sub(1).and_then(|p| v.get(p)), v.get(i)); + let Some(g) = v.get_mut(i).filter(|g| g.adv > 0.0 && !continues && stands_upright(g)) else { continue }; let extra = upright_cell(g) - g.face.advance(g.gid) * g.sx; g.dx += extra * 0.5; g.adv += extra; @@ -181,6 +194,8 @@ impl Ctx<'_> { } fn emit(&mut self, g: &SGlyph, pre: Affine, origin: Point, angle: f64, advance: f64, line: usize) { + // Only the glyph right after an upright glyph can continue its cluster. + let cluster = self.upright_cluster.take(); // Control characters (tabs) and soft hyphens draw nothing (fonts map them to .notdef). let blank = g.is_soft_hyphen() || g.ch.is_control() || g.ch == '\u{2028}'; // A colour glyph draws its art (COLR layers, an SVG document) or its image (a bitmap, or @@ -235,16 +250,29 @@ impl Ctx<'_> { let squeeze = Affine::translate((centre.x, 0.0)) * Affine::scale_non_uniform(t.squeeze, 1.0) * Affine::translate((-centre.x, 0.0)); m = Affine::rotate_about(-std::f64::consts::FRAC_PI_2, centre) * squeeze * across * m; } else if self.vertical && stands_upright(g) { - // Turned about the centre of its cell, which the column's centre line runs through: the - // middle of its own cell, not of its advance (tracking and justification add space - // after the cell, and must not push the glyph off the centre line). - let em = self.style_at(g.byte).size; - let cell = if g.adv > 0.0 { upright_cell(g) } else { advance }; - // A leading space taken off moves it up the column after the turn (moving the - // turning point instead would move it across the column too). - m = Affine::translate((-g.lead, 0.0)) - * Affine::rotate_about(-std::f64::consts::FRAC_PI_2, Point::new(origin.x + cell * 0.5, origin.y - upright_centre(g, cell, em))) - * m; + let next = self.out.glyphs.len(); + let after_base = self.out.glyphs.last().is_some_and(|p| p.byte == g.byte && p.line == line && p.len > 0); + if let Some((_, _, turn, after)) = cluster.filter(|c| c.0 == g.byte && c.1 == next && after_base && g.len > 0) { + // A later glyph of an upright glyph's cluster: set after it as the shaper placed + // it, and turned with it. + m = turn * Affine::translate((after - origin.x, 0.0)) * m; + self.upright_cluster = Some((g.byte, next + 1, turn, after)); + } else { + // Turned about the centre of its cell, which the column's centre line runs through: + // the middle of its own cell, not of its advance (tracking and justification add + // space after the cell, and must not push the glyph off the centre line). + let em = self.style_at(g.byte).size; + let cell = if g.adv > 0.0 { upright_cell(g) } else { advance }; + // A leading space taken off moves it up the column after the turn (moving the + // turning point instead would move it across the column too). + let turn = Affine::translate((-g.lead, 0.0)) + * Affine::rotate_about(-std::f64::consts::FRAC_PI_2, Point::new(origin.x + cell * 0.5, origin.y - upright_centre(g, cell, em))); + m = turn * m; + // Its own advance across, from where the cell centres it: where the shaper set the + // next glyph of its cluster. + let across = g.face.advance(g.gid) * g.sx; + self.upright_cluster = (g.len > 0).then_some((g.byte, next + 1, turn, origin.x + (cell - across) * 0.5 + across)); + } } let outline = if src.elements().is_empty() || blank { BezPath::new() diff --git a/crates/text/src/layout/driver.rs b/crates/text/src/layout/driver.rs index 03a5d66179..4cb518d0d5 100644 --- a/crates/text/src/layout/driver.rs +++ b/crates/text/src/layout/driver.rs @@ -228,6 +228,7 @@ fn layout_once(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLayout vertical, system_layout: t.system_layout, fractional_widths: t.fractional_widths, + upright_cluster: None, out: TextLayout::default(), }; // Vertical type: line space turned a quarter turn clockwise (lines become columns, each next diff --git a/crates/text/src/layout/vertical.rs b/crates/text/src/layout/vertical.rs index 0953ae6567..61251d76ed 100644 --- a/crates/text/src/layout/vertical.rs +++ b/crates/text/src/layout/vertical.rs @@ -218,6 +218,12 @@ pub(super) const QUARTER_TURN: Affine = Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0 /// their side when the font has none (Unicode's Vertical_Orientation Tr). /// Fullwidth !/? instead keep the nominal glyph upright (Tu fallback, UAX #50 §3.1): /// <https://www.unicode.org/reports/tr50/#vo>. +/// +/// Standard Vertical Roman Alignment (Character panel menu): a marked Latin letter, digit or other +/// character outside the classes above stands upright instead of lying on its side, except spaces +/// and control characters (they keep their width down the column) and the glyphs of a +/// tate-chu-yoko block, which stays across the column. +/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html> pub(super) fn stands_upright(g: &SGlyph) -> bool { let c = g.ch as u32; let upright = matches!(c, @@ -230,7 +236,7 @@ pub(super) fn stands_upright(g: &SGlyph) -> bool { | 0xE000..=0xFAFF | 0xFE10..=0xFE1F | 0xFE30..=0xFE4F | 0xFE50..=0xFE6F | 0xFF00..=0xFFE7 | 0x1F000..=0x1FAFF | 0x20000..=0x3FFFF); if !upright { - return false; + return g.vertical_roman && g.tcy.is_none() && g.inline.is_none() && !g.ch.is_whitespace() && !g.ch.is_control(); } let needs_vertical_form = matches!(c, 0x3001 | 0x3002 | 0x3008..=0x3011 | 0x3013..=0x301F | 0x3030 | 0x30A0 | 0x30FC diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index 6be50fbd8d..360c386ead 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -36,6 +36,7 @@ fn synthetic_glyphs(specs: &[(usize, usize, f64, char)]) -> Vec<SGlyph> { vpal: None, level: unicode_bidi::Level::ltr(), no_break: false, + vertical_roman: false, cursive: false, }) .collect() diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index f0fbb0c4de..e04c6c6dca 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -69,6 +69,9 @@ pub(crate) struct SGlyph { /// No Break (Character panel menu): keep this glyph on the same line as the neighbouring /// glyphs that have it. pub no_break: bool, + /// Standard Vertical Roman Alignment (Character panel menu): in vertical type this glyph + /// stands upright when it would otherwise lie on its side ([`crate::layout`]). + pub vertical_roman: bool, /// The glyph is of a script whose letters join (Arabic, Syriac, N'Ko, Mongolian, Adlam…), /// decided for the whole segment it was shaped in ([`joins`]): on a curved path it is bent /// along the path so its joins meet. @@ -713,6 +716,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { char_direction: _, proportional_metrics, tate_chu_yoko, + standard_vertical_roman: _, digits, no_break, language, @@ -828,6 +832,7 @@ fn inline_glyph(face: &Arc<FontFace>, st: &CharStyle, art: &InlineArt, run: usiz inline: Some(InlineBox { art: drawn, xf }), word_end: false, no_break: st.no_break, + vertical_roman: false, cursive: false, } } @@ -1137,6 +1142,7 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe inline: None, word_end: false, no_break: gst.no_break, + vertical_roman: gst.standard_vertical_roman, cursive, }); } diff --git a/crates/text/src/tests/vertical.rs b/crates/text/src/tests/vertical.rs index a2206df5eb..1010ed84a8 100644 --- a/crates/text/src/tests/vertical.rs +++ b/crates/text/src/tests/vertical.rs @@ -379,6 +379,60 @@ fn manual_tate_chu_yoko_leaves_unmarked_digits_and_stays_on_one_line() { assert!(wrapped.lines.len() > 1, "unmarked 2026 is longer than the column"); } +/// Character panel menu › Standard Vertical Roman Alignment: marked Latin letters and digits stand +/// upright one below the other, each in a cell of one em (the bundled font has no vertical +/// metrics), centred on the column. A space keeps its width, two digits stay tate-chu-yoko, +/// unmarked letters lie on their side, and horizontal type is unchanged. +#[test] +fn standard_vertical_roman_alignment_stands_half_width_characters_upright() { + let plain = CharStyle { size: 20.0, ..CharStyle::default() }; + let marked = CharStyle { standard_vertical_roman: true, ..plain.clone() }; + let h = layout(FontDb::global(), &TextObject::point(Point::ZERO, "l", plain.clone())); + let side = layout(FontDb::global(), &vertical_styled("lA l", plain.clone())); + let up = layout(FontDb::global(), &vertical_styled("lA l", marked.clone())); + let (hl, sl, ul) = (ink(&h, 0), ink(&side, 0), ink(&up, 0)); + assert!(sl.width() > sl.height(), "unmarked l lies across the column: {sl:?}"); + assert!((ul.width() - hl.width()).abs() < 0.01 && (ul.height() - hl.height()).abs() < 0.01, "marked l upright: {hl:?} {ul:?}"); + assert!(ul.height() > ul.width()); + for i in [0, 1, 3] { + assert!((up.glyphs[i].advance - 20.0).abs() < 1e-6, "one em down the column: {:?}", up.glyphs[i].advance); + assert!(ink(&up, i).center().x.abs() < 1.5, "centred on the column: {:?}", ink(&up, i)); + assert!(side.glyphs[i].advance < 20.0, "unmarked advance: {:?}", side.glyphs[i].advance); + } + assert!(ink(&up, 1).center().y > ink(&up, 0).center().y + 15.0, "one below the other"); + assert!((up.glyphs[2].advance - side.glyphs[2].advance).abs() < 1e-6, "the space keeps its width"); + + let digits = layout(FontDb::global(), &vertical_styled("10", marked.clone())); + assert!((digits.glyphs[0].advance - 20.0).abs() < 1e-6 && digits.glyphs[1].advance == 0.0, "two digits stay tate-chu-yoko"); + let (a, b) = (ink(&digits, 0), ink(&digits, 1)); + assert!((a.center().y - b.center().y).abs() < 1.0 && b.center().x > a.center().x, "side by side: {a:?} {b:?}"); + + let mut horizontal = TextObject::point(Point::ZERO, "lA", marked); + horizontal.xf = Affine::IDENTITY; + let row = layout(FontDb::global(), &horizontal); + let plain_row = layout(FontDb::global(), &TextObject::point(Point::ZERO, "lA", plain)); + assert_eq!(row.glyphs.iter().map(|g| g.advance).collect::<Vec<_>>(), plain_row.glyphs.iter().map(|g| g.advance).collect::<Vec<_>>()); + assert!((ink(&row, 0).height() - hl.height()).abs() < 0.01, "horizontal type stays as it is"); +} + +/// A combining mark shaped as a glyph of its own turns upright with its letter and stays over it, +/// as in horizontal type, and takes no cell of its own down the column. +#[test] +fn standard_vertical_roman_alignment_keeps_combining_marks_on_their_letter() { + let plain = CharStyle { size: 20.0, ..CharStyle::default() }; + let text = "q\u{301}x"; + let h = layout(FontDb::global(), &TextObject::point(Point::ZERO, text, plain.clone())); + assert_eq!(h.glyphs.len(), 3, "the bundled font sets the acute as a glyph of its own"); + let up = layout(FontDb::global(), &vertical_styled(text, CharStyle { standard_vertical_roman: true, ..plain })); + assert_eq!(up.glyphs.len(), 3); + let (hq, ha, q, a, x) = (ink(&h, 0), ink(&h, 1), ink(&up, 0), ink(&up, 1), ink(&up, 2)); + let offset = |base: Rect, mark: Rect| (mark.center().x - base.center().x, mark.center().y - base.center().y); + let (want, got) = (offset(hq, ha), offset(q, a)); + assert!((want.0 - got.0).abs() < 0.01 && (want.1 - got.1).abs() < 0.01, "the acute sits on the q as in a row: {want:?} {got:?}"); + assert!((up.glyphs[0].advance - 20.0).abs() < 1e-6 && up.glyphs[1].advance == 0.0, "one cell for the cluster"); + assert!(x.center().y > q.center().y + 10.0, "the next letter below: {q:?} {x:?}"); +} + /// Issue #260 as reported, with a Japanese face of craft-fonts (whose own digits are proportional). #[test] fn japanese_numbers_keep_their_own_cells_down_the_column() { diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 848151ac54..71d48056b5 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -19,9 +19,12 @@ const BASIC: &[&str] = &[ "position", "underline", "strikethrough", + "standardVerticalRoman", "charAlign", ]; const NUMBERS: &[&str] = &["size", "leading", "kerning", "tracking"]; +/// The on, off or unset checkboxes. +const SWITCHES: &[&str] = &["underline", "strikethrough", "standardVerticalRoman"]; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Character Style Options").into(), @@ -41,6 +44,7 @@ pub(super) const SPEC: DialogSpec = DialogSpec { "position", "underline", "strikethrough", + "standardVerticalRoman", "charAlign", "section", ] @@ -68,9 +72,11 @@ pub fn open(app: &mut VectorcraftApp, name: &str) -> Result<Value, String> { pub(crate) fn fields_from_attrs(attrs: &Map<String, Value>) -> Map<String, Value> { let mut fields = Map::new(); - for key in ["font_family", "font_style", "size", "leading", "kerning", "tracking", "underline", "strikethrough", "charAlign"] { + for key in + ["font_family", "font_style", "size", "leading", "kerning", "tracking", "underline", "strikethrough", "standardVerticalRoman", "charAlign"] + { let value = attrs.get(key).cloned().unwrap_or(Value::Null); - let shown = if ["underline", "strikethrough"].contains(&key) { + let shown = if SWITCHES.contains(&key) { value } else if value.is_null() { if attrs.contains_key(key) && ["leading", "kerning"].contains(&key) { json!("Auto") } else { json!("") } @@ -144,9 +150,9 @@ pub(crate) fn edited_attrs(d: &Dialog) -> Result<Map<String, Value>, String> { attrs.insert((*key).into(), v); } } - for key in ["underline", "strikethrough"] { - if let Some(v) = d.fields.get(key).and_then(Value::as_bool) { - attrs.insert(key.into(), json!(v)); + for key in SWITCHES { + if let Some(v) = d.fields.get(*key).and_then(Value::as_bool) { + attrs.insert((*key).into(), json!(v)); } } if reset || d.fields.get("case").and_then(Value::as_str) != case_from_attrs(&original) { @@ -204,8 +210,20 @@ pub(crate) fn edited_attrs(d: &Dialog) -> Result<Map<String, Value>, String> { pub(crate) fn reset_basic(d: &mut Dialog) { d.fields.insert("__resetBasic".into(), json!(true)); - for key in ["font_family", "font_style", "size", "leading", "kerning", "tracking", "case", "position", "underline", "strikethrough", "charAlign"] - { + for key in [ + "font_family", + "font_style", + "size", + "leading", + "kerning", + "tracking", + "case", + "position", + "underline", + "strikethrough", + "standardVerticalRoman", + "charAlign", + ] { d.fields.insert( key.into(), if ["font_family", "font_style", "size", "leading", "kerning", "tracking"].contains(&key) { json!("") } else { Value::Null }, @@ -255,7 +273,11 @@ pub(crate) fn basic_body(ui: &mut egui::Ui, d: &mut Dialog) { ui.label(tl!("Position")); choice(ui, d, "position", &[("normal", tl!("Normal")), ("superscript", tl!("Superscript")), ("subscript", tl!("Subscript"))]); ui.end_row(); - for (key, caption) in [("underline", tl!("Underline")), ("strikethrough", tl!("Strikethrough"))] { + for (key, caption) in [ + ("underline", tl!("Underline")), + ("strikethrough", tl!("Strikethrough")), + ("standardVerticalRoman", tl!("Standard Vertical Roman Alignment")), + ] { ui.label(""); let value = d.fields.get(key).and_then(Value::as_bool); if crate::widgets::check3(ui, caption, value, true) { @@ -270,7 +292,7 @@ pub(crate) fn basic_body(ui: &mut egui::Ui, d: &mut Dialog) { } ui.end_row(); } - ui.label(tl!("Standard Vertical Roman Alignment")); + ui.label(tl!("Character Alignment")); choice( ui, d, @@ -466,6 +488,39 @@ mod tests { assert_eq!(app.session.doc().unwrap().doc.char_styles.iter().find(|def| def.name == "Future").unwrap().attrs["size"], json!(36.0)); } + /// Basic Character Formats shows Character Alignment under its own name, and Standard Vertical + /// Roman Alignment as its own on, off or unset checkbox that the style saves. + #[test] + fn standard_vertical_roman_alignment_has_its_own_row() { + let mut d = Dialog::new(KIND, json!({})); + d.fields.extend(fields_from_attrs(&Map::new())); + d.fields.insert("__attrs".into(), json!({})); + let mut app = app(); + let shown = crate::tests_labels::painted_text(&mut app, |_, ui| basic_body(ui, &mut d)); + assert!(shown.contains("Character Alignment"), "{shown}"); + assert!(shown.contains("Standard Vertical Roman Alignment"), "{shown}"); + assert!(d.fields["standardVerticalRoman"].is_null()); + assert_eq!(edited_attrs(&d).unwrap(), Map::new()); + d.fields.insert("standardVerticalRoman".into(), json!(true)); + d.fields.insert("charAlign".into(), json!("emBoxCenter")); + assert_eq!(edited_attrs(&d).unwrap(), json!({"standardVerticalRoman": true, "charAlign": "emBoxCenter"}).as_object().unwrap().clone()); + let fields = fields_from_attrs(json!({"standardVerticalRoman": false}).as_object().unwrap()); + assert_eq!(fields["standardVerticalRoman"], json!(false)); + reset_basic(&mut d); + assert!(d.fields["standardVerticalRoman"].is_null()); + + app.run("charStyle.new", json!({"name": "Upright", "attrs": {}})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "AB", "vertical": true})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name": "Upright", "id": id})).unwrap(); + open(&mut app, "Upright").unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("standardVerticalRoman".into(), json!(true)); + super::super::confirm(&mut app).unwrap(); + let doc = &app.session.doc().unwrap().doc; + assert_eq!(doc.char_styles[0].attrs["standardVerticalRoman"], json!(true)); + let vectorcraft_doc::NodeKind::Text(t) = &doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { panic!("text") }; + assert!(t.runs.iter().all(|r| r.style.standard_vertical_roman)); + } + #[test] fn invalid_numbers_name_the_visible_field() { let mut d = Dialog::new(KIND, json!({})); diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index bf5788d985..b3a72b9d3b 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -1120,6 +1120,13 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Tate-chu-yoko"), has, tcy) { format(app, json!({"tateChuYoko": !tcy})); } + // Standard Vertical Roman Alignment: the selected half-width characters stand upright in + // vertical type instead of being rotated. Checked when every selected character has it; a + // mixed selection turns it on. + let roman = shared(app, |s| s.standard_vertical_roman) == Some(true); + if menu_item(ui, tl!("Standard Vertical Roman Alignment"), has, roman) { + format(app, json!({"standardVerticalRoman": !roman})); + } ui.separator(); } // Digits: the numeral system the selected characters' digits are drawn in, with the Middle @@ -1156,7 +1163,6 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("System Layout"), open, system) { app.run("type.systemLayout", json!({})).ok(); } - menu_item(ui, tl!("Standard Vertical Roman Alignment"), false, false); ui.separator(); // The installed fonts are always listed; this picks up fonts installed since the app started. #[cfg(not(target_arch = "wasm32"))] @@ -1184,9 +1190,9 @@ fn fractional_widths_on(app: &VectorcraftApp) -> bool { /// Reset Panel: the characters the panel acts on ([`char_cmd`]) take tracking 0, Auto leading and /// kerning, no baseline shift, 100% scales, no rotation, no underline or strikethrough, All Caps /// and Small Caps off, the normal position (neither superscript nor subscript), Roman Baseline -/// character alignment, Proportional Metrics, Tate-chu-yoko and No Break off, the Default character -/// direction and the Default digits, whether or not Show East Asian Options and Show Indic Options -/// are on. +/// character alignment, Proportional Metrics, Tate-chu-yoko, Standard Vertical Roman Alignment and +/// No Break off, the Default character direction and the Default digits, whether or not Show East +/// Asian Options and Show Indic Options are on. fn reset_panel(app: &mut VectorcraftApp) { let d = CharStyle::default(); style(app, json!({"tracking": 0, "leading": "auto"})); @@ -1195,7 +1201,8 @@ fn reset_panel(app: &mut VectorcraftApp) { json!({ "kerning": "auto", "baselineShift": 0, "hScale": 100, "vScale": 100, "rotation": 0, "underline": false, "strikethrough": false, "allCaps": false, "smallCaps": d.small_caps.is_some(), "position": d.position.id(), "charAlign": d.char_align, - "proportionalMetrics": d.proportional_metrics, "tateChuYoko": d.tate_chu_yoko, "noBreak": d.no_break, "charDirection": "default", + "proportionalMetrics": d.proportional_metrics, "tateChuYoko": d.tate_chu_yoko, + "standardVerticalRoman": d.standard_vertical_roman, "noBreak": d.no_break, "charDirection": "default", "digits": d.digits }), ); diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 8f02228b5b..92809a2a49 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -526,6 +526,42 @@ fn tate_chu_yoko_menu_item_shows_with_east_asian_options_and_toggles() { assert!(!on(&app)); } +/// Standard Vertical Roman Alignment is in the panel menu with the East Asian options. Choosing it +/// marks the selected characters, one undo step each way; its check shows only while every +/// selected character has it, and a mixed selection turns it on. +#[test] +fn standard_vertical_roman_alignment_menu_item_toggles() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "ABC"})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let ctx = egui::Context::default(); + let label = "Standard Vertical Roman Alignment"; + assert!(!crate::tests_labels::painted_text(&mut app, menu).contains(label)); + app.session.prefs.show_east_asian_options = true; + let on = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().all(|r| r.style.standard_vertical_roman), + _ => panic!("text"), + }; + // Only the first letter has it: the item is unchecked. + app.session.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 1, "standardVerticalRoman": true})).unwrap(); + let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let before = undo(&app); + assert!(!on(&app)); + assert!(!crate::tests_labels::painted_text(&mut app, menu).contains(&format!("✓ {label}"))); + let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], menu); + let at = texts.iter().find(|(t, _)| t.trim_start_matches(['✓', ' ']) == label).unwrap_or_else(|| panic!("{texts:?}")).1; + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + assert!(on(&app)); + assert_eq!(undo(&app), before + 1); + assert!(crate::tests_labels::painted_text(&mut app, menu).contains(&format!("✓ {label}"))); + let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], menu); + let at = texts.iter().find(|(t, _)| t.trim_start_matches(['✓', ' ']) == label).unwrap().1; + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + assert!(!on(&app)); + assert_eq!(undo(&app), before + 2); +} + /// Digits is in the panel menu with the Middle Eastern (Indic) options only, as Paragraph /// Direction is in the Paragraph panel. #[test] @@ -715,6 +751,7 @@ fn reset_panel_resets_every_attribute_but_the_font() { s.char_align != d.char_align, s.proportional_metrics != d.proportional_metrics, s.tate_chu_yoko != d.tate_chu_yoko, + s.standard_vertical_roman != d.standard_vertical_roman, s.no_break != d.no_break, s.char_direction != d.char_direction, s.digits != d.digits, @@ -726,17 +763,17 @@ fn reset_panel_resets_every_attribute_but_the_font() { json!({ "id": id, "tracking": 50, "leading": 30, "kerning": 20, "baselineShift": 3, "hScale": 120, "vScale": 90, "rotation": 15, "underline": true, "strikethrough": true, "allCaps": true, "smallCaps": true, "position": "superscript", - "charAlign": "emBoxCenter", "proportionalMetrics": true, "tateChuYoko": true, "noBreak": true, - "charDirection": "rightToLeft", "digits": "hindi" + "charAlign": "emBoxCenter", "proportionalMetrics": true, "tateChuYoko": true, "standardVerticalRoman": true, + "noBreak": true, "charDirection": "rightToLeft", "digits": "hindi" }), ) .unwrap(); }; let plain = runs(&app)[0].1.clone(); - assert_eq!(differs(&plain, &CharStyle::default()), [false; 18]); + assert_eq!(differs(&plain, &CharStyle::default()), [false; 19]); custom(&mut app); let styled = runs(&app)[0].1.clone(); - assert_eq!(differs(&styled, &CharStyle::default()), [true; 18]); + assert_eq!(differs(&styled, &CharStyle::default()), [true; 19]); app.run("select.set", json!({"ids": [id]})).unwrap(); reset_panel(&mut app); assert_eq!(runs(&app), [("One 12".to_string(), plain.clone())]); diff --git a/docs/mcp.md b/docs/mcp.md index e95d5d1826..799c2427c1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1147,7 +1147,7 @@ a key left out. These commands refuse a string, a number or another value that is not true or false with `` `closed` must be true or false ``, naming the key, and leave the document and its undo history as they were: `clockwise` in `shape.spiral`; `closed` in `shape.arc` and `path.create`; `vertical` and `placeholder` in `text.create` -and `text.createInPath`; `underline`, `strikethrough`, `allCaps`, `proportionalMetrics`, `tateChuYoko` and `noBreak` +and `text.createInPath`; `underline`, `strikethrough`, `allCaps`, `proportionalMetrics`, `tateChuYoko`, `standardVerticalRoman` and `noBreak` in `text.setRangeStyle`; `effective` in `text.getRange`; `on` in `type.opticalMarginAlignment`, `type.systemLayout` and `type.fractionalWidths`; `remove` and `overhang` in `type.ruby`; `expandInstances` in `symbol.delete`; `alt` in `symbol.spray` and `symbol.adjust`; `spot` and `global` in `swatch.new` and `swatch.edit`; `unlink` in diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9d6e87405a..8bf7e7c5cc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -888,6 +888,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a drag on the Tabs panel's ruler or a value typed in its X field moves a tab stop past another stop, the moved stop stays selected. The Tabs panel menu's Clear All Tabs (`text.tabs.clear`), Delete Tab and Repeat Tab (`text.tabs.set`) can be chosen while the panel's ruler shows tab stops. Delete Tab removes the stop selected on the ruler. Repeat Tab replaces the stops after the selected stop with up to 20 copies of it. The copies are spaced by the selected stop's distance from the stop before it, or from the paragraph's left indent when it is the first stop, and no copy is placed at 2,000 pt or beyond. Clear All Tabs removes every stop, so the default stops every ½ inch apply again. - **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian and Finnish also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). + Character panel menu › Standard Vertical Roman Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {standardVerticalRoman}`, off by default) stands the selected Latin letters, digits and other half-width characters upright one below the other in vertical type instead of rotating them ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); spaces keep their width, tate-chu-yoko blocks stay across the column, and Character Style Options gives it its own checkbox beside Character Alignment. - **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `<mask>` and PDF soft masks. The constant alpha soft mask that PDF and `.ai` export draw a CMYK page with transparency through is white, so applications that read every soft mask by its luminosity show the page too (#1359, part of #1286). Isolation mode and opacity mask editing exclude each other ([transparency and blending modes](https://web.archive.org/web/20230102045151/https://helpx.adobe.com/illustrator/using/transparency-blending-modes.html)): in isolation mode a click or Alt-click on the mask thumbnail does not edit the mask, and Make Mask is off for one object; while a mask is edited, Enter Isolation Mode and Object › Perspective › Edit Text are off, the Contextual Task Bar leaves out Isolate, and Quick Actions leave out Isolate Group. Pattern editing mode and opacity mask editing exclude each other, by a rule of VectorCraft itself: in pattern editing mode a click or Alt-click on the mask thumbnail does not edit the mask, and Make Mask is off for one object; while a mask is edited, Object › Pattern › Make and Edit Pattern are off. diff --git a/docs/type-parity.md b/docs/type-parity.md index 50f4e44bce..0b7384d65a 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -59,6 +59,7 @@ against Illustrator's public documentation; **estimated** unless noted. | CJK: kinsoku (Hard, Soft, None), Line-end Punctuation Half Width, tate-chu-yoko (auto) | done / partial | custom kinsoku sets, the Mojikumi Settings dialog and the other mojikumi sets missing | | CJK: Proportional Metrics (`palt` in horizontal type, `vpal` in vertical type) | done | #966 | | CJK: manual tate-chu-yoko | done | Character panel menu › Tate-chu-yoko (`text.setFormat` / `text.setRangeStyle {tateChuYoko}`), with Show East Asian Options: marked characters stand side by side across one em of a vertical column, squeezed to the em when wider; two or three half-width digits still do so without the mark; horizontal type keeps the mark and does not move them. Up/Down and Left/Right settings remain. Evidence: `tests_vertical::manual_tate_chu_yoko_sets_marked_characters_across_one_em`, `typecmd::tate_chu_yoko_is_a_character_attribute_saved_only_when_on` | +| CJK: Standard Vertical Roman Alignment | done | Character panel menu › Standard Vertical Roman Alignment (`text.setFormat` / `text.setRangeStyle {standardVerticalRoman}`), with Show East Asian Options, off by default: in vertical type the marked half-width characters (Latin letters, digits and other characters that would lie on their side) stand upright one below the other, each in its upright cell; spaces keep their width and tate-chu-yoko blocks stay across the column; horizontal type keeps the mark and does not change. Character Style Options has its own checkbox for it. Evidence: `tests_vertical::standard_vertical_roman_alignment_stands_half_width_characters_upright`, `typecmd::standard_vertical_roman_is_a_character_attribute_saved_only_when_on` | | CJK: ruby, manual tate-chu-yoko | partial | ruby (ふりがな) for live text (`type.ruby`): a reading over a byte range, above (right of the column in vertical type) or below, start/centre/end alignment, size, overhang or squeeze; saved natively, laid out with its line growing, drawn on the canvas, in SVG and PDF (as outlines where ruby is present), in EPS, EMF/WMF and legacy `.ai` (legacy `.ai` writes type with ruby as outlines), and kept by Create Outlines, Expand Appearance and flattening, each glyph where the layout puts it (`typecmd::ruby_tests::create_outlines_keeps_the_ruby_where_it_is_laid_out`); manual tate-chu-yoko missing | #633 | | Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Serbian: Cyrillic, Serbian: Latin and Croatian); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). Not yet: hyphenation and spelling by it, `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set` | | No Break | done | Character panel menu (`text.setFormat` / `text.setRangeStyle {noBreak}`): the marked characters stay on one line, including across a space; a run that does not fit after earlier text moves together, and a run longer than the line stays together. Evidence: `layout::wrapping_tests::no_break_keeps_marked_characters_on_one_line`, `tests::no_break_keeps_marked_words_on_one_line`, `typecmd::no_break_is_a_character_attribute_saved_only_when_on` | From f07b9ab76545e274f02e5621e7bc09007c23fe68 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 17:51:55 -0700 Subject: [PATCH 235/260] Live Paint: Live Paint Bucket Options set what a click paints and the highlight Double-clicking the Live Paint Bucket did nothing, and the tool always filled on a click, stroked on Shift-click and highlighted in red at 4 px. It now opens Live Paint Bucket Options with Paint Fills, Paint Strokes, Highlight, Color and Width. - Paint Fills (on) and Paint Strokes (off) set what a click paints. With Paint Strokes alone, a click strokes the edge within 4 px of the pointer. With both on, a click strokes an edge within 4 px and otherwise fills the face. With both off, a click paints nothing. - Shift switches Paint Fills alone to Paint Strokes alone and back, and switches both to Paint Fills alone. With the defaults, Shift-click strokes the edge as before. - Highlight turns the outline of the face or edge under the pointer on or off; Color (a layer color or a custom color) and Width (1 to 20 px) set it. With Paint Strokes alone, a selection of ordinary paths no longer highlights a region, since a click there paints nothing. - The options are tool options (tool.setOption {tool: "livePaintBucket"}): they last across tool switches and are saved with the preferences. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/tools/src/builder.rs | 2 +- crates/tools/src/builder/live_paint.rs | 129 +++++++++++++-- crates/tools/src/builder/tests.rs | 100 ++++++++++++ crates/tools/src/settings.rs | 2 + crates/ui-egui/src/dialogs.rs | 2 + .../ui-egui/src/dialogs/live_paint_bucket.rs | 151 ++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/bs.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/toolbar.rs | 2 + docs/mcp.md | 9 ++ docs/target-app-parity.md | 1 + 36 files changed, 460 insertions(+), 18 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/live_paint_bucket.rs diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index 5903ac5b3d..2e6164a4cb 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -36,7 +36,7 @@ use cache::RegionCache; #[cfg(test)] use live_paint::LpHover; use live_paint::lp_color; -pub use live_paint::{LP_SELECT_WIDTH, LP_SELECT_WIDTH_RANGE, LivePaintBucketTool, LivePaintSelectionTool}; +pub use live_paint::{LP_BUCKET_WIDTH, LP_BUCKET_WIDTH_RANGE, LP_SELECT_WIDTH, LP_SELECT_WIDTH_RANGE, LivePaintBucketTool, LivePaintSelectionTool}; pub use lookup::{ EDGE_NAME, FACE_NAME, Face, LIVE_PAINT_NAME, LIVE_PAINT_PREFIX, SOURCES_NAME, builder_members, drawn_outlines, edge_near, edges, face_at, faces, is_live_paint, leaf_shapes, live_paint_at, live_paint_takes, node_outline, outline_snap, path_contains, shape_builder_shapes, shapes_for, diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index 7265122c3c..4d201acc92 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -86,20 +86,91 @@ fn lp_overlays(h: &LpHover, cache: &RegionCache, color: [u8; 3], width: f32) -> } } -/// Live Paint Bucket: click fills the face under the cursor with the current fill; Shift-click -/// paints the nearest edge with the current stroke. Alt-click samples a fill or stroke into the -/// paint defaults; Alt+Shift-click samples only the color under the pointer. Clicking selected -/// ordinary paths without Alt makes them a Live Paint group first. +/// The Live Paint Bucket's highlight width (screen pixels) by default. +pub const LP_BUCKET_WIDTH: f64 = 4.0; + +/// The least and greatest highlight width (screen pixels) the Live Paint Bucket takes. +pub const LP_BUCKET_WIDTH_RANGE: (f64, f64) = (1.0, 20.0); + +/// What a Live Paint Bucket click paints. +#[derive(Clone, Copy, Debug, PartialEq)] +enum LpPaint { + Nothing, + /// The face under the pointer. + Fills, + /// The edge nearest the pointer. + Strokes, + /// The edge nearest the pointer when one is in reach, else the face under the pointer. + Both, +} + +/// Live Paint Bucket: by default, a click fills the face under the cursor with the current fill, +/// and Shift-click paints the nearest edge with the current stroke. Alt-click samples a fill or +/// stroke into the paint defaults; Alt+Shift-click samples only the color under the pointer. +/// Clicking selected ordinary paths without Alt makes them a Live Paint group first. Its Tool +/// Options (double-click the tool) are `paintFills` (on) and `paintStrokes` (off), `highlight` +/// (on), the highlight `color` (`#rrggbb`, red by default) and its `width` ([`LP_BUCKET_WIDTH`] +/// pixels). With Paint Strokes alone on, a click paints the edge nearest the pointer and +/// Shift-click fills the face. With both on, a click paints the edge nearest the pointer when one +/// is within 4 pixels, else it fills the face, and Shift-click fills the face. With both off, a +/// click paints nothing. With Highlight off, the face or edge under the pointer is not +/// highlighted. pub struct LivePaintBucketTool { pub(super) cache: RegionCache, pub(super) hover: LpHover, /// Where the pointer last moved, and whether Shift and Alt were held. at: Option<(Point, bool, bool)>, + fills: bool, + strokes: bool, + highlight: bool, + color: [u8; 3], + width: f64, } impl Default for LivePaintBucketTool { fn default() -> Self { - Self { cache: RegionCache::live_paint(), hover: LpHover::None, at: None } + Self { + cache: RegionCache::live_paint(), + hover: LpHover::None, + at: None, + fills: true, + strokes: false, + highlight: true, + color: HIGHLIGHT_RED, + width: LP_BUCKET_WIDTH, + } + } +} + +impl LivePaintBucketTool { + /// What a click paints, Shift held or not. Shift switches Paint Fills alone to Paint Strokes + /// alone and back, and switches both to Paint Fills alone. + fn paints(&self, shift: bool) -> LpPaint { + match (self.fills, self.strokes, shift) { + (false, false, _) => LpPaint::Nothing, + (true, true, false) => LpPaint::Both, + (true, false, false) | (_, true, true) => LpPaint::Fills, + (true, false, true) | (false, true, false) => LpPaint::Strokes, + } + } + + /// The highlight at `p` for a pointer with Shift and Alt held as given: none with Alt or with + /// Highlight off, else the face or edge a click there paints. + fn hover_at(&mut self, cx: &ToolContext, p: Point, shift: bool, alt: bool) -> LpHover { + if alt || !self.highlight { + return LpHover::None; + } + let takes = |id| lp_visible(cx, id); + match self.paints(shift) { + LpPaint::Nothing => LpHover::None, + LpPaint::Fills => lp_hover(cx, Some(&mut self.cache), p, false, &takes), + // A click paints no region of the selection, so none is highlighted. + LpPaint::Strokes => lp_hover(cx, None, p, true, &takes), + LpPaint::Both => match lp_part_at(cx.doc, p, cx.tol(4.0), true, &takes) { + Some((_, Some(e))) => e.path_data().map(|pd| LpHover::Part(pd.to_bezpath())).unwrap_or_default(), + _ => lp_hover(cx, Some(&mut self.cache), p, false, &takes), + }, + } } } @@ -113,8 +184,7 @@ impl Tool for LivePaintBucketTool { match ev.kind { PointerKind::Move => { self.at = Some((p, ev.mods.shift, ev.mods.alt)); - self.hover = - if ev.mods.alt { LpHover::None } else { lp_hover(cx, Some(&mut self.cache), p, ev.mods.shift, &|id| lp_visible(cx, id)) }; + self.hover = self.hover_at(cx, p, ev.mods.shift, ev.mods.alt); vec![] } PointerKind::Down => { @@ -142,13 +212,14 @@ impl Tool for LivePaintBucketTool { }); } let point = json!([p.x, p.y]); - if ev.mods.shift { - return match lp_part_at(cx.doc, p, cx.tol(4.0), true, &|id| lp_visible(cx, id)) { - Some((g, Some(_))) => { - vec![Action::Exec("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": point, "tolerance": cx.tol(4.0) }))] - } - _ => vec![], - }; + let paint = self.paints(ev.mods.shift); + if matches!(paint, LpPaint::Strokes | LpPaint::Both) + && let Some((g, Some(_))) = lp_part_at(cx.doc, p, cx.tol(4.0), true, &|id| lp_visible(cx, id)) + { + return vec![Action::Exec("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": point, "tolerance": cx.tol(4.0) }))]; + } + if !matches!(paint, LpPaint::Fills | LpPaint::Both) { + return vec![]; } if let Some(g) = live_paint_at(cx.doc, p) { return vec![Action::Exec("livePaint.fill".into(), json!({ "group": g.0, "point": point }))]; @@ -164,13 +235,39 @@ impl Tool for LivePaintBucketTool { } fn overlays(&self, _cx: &ToolContext) -> Vec<Overlay> { - lp_overlays(&self.hover, &self.cache, HIGHLIGHT_RED, 4.0) + lp_overlays(&self.hover, &self.cache, self.color, self.width as f32) } fn cursor(&self, _cx: &ToolContext, _p: Point, m: Mods) -> Cursor { if m.alt { Cursor::Eyedropper } else { Cursor::LivePaintBucket } } + fn options(&self) -> Value { + let [r, g, b] = self.color; + json!({ + "paintFills": self.fills, + "paintStrokes": self.strokes, + "highlight": self.highlight, + "color": format!("#{r:02x}{g:02x}{b:02x}"), + "width": self.width, + }) + } + + fn set_option(&mut self, key: &str, v: &Value) { + match key { + "paintFills" => self.fills = v.as_bool().unwrap_or(self.fills), + "paintStrokes" => self.strokes = v.as_bool().unwrap_or(self.strokes), + "highlight" => self.highlight = v.as_bool().unwrap_or(self.highlight), + "color" => self.color = lp_color(v).unwrap_or(self.color), + "width" => { + let (min, max) = LP_BUCKET_WIDTH_RANGE; + self.width = v.as_f64().filter(|w| w.is_finite()).map_or(self.width, |w| w.clamp(min, max)); + } + _ => return, + } + self.hover = LpHover::None; + } + fn waiting(&self) -> bool { self.cache.waiting() } @@ -184,7 +281,7 @@ impl Tool for LivePaintBucketTool { loop { self.cache.settle(wait); if let Some((p, shift, alt)) = self.at { - self.hover = if alt { LpHover::None } else { lp_hover(cx, Some(&mut self.cache), p, shift, &|id| lp_visible(cx, id)) }; + self.hover = self.hover_at(cx, p, shift, alt); } if !wait || !self.cache.waiting() { break; diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index f4a8b771fc..9bfc411bfc 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -765,6 +765,106 @@ fn bucket_click_fills_face_and_shift_click_strokes_edge() { assert_eq!(id, "livePaint.strokeEdge"); } +#[test] +fn bucket_options_choose_what_a_click_paints() { + let (d, gid, ..) = live_group_doc(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Default::default() }; + let fill = |x: f64| vec![Action::Exec("livePaint.fill".into(), json!({ "group": gid.0, "point": [x, 25.0] }))]; + let stroke = |x: f64| vec![Action::Exec("livePaint.strokeEdge".into(), json!({ "group": gid.0, "point": [x, 25.0], "tolerance": 4.0 }))]; + let click = |t: &mut LivePaintBucketTool, x: f64, m: Mods| t.pointer(&cx, &ev(PointerKind::Down, x, 25.0).with_mods(m)); + let hovered = |t: &mut LivePaintBucketTool, x: f64, m: Mods| { + t.pointer(&cx, &ev(PointerKind::Move, x, 25.0).with_mods(m)); + match t.overlays(&cx).as_slice() { + [] => None, + [Overlay::Path { path, .. }] => Some(path.bounding_box()), + ov => panic!("{ov:?}"), + } + }; + let (face, edge) = (Some(Rect::new(50.0, 0.0, 100.0, 50.0)), Some(Rect::new(50.0, 0.0, 50.0, 50.0))); + let mut t = LivePaintBucketTool::default(); + assert_eq!(t.options(), json!({"paintFills": true, "paintStrokes": false, "highlight": true, "color": "#ff2a2a", "width": 4.0})); + // Paint Fills alone: 1 pt from the edge, a click fills the face and Shift-click strokes the edge. + assert_eq!((click(&mut t, 51.0, Mods::default()), hovered(&mut t, 51.0, Mods::default())), (fill(51.0), face)); + assert_eq!((click(&mut t, 51.0, shift), hovered(&mut t, 51.0, shift)), (stroke(51.0), edge)); + // Paint Strokes alone: a click strokes the edge in reach and paints nothing farther away; + // Shift-click fills the face. + t.set_option("paintFills", &json!(false)); + t.set_option("paintStrokes", &json!(true)); + assert_eq!((click(&mut t, 51.0, Mods::default()), hovered(&mut t, 51.0, Mods::default())), (stroke(51.0), edge)); + assert_eq!((click(&mut t, 75.0, Mods::default()), hovered(&mut t, 75.0, Mods::default())), (vec![], None)); + assert_eq!((click(&mut t, 51.0, shift), hovered(&mut t, 51.0, shift)), (fill(51.0), face)); + // Both: a click strokes the edge in reach, else fills the face; Shift-click fills the face. + t.set_option("paintFills", &json!(true)); + assert_eq!((click(&mut t, 51.0, Mods::default()), hovered(&mut t, 51.0, Mods::default())), (stroke(51.0), edge)); + assert_eq!((click(&mut t, 75.0, Mods::default()), hovered(&mut t, 75.0, Mods::default())), (fill(75.0), face)); + assert_eq!((click(&mut t, 51.0, shift), hovered(&mut t, 51.0, shift)), (fill(51.0), face)); + // Both off: nothing is painted or highlighted. + t.set_option("paintFills", &json!(false)); + t.set_option("paintStrokes", &json!(false)); + for m in [Mods::default(), shift] { + assert_eq!((click(&mut t, 51.0, m), hovered(&mut t, 51.0, m)), (vec![], None)); + } + // A value that is not true or false is ignored. + t.set_option("paintFills", &json!("yes")); + assert_eq!(t.options()["paintFills"], false); +} + +#[test] +fn bucket_strokes_alone_paints_and_highlights_no_region_of_the_selection() { + let (d, a, b) = two_rects(); + let mut s = Selection::default(); + s.set([a, b]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = LivePaintBucketTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, 75.0, 50.0)); + t.poll(&cx, true); + assert!(!t.overlays(&cx).is_empty(), "Paint Fills highlights the region"); + t.set_option("paintFills", &json!(false)); + t.set_option("paintStrokes", &json!(true)); + t.pointer(&cx, &ev(PointerKind::Move, 75.0, 50.0)); + t.poll(&cx, true); + assert!(t.overlays(&cx).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)).is_empty()); +} + +#[test] +fn bucket_options_set_the_highlight() { + let (d, ..) = live_group_doc(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = LivePaintBucketTool::default(); + let highlight = |t: &mut LivePaintBucketTool| { + t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0)); + match t.overlays(&cx).as_slice() { + [] => None, + [Overlay::Path { color, width, .. }] => Some((*color, *width)), + ov => panic!("{ov:?}"), + } + }; + assert_eq!(highlight(&mut t), Some((HIGHLIGHT_RED, 4.0))); + t.set_option("color", &json!("#00FF00")); + t.set_option("width", &json!(9)); + assert_eq!(highlight(&mut t), Some(([0, 0xff, 0], 9.0))); + t.set_option("color", &json!("light blue")); + t.set_option("width", &json!("wide")); + assert_eq!(highlight(&mut t), Some(([0x4f, 0x80, 0xff], 9.0))); + t.set_option("width", &json!(100)); + assert_eq!(t.options()["width"], json!(LP_BUCKET_WIDTH_RANGE.1)); + t.set_option("width", &json!(0)); + assert_eq!(t.options()["width"], json!(LP_BUCKET_WIDTH_RANGE.0)); + // Highlight off: nothing is highlighted, and a click still paints. + t.set_option("highlight", &json!(false)); + assert_eq!(highlight(&mut t), None); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0)).len(), 1); + t.set_option("highlight", &json!(true)); + assert!(highlight(&mut t).is_some()); +} + #[test] fn bucket_alt_samples_face_edge_and_selected_region_without_painting() { let (mut d, _gid, face, edge) = live_group_doc(); diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 1e94c6d2c4..e7b9f9a5c4 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -45,6 +45,8 @@ const ROWS: &[Row] = &[ (&["blobBrush", "eraser"], None, &["angle", "roundness"]), // Live Paint Selection Tool Options (`builder::LivePaintSelectionTool`). (&["livePaintSelection"], None, &["selectFills", "selectStrokes", "color", "width"]), + // Live Paint Bucket Options (`builder::LivePaintBucketTool`). + (&["livePaintBucket"], None, &["paintFills", "paintStrokes", "highlight", "color", "width"]), (&["polygon"], None, &["sides"]), (&["star"], None, &["points"]), (&["freeTransform"], None, &["constrain"]), diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index b0210026a9..0e9f7b75f1 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -56,6 +56,7 @@ pub mod justification; pub mod layer_options; pub mod layers_panel_options; pub mod liquify; +pub mod live_paint_bucket; pub mod live_paint_gaps; pub mod live_paint_selection; pub mod missing_fonts; @@ -389,6 +390,7 @@ registry! { BlendOptions: [blend_options::KIND] => blend_options::SPEC, LivePaintGaps: [live_paint_gaps::KIND] => live_paint_gaps::SPEC, LivePaintSelectionOptions: [live_paint_selection::KIND] => live_paint_selection::SPEC, + LivePaintBucketOptions: [live_paint_bucket::KIND] => live_paint_bucket::SPEC, BrushOptions: [brush_options::KIND] => brush_options::SPEC, NewBrush: [new_brush::KIND] => new_brush::SPEC, EditSelection: [edit_selection::KIND] => edit_selection::SPEC, diff --git a/crates/ui-egui/src/dialogs/live_paint_bucket.rs b/crates/ui-egui/src/dialogs/live_paint_bucket.rs new file mode 100644 index 0000000000..550b235348 --- /dev/null +++ b/crates/ui-egui/src/dialogs/live_paint_bucket.rs @@ -0,0 +1,151 @@ +//! Live Paint Bucket Options (double-click the Live Paint Bucket tool): what a click with the tool +//! paints and how the face or edge under the pointer highlights. The options last across tool +//! switches and are saved with the preferences. OK sets them with +//! `tool.setOption {tool: "livePaintBucket", values}`. +//! +//! Fields: `paintFills` and `paintStrokes` (the faces and the edges of Live Paint groups), +//! `highlight` (whether the face or edge under the pointer is outlined), `color` (the highlight +//! color: `#rrggbb`, or a layer color's name such as "Red") and `width` (the highlight's width in +//! screen pixels). + +use serde_json::{Map, Value, json}; +use vectorcraft_color::Color; +use vectorcraft_doc::LAYER_COLORS; +use vectorcraft_tools::builder::LP_BUCKET_WIDTH_RANGE; + +use super::tile_edge_color::resolve; +use super::{DialogSpec, form, run_and_close}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of the Live Paint Bucket Options. +pub const KIND: &str = "livePaintBucketOptions"; + +/// The tool the dialog serves. +const TOOL: &str = "livePaintBucket"; + +/// The options the dialog edits. +const KEYS: [&str; 5] = ["paintFills", "paintStrokes", "highlight", "color", "width"]; + +/// Width of the label column. +const LABEL_W: f32 = 60.0; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 300.0, ..DialogSpec::FORM }; + +fn heading(_: &Dialog) -> String { + let label = vectorcraft_tools::tool_info(TOOL).map_or("", |t| t.label); + crate::i18n::fmt(tl!("{tool} Options"), &[("tool", tl!(label))]) +} + +/// Open the Live Paint Bucket Options with the tool's current values. +pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> { + let o = app.session.tool_options_of(TOOL); + let fields: Map<String, Value> = KEYS.iter().filter_map(|key| Some((key.to_string(), o.get(*key)?.clone()))).collect(); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + Ok(json!({ "dialog": KIND })) +} + +fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + form::check(ui, d, "paintFills", tl!("Paint Fills")); + form::check(ui, d, "paintStrokes", tl!("Paint Strokes")); + ui.add_space(6.0); + form::check(ui, d, "highlight", tl!("Highlight")); + let color = resolve(&d.str("color")).unwrap_or(Color::BLACK); + let [r, g, b, _] = color.to_rgba8(1.0); + let preset = LAYER_COLORS.iter().position(|(_, c)| *c == [r, g, b]); + let names: Vec<&str> = LAYER_COLORS.iter().map(|(n, _)| *n).chain(["Custom"]).collect(); + ui.add_enabled_ui(d.bool("highlight"), |ui| { + widgets::label_row(ui, tl!("Color:"), LABEL_W, |ui| { + if let Some((_, [r, g, b])) = + widgets::dropdown(ui, "lp-bucket-color", names[preset.unwrap_or(LAYER_COLORS.len())], &names, 130.0).and_then(|i| LAYER_COLORS.get(i)) + { + d.fields.insert("color".into(), json!(Color::rgb8(*r, *g, *b).to_hex())); + } + // The color button sets any other color; the dropdown then shows Custom. + let mut rgb = [r, g, b]; + if ui.color_edit_button_srgb(&mut rgb).changed() { + d.fields.insert("color".into(), json!(Color::rgb8(rgb[0], rgb[1], rgb[2]).to_hex())); + } + }); + let (min, max) = LP_BUCKET_WIDTH_RANGE; + let v = d.f64("width", min); + widgets::label_row(ui, tl!("Width:"), LABEL_W, |ui| { + if let Some(x) = widgets::range_field(ui, "lp-bucket-width", v, min..=max, "px", 0, 72.0) { + d.fields.insert("width".into(), json!(x)); + } + }); + }); + false +} + +/// OK: set the tool's options. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { + let values: Map<String, Value> = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); + run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + use vectorcraft_tools::{Overlay, PointerEvent, PointerKind}; + + /// The labels the open dialog paints. + fn painted(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + } + + #[test] + fn double_clicking_the_tool_opens_its_options_and_ok_sets_them() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + // Two squares side by side, made a Live Paint group: two faces and the edge between them. + for x in [0, 100] { + app.run("shape.rectangle", json!({"x": 50 + x, "y": 50, "width": 100, "height": 100})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + app.run("livePaint.make", json!({})).unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + app.select_tool(TOOL); + let hover = |app: &mut VectorcraftApp, x: f64| { + let view = app.view_info(); + crate::canvas::dispatch(app, &PointerEvent::new(PointerKind::Move, x, 100.0), view); + app.session.overlays(view) + }; + let ov = hover(&mut app, 151.0); + assert!(ov.iter().any(|o| matches!(o, Overlay::Path { color: [0xff, 0x2a, 0x2a], width: 4.0, .. })), "{ov:?}"); + + crate::toolbar::open_options(&mut app, TOOL).unwrap(); + let text = painted(&mut app); + for label in ["Live Paint Bucket Options", "Paint Fills", "Paint Strokes", "Highlight", "Color:", "Width:"] { + assert!(text.contains(label), "{label} in {text}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.kind, KIND); + assert_eq!( + (d.bool("paintFills"), d.bool("paintStrokes"), d.bool("highlight"), d.str("color"), d.f64("width", 0.0)), + (true, false, true, "#ff2a2a".to_string(), 4.0) + ); + d.fields.insert("paintFills".into(), json!(false)); + d.fields.insert("paintStrokes".into(), json!(true)); + d.fields.insert("color".into(), json!("Green")); + d.fields.insert("width".into(), json!(8)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + // The tool takes them: by the edge, the edge highlights in the new color and width. + let ov = hover(&mut app, 151.0); + assert!(ov.iter().any(|o| matches!(o, Overlay::Path { color: [0x4f, 0xff, 0x4f], width: 8.0, .. })), "{ov:?}"); + // They last while another tool is chosen, and the dialog opens on them again. + app.select_tool("selection"); + let o = app.session.tool_options_of(TOOL); + assert_eq!((o["paintFills"].as_bool(), o["paintStrokes"].as_bool(), o["color"].as_str()), (Some(false), Some(true), Some("#4fff4f"))); + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((d.bool("paintStrokes"), d.str("color")), (true, "#4fff4f".to_string())); + // Highlight off: the tool outlines nothing under the pointer. + d.fields.insert("highlight".into(), json!(false)); + super::super::confirm(&mut app).unwrap(); + app.select_tool(TOOL); + assert!(!hover(&mut app, 151.0).iter().any(|o| matches!(o, Overlay::Path { .. }))); + } +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index f2389f4b81..b3bc7e8601 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1230,6 +1230,9 @@ font-technology Variable Променливи Hide Live Paint Gaps Скриване на пролуките на динамичното оцветяване Select Fills Избиране на запълвания Select Strokes Избиране на щрихове + Paint Fills Боядисване на запълвания + Paint Strokes Боядисване на щрихове + Highlight Маркиране Gaussian Blur… Гаусово размазване… General Общи General › Placement › X Общи › Разположение › X diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 2e9b5fd554..aaa5ec00f6 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -267,6 +267,9 @@ Hide Live Paint Gaps Sakrij praznine živog bojenja Select Fills Odaberi ispune Select Strokes Odaberi poteze + Paint Fills Boji ispune + Paint Strokes Boji poteze + Highlight Isticanje Image Trace Praćenje slike Image Trace (Make and Expand) Praćenje slike (napravi i proširi) Release Image Trace Oslobodi praćenje slike diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 0c2238de16..5e309464e9 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1859,6 +1859,7 @@ digits Malayalam Malaiàlam High Quality Print Impressió d’alta qualitat High Resolution Alta resolució High resolution Alta resolució + Highlight Ressaltat Highlight Alternate Glyphs Ressalta els glifs alternatius Highlight anchors on mouse over Ressalta els punts d’ancoratge en passar el ratolí Highlight Area Ressalta l’àrea @@ -2844,8 +2845,10 @@ digits Malayalam Malaiàlam Pages Pàgines Paint Daubs Taques de pintura Paint Daubs… Taques de pintura… + Paint Fills Pinta els farciments Paint Opacity: Opacitat de pintura: Paint Stops At: La pintura s’atura a: + Paint Strokes Pinta els traços Paintbrush Pinzell Paintbrush Tool Eina de pinzell Palette Knife Espàtula diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index d8d77feefb..700dcf26d3 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -277,6 +277,9 @@ Hide Live Paint Gaps Skrýt mezery živé malby Select Fills Vybírat výplně Select Strokes Vybírat tahy + Paint Fills Malovat výplně + Paint Strokes Malovat tahy + Highlight Zvýraznění Image Trace Vektorizace obrazu Image Trace (Make and Expand) Vektorizace obrazu (vytvořit a rozložit) Release Image Trace Uvolnit vektorizaci obrazu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 7a1740223a..b4cb18ce09 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5312,6 +5312,9 @@ swatch Bright Violet Kraftig violet Close Gaps With Paths Luk huller med stier Select Fills Markér udfyldninger Select Strokes Markér konturer + Paint Fills Mal udfyldninger + Paint Strokes Mal konturer + Highlight Fremhævning Column Type: Søjletype: Each Design Represents: Hvert design repræsenterer: Event: Hændelse: diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 48e587d88c..0f9001fa40 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1254,6 +1254,9 @@ file-filter Templates Vorlagen Hide Live Paint Gaps Lücken beim interaktiven Malen ausblenden Select Fills Flächen auswählen Select Strokes Konturen auswählen + Paint Fills Flächen malen + Paint Strokes Konturen malen + Highlight Hervorheben Gaussian Blur… Gaußscher Weichzeichner… General Allgemein General › Placement › X Allgemein › Platzierung › X diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bec866697a..931624d4d4 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1196,6 +1196,9 @@ font-technology Variable Μεταβλητές Hide Live Paint Gaps Απόκρυψη διακένων δυναμικής βαφής Select Fills Επιλογή γεμισμάτων Select Strokes Επιλογή περιγραμμάτων + Paint Fills Βαφή γεμισμάτων + Paint Strokes Βαφή περιγραμμάτων + Highlight Επισήμανση Gaussian Blur… Θόλωση Γκάους… General Γενικά General › Placement › X Γενικά › Τοποθέτηση › X diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index d5a6640298..7bb969e1bf 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1267,6 +1267,9 @@ font-technology Variable Variables Hide Live Paint Gaps Ocultar huecos de pintura interactiva Select Fills Seleccionar rellenos Select Strokes Seleccionar trazos + Paint Fills Pintar rellenos + Paint Strokes Pintar trazos + Highlight Resaltado Gaussian Blur… Desenfoque gaussiano… General General General › Placement › X General › Colocación › X diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index f1badd4853..a0017ed4d2 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -284,6 +284,9 @@ Hide Live Paint Gaps Piilota elävän maalauksen aukot Select Fills Valitse täytöt Select Strokes Valitse viivat + Paint Fills Maalaa täytöt + Paint Strokes Maalaa viivat + Highlight Korostus Image Trace Kuvan jäljitys Image Trace (Make and Expand) Kuvan jäljitys (luo ja laajenna) Release Image Trace Vapauta kuvan jäljitys diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index be6e4d1ae0..a4c3483b79 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1267,6 +1267,9 @@ font-technology Variable Variables Hide Live Paint Gaps Masquer les espaces de peinture dynamique Select Fills Sélectionner les fonds Select Strokes Sélectionner les contours + Paint Fills Peindre les fonds + Paint Strokes Peindre les contours + Highlight Mise en évidence Gaussian Blur… Flou gaussien… General Général General › Placement › X Général › Placement › X diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 7243f3dee4..c44637ba98 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1584,6 +1584,9 @@ file-filter Templates Sablonok Hide Live Paint Gaps Élő festés hézagainak elrejtése Select Fills Kitöltések kijelölése Select Strokes Körvonalak kijelölése + Paint Fills Kitöltések festése + Paint Strokes Körvonalak festése + Highlight Kiemelés Gaussian Blur Gauss-elmosás Gaussian Blur… Gauss-elmosás… General Általános diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 84e58c69be..e1b6202777 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5312,6 +5312,9 @@ swatch Bright Violet Violet cerah Close Gaps With Paths Tutup celah dengan jalur Select Fills Pilih isian Select Strokes Pilih stroke + Paint Fills Cat isian + Paint Strokes Cat stroke + Highlight Sorotan Column Type: Jenis kolom: Each Design Represents: Setiap desain mewakili: Event: Peristiwa: diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 6845ed74e1..77d8c0a202 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1277,6 +1277,9 @@ file-filter Templates Modelli Hide Live Paint Gaps Nascondi spazi vuoti pittura dinamica Select Fills Seleziona riempimenti Select Strokes Seleziona tracce + Paint Fills Colora riempimenti + Paint Strokes Colora tracce + Highlight Evidenziazione Gaussian Blur… Sfocatura gaussiana… General Generale General › Placement › X Generale › Posizionamento › X diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index cfe312e9e8..fea3338489 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -292,6 +292,9 @@ digits Malayalam マラヤーラム数字 Hide Live Paint Gaps ライブペイントの間隔を隠す Select Fills 塗りを選択 Select Strokes 線を選択 + Paint Fills 塗りをペイント + Paint Strokes 線をペイント + Highlight ハイライト Image Trace 画像トレース Image Tracing 画像トレースオブジェクト Tracing Presets トレースプリセット diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d6f951f6eb..586b59cc56 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5339,6 +5339,9 @@ imageTrace Outline კონტური Scale in Perspective პერსპექტივაში მასშტაბირება Select Fills შევსებების მონიშვნა Select Strokes კონტურების მონიშვნა + Paint Fills შევსებების შეღებვა + Paint Strokes კონტურების შეღებვა + Highlight გამოკვეთა Set History Limit… ისტორიის ლიმიტის დაყენება… Shape Builder Delete ფიგურების კონსტრუქტორით წაშლა Sliding სრიალა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 2df53a0989..05d5ed4e69 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -285,6 +285,9 @@ digits Malayalam 말라얄람어 Hide Live Paint Gaps 라이브 페인트 간격 숨기기 Select Fills 칠 선택 Select Strokes 선 선택 + Paint Fills 칠 페인트 + Paint Strokes 선 페인트 + Highlight 강조 표시 Image Trace 이미지 추적 Image Tracing 이미지 추적 Tracing Presets 추적 프리셋 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 0591d4042a..98a89cc6b7 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5323,6 +5323,9 @@ swatch Bright Violet Felviolet Close Gaps With Paths Openingen sluiten met paden Select Fills Vullingen selecteren Select Strokes Lijnen selecteren + Paint Fills Vullingen verven + Paint Strokes Lijnen verven + Highlight Markering Column Type: Kolomtype: Each Design Represents: Elk ontwerp staat voor: Event: Gebeurtenis: diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 6acc18ccfb..08ab910c42 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -242,6 +242,9 @@ Hide Live Paint Gaps Ukryj przerwy aktywnego malowania Select Fills Zaznaczaj wypełnienia Select Strokes Zaznaczaj obrysy + Paint Fills Maluj wypełnienia + Paint Strokes Maluj obrysy + Highlight Podświetlenie Image Trace Obrys obrazu Text Wrap Oblewanie tekstem Text Wrap Options… Opcje oblewania tekstem… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index f55b23cf29..4c8c885726 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1116,6 +1116,9 @@ Hide Live Paint Gaps Ocultar Lacunas da Pintura ao Vivo Select Fills Selecionar Preenchimentos Select Strokes Selecionar Traçados + Paint Fills Pintar Preenchimentos + Paint Strokes Pintar Traçados + Highlight Destaque Gaussian Blur… Desfoque Gaussiano… General Geral Generate CSS Gerar CSS diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 038c380a3f..d330e4ccc1 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1275,6 +1275,9 @@ file-filter Templates Шаблоны Hide Live Paint Gaps Скрыть зазоры быстрой заливки Select Fills Выделять заливки Select Strokes Выделять обводки + Paint Fills Рисовать заливки + Paint Strokes Рисовать обводки + Highlight Подсветка Gaussian Blur… Размытие по Гауссу… General Общие General › Placement › X Общие › Размещение › X diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 91c94e58e2..d18203ddfe 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1232,6 +1232,9 @@ font-technology Variable Variabla Hide Live Paint Gaps Dölj mellanrum i direktmålning Select Fills Markera fyllningar Select Strokes Markera konturer + Paint Fills Måla fyllningar + Paint Strokes Måla konturer + Highlight Framhävning Gaussian Blur… Gaussisk oskärpa… General Allmänt General › Placement › X Allmänt › Placering › X diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 43682accab..7bf6aa584d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5364,6 +5364,9 @@ theme Appearance Görünüm Overlap Örtüşme Select Fills Dolguları Seç Select Strokes Konturları Seç + Paint Fills Dolguları Boya + Paint Strokes Konturları Boya + Highlight Vurgulama Snap to Unit Birim Değerine Yasla The plug-in writes the whole document. Eklenti tüm belgeyi yazar. Attach İliştir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d6610c36b2..f4ed70ce24 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1271,6 +1271,9 @@ file-filter Templates Шаблони Hide Live Paint Gaps Приховати проміжки швидкої заливки Select Fills Виділяти заливки Select Strokes Виділяти обведення + Paint Fills Фарбувати заливки + Paint Strokes Фарбувати обведення + Highlight Підсвічування Gaussian Blur… Розмиття за Гауссом… General Загальні General › Placement › X Загальні › Розміщення › X diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5315376b90..82e7600d29 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1486,6 +1486,9 @@ file-filter Templates Mẫu Hide Live Paint Gaps Ẩn khoảng cách tô trực tiếp Select Fills Chọn vùng tô Select Strokes Chọn nét + Paint Fills Tô vùng tô + Paint Strokes Tô nét + Highlight Làm nổi bật Gaussian Blur Mờ Gaussian Gaussian Blur… Làm mờ Gaussian… General Chung diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 156b250848..9cba58ad33 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1215,6 +1215,9 @@ file-filter Templates 模板 Hide Live Paint Gaps 隐藏实时上色间隙 Select Fills 选择填色 Select Strokes 选择描边 + Paint Fills 为填色上色 + Paint Strokes 为描边上色 + Highlight 突出显示 Gaussian Blur… 高斯模糊… General 常规 General › Placement › X 一般 › 位置 › X diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 33406bd06c..ec99ae2e2b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1241,6 +1241,9 @@ file-filter Templates 範本 Hide Live Paint Gaps 隱藏即時上色間隙 Select Fills 選取填色 Select Strokes 選取筆畫 + Paint Fills 為填色上色 + Paint Strokes 為筆畫上色 + Highlight 強調顯示 Gaussian Blur… 高斯模糊… General 一般 General › Placement › X 一般 › 位置 › X diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 28642f0152..11f3424200 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -691,7 +691,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (pt), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (pt), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintBucket\", values}), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index a3bcaa83f8..5ab3e389e6 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -377,6 +377,8 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result<serde_json:: _ if crate::dialogs::freehand::TOOLS.contains(&tool) => crate::dialogs::freehand::open(app, tool), // The Live Paint Selection tool: its Tool Options (what a click selects, the highlight). "livePaintSelection" => crate::dialogs::live_paint_selection::open(app), + // The Live Paint Bucket: its options (what a click paints, the highlight). + "livePaintBucket" => crate::dialogs::live_paint_bucket::open(app), // The Symbolism tools: the brush they share. _ if vectorcraft_tools::settings::SYMBOLISM.contains(&tool) => Ok(crate::dialogs::symbolism_options::open(app, tool)), // The graph tools: Graph Type for the selected graph. diff --git a/docs/mcp.md b/docs/mcp.md index 799c2427c1..7acb9e5f41 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1701,6 +1701,15 @@ already walks Image Trace. Short agent entry points: release, and Escape between the press and the release removes the marquee so that the release runs nothing. The tool does not highlight or select the faces and edges of a Live Paint group that is locked, on a locked layer or on a locked artboard, or in isolation mode outside the isolated art. + The Live Paint Bucket's options (`tool.setOption {tool: "livePaintBucket", values}`; double-clicking the tool opens + them, dialog `livePaintBucketOptions`) are `paintFills` (on), `paintStrokes` (off), `highlight` (on), `color` (the + highlight color, `#rrggbb` or a layer color's name; `#ff2a2a`) and `width` (the highlight's width, 1 to 20 screen + pixels; 4). With `paintFills` alone on, a click runs `livePaint.fill` and Shift-click runs `livePaint.strokeEdge`. + With `paintStrokes` alone on, a click runs `livePaint.strokeEdge` on the edge within 4 screen pixels of the pointer, + or nothing when none is in reach, and Shift-click runs `livePaint.fill`. With both on, a click runs + `livePaint.strokeEdge` when an edge is within 4 screen pixels of the pointer and `livePaint.fill` otherwise, and + Shift-click runs `livePaint.fill`. With both off, a click runs nothing. With `highlight` off, the face or edge under + the pointer is not outlined. `livePaint.merge` keeps the bottom Live Paint group's id, name, lock, visibility, transparency, appearance, opacity mask and graphic style link. With a Live Paint group among the objects, `livePaint.make` adds the others to it as `livePaint.merge` does, and so does `livePaint.fill {ids}` when `point` is outside that group's faces. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8bf7e7c5cc..377dd2d87e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -928,6 +928,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Create Strokes uses exact squared Euclidean distances and Guo–Hall thinning in bounded per-blob crops. Maximal-disc pruning, split-crossing merges and degree-two joins simplify its skeleton graph. The whole-blob width rule and ink fitting remain; 46 code-drawn inputs measure ends and junctions in [`image-trace-quality.md`](image-trace-quality.md#centre-lines). Junction degrees measure 44/45 correct in each input variant; remaining spurs are recorded. This is a measured skeleton improvement; the Image Trace score, missing per-feature selection and width controls, and estimates remain unchanged. Object › Live Paint › Merge adds the other selected paths and Live Paint groups to the bottom selected Live Paint group ([Live Paint groups](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/live-paint-groups.html)), which keeps its id, the paint of its faces and edges, and its name, lock, visibility, transparency, appearance, opacity mask and graphic style link. Object › Live Paint › Make with a Live Paint group selected, and a Live Paint Bucket click on a selected path beside a selected Live Paint group, add the paths to that group the same way. Make, Merge and the Live Paint Bucket take paths, compound paths and groups of them; with type, an image or another object among the selection they report that it has to be converted to paths first and change nothing, as type and raster images can't go into a Live Paint group directly ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)); before, such an object went among the group's hidden sources and vanished from the canvas. Evidence: `tests_build::live_paint_refuses_type_and_images_and_changes_nothing`. With the Live Paint Bucket selected, Alt-click on vector art samples its fill, stroke and stroke weight into the paint defaults ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)). On a placed image it samples the image pixel as a solid fill with no stroke. Alt+Shift-click samples only the color under the pointer, including an intermediate gradient color or image pixels, into the active fill or stroke ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). Neither click paints or changes the selection or selected art, and the next Bucket click paints with the sampled paint. Evidence: `tests_build::live_paint_bucket_alt_sample_paints_next_face_without_changing_selection`. + Double-clicking the Live Paint Bucket opens Live Paint Bucket Options ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)): Paint Fills (on) and Paint Strokes (off) set whether a click paints faces, edges or both, Highlight turns the outline of the face or edge under the pointer on or off, and Color and Width set it (red and 4 px by default). With both on, a click paints the edge within 4 px of the pointer, else the face, and Shift switches to Paint Fills only; with one on, Shift switches to the other. The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintBucket"}`). Evidence: `builder::tests::{bucket_options_choose_what_a_click_paints, bucket_options_set_the_highlight}`, `dialogs::live_paint_bucket::tests::double_clicking_the_tool_opens_its_options_and_ok_sets_them`. Live Paint Gap Options (Object › Live Paint › Gap Options…, `livePaint.gapOptions`): with Gap Detection on, paint stops at the gaps that run from a loose end of a path to the nearest path, up to Small (3 pt), Medium (6 pt), Large (12 pt) or a custom size; Close Gaps With Paths adds an unpainted path across each gap; Preview applies the options live and draws the gaps in the Gap Preview Color. The options are saved, copied and undone with the group, and Merge keeps the bottom group's options when its Gap Detection is on, or else turns Gap Detection on with Small when another merged group has it on. When Gap Detection is off in every merged group, it stays off. View › Show Live Paint Gaps (`view.livePaintGaps`) draws the gaps of the selected Live Paint groups up to their Paint Stops At size, each in its group's Gap Preview Color, until Hide Live Paint Gaps or Hide Edges hides them ([Live Paint gaps](https://web.archive.org/web/20260105111201/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/find-and-close-gaps-in-live-paint-groups.html)). Double-clicking the Live Paint Selection tool opens its Tool Options ([Live Paint Selection tool options](https://web.archive.org/web/20250904012025/https://helpx.adobe.com/illustrator/using/selecting-objects.html)): with Select Fills off, a click selects an edge instead of a face; with Select Strokes off, Alt-click selects a face instead of an edge; Color and Width set the color and width of the highlight on the face or edge under the pointer (red and 4 px by default). The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintSelection"}`). From d72022daf55c428f028bfe12f63a94df889fd054 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 1 Nov 2026 08:33:02 +0700 Subject: [PATCH 236/260] Grid tools: F, V, X and C change the divider skews by 10 while a grid is dragged out Squashed from #5019 onto main. --- crates/engine/src/tests/draw2.rs | 30 +++++++++ crates/mcp/src/tests.rs | 50 +++++++++++++++ crates/tools/src/draw2/family.rs | 87 ++++++++++++++++++++++++++- crates/ui-egui/src/shortcuts/tests.rs | 32 ++++++++++ docs/mcp.md | 9 ++- docs/target-app-parity.md | 1 + 6 files changed, 205 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index e5d9ac3cc6..811621a5d3 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -1463,6 +1463,36 @@ fn rectangular_grid_options_frame_fill_and_skew() { assert!(most.iter().all(|v| *v > 0.0 && *v < 100.0), "{most:?}"); } +/// F, V, X and C pressed while a grid is dragged out change its divider skews by 10 each: the +/// grid drawn on release is the one `shape.rectangularGrid` / `shape.polarGrid` draws with those +/// skews, and they stay as the tool's options. +#[test] +fn grid_drag_keys_skew_the_grid_drawn() { + let v = view(); + for (tool, keys, skews) in [ + ("rectangularGrid", "vvvfcc", json!({"rows": 5, "columns": 5, "rowSkew": 20.0, "columnSkew": 20.0})), + ("polarGrid", "fffxvc", json!({"concentric": 5, "radial": 5, "radialSkew": -20.0, "concentricSkew": 0.0})), + ] { + let mut s = session(); + s.select_tool(tool, v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap(); + for c in keys.chars() { + assert!(s.tool_claims_key(ToolKey::Letter(c), v), "{tool}: {c}"); + s.tool_key(ToolKey::Letter(c), Mods::default(), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0), v).unwrap(); + let drawn = s.doc().unwrap().doc.layers[0].children().unwrap().last().unwrap().children().unwrap().to_vec(); + let want = grid(&mut s, &format!("shape.{tool}"), with(&json!({"x": 100, "y": 100, "width": 100, "height": 100}), skews.clone())); + let geometry = |g: &[std::sync::Arc<vectorcraft_doc::Node>]| g.iter().map(|n| format!("{:?}", n.geometric_bounds())).collect::<Vec<_>>(); + assert_eq!(geometry(&drawn), geometry(&want), "{tool}"); + let o = s.tool_options(); + for (k, value) in skews.as_object().unwrap() { + assert_eq!(&o[k], value, "{tool}: {k}"); + } + } +} + /// #1377: the Polar Grid options. The ellipses lie under the radial dividers, largest first; /// `compound` pairs them into compound-path rings, `fill` paints the current fill and the skews /// crowd the ellipses outward and the radial dividers clockwise of the top one (positive). diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 7192d82085..f61b8839cf 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1492,6 +1492,56 @@ fn c_and_f_during_an_arc_gesture_go_to_the_arc_tool() { assert_ne!(serde_json::from_str::<Value>(&text_of(&r)).unwrap()["handledBy"], "tool", "{r}"); } +/// `press_key` with `f`, `v`, `x` and `c` while a rectangular or polar grid is being dragged goes +/// to the grid tool, and the release draws one grid. With nothing dragged, V is a shortcut again. +#[test] +fn f_v_x_and_c_during_a_grid_gesture_go_to_the_grid_tool() { + let count = |s: &mut Server, id: u64| { + let r = call(s, id, "inspect_document", json!({"depth": 0})); + serde_json::from_str::<Value>(&text_of(&r)).unwrap()["layers"][0]["childCount"].as_u64().unwrap() + }; + for tool in ["rectangularGrid", "polarGrid"] { + let mut s = server(); + let before = count(&mut s, 1); + let begin = json!([{"kind": "down", "x": 100, "y": 100}, {"kind": "drag", "x": 200, "y": 180}]); + let r = call(&mut s, 2, "pointer_gesture", json!({"tool": tool, "events": begin})); + assert_eq!(r["isError"], false, "{r}"); + for (id, key) in [(3, "f"), (4, "v"), (5, "x"), (6, "c")] { + let r = call(&mut s, id, "press_key", json!({"key": key})); + assert_eq!(serde_json::from_str::<Value>(&text_of(&r)).unwrap()["handledBy"], "tool", "{tool} {key}: {r}"); + } + let r = call(&mut s, 7, "pointer_gesture", json!({"tool": tool, "events": [{"kind": "up", "x": 200, "y": 180}]})); + assert_eq!(r["isError"], false, "{r}"); + assert_eq!(count(&mut s, 8), before + 1, "{tool}"); + let r = call(&mut s, 9, "press_key", json!({"key": "v"})); + assert_ne!(serde_json::from_str::<Value>(&text_of(&r)).unwrap()["handledBy"], "tool", "{tool}: {r}"); + } +} + +/// Grid letters with Shift reach the grid tool during a drag; with Ctrl, Cmd or Alt they do not. +#[test] +fn shifted_grid_letters_during_a_drag_go_to_the_grid_tool() { + let mut s = server(); + let r = call( + &mut s, + 1, + "pointer_gesture", + json!({"tool": "polarGrid", "events": [{"kind": "down", "x": 100, "y": 100}, {"kind": "drag", "x": 200, "y": 180}]}), + ); + assert_eq!(r["isError"], false, "{r}"); + for (id, key, mods, tool) in [ + (2, "v", json!({"shift": true}), true), + (3, "f", json!({"ctrl": true}), false), + (4, "x", json!({"cmd": true}), false), + (5, "c", json!({"cmd": true}), false), + (6, "v", json!({"alt": true}), false), + ] { + let r = call(&mut s, id, "press_key", json!({"key": key, "mods": mods})); + let handled = serde_json::from_str::<Value>(&text_of(&r)).ok().is_some_and(|v| v["handledBy"] == "tool"); + assert_eq!(handled, tool, "{key} {mods}: {r}"); + } +} + /// A click on one of two selected objects makes it the key object: `pointer_gesture` replies /// with it as `key` and `inspect_document` lists it, and a click on the key again lets it go. #[test] diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index aad4ff38fe..0bbdcf79b8 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -9,6 +9,9 @@ //! and Ctrl/Cmd keep its inner end at the distance from the center on the first modified drag as //! the outer end follows the pointer: Alt adds or removes whole winds of four segments, and //! Ctrl/Cmd changes the decay. +//! On a grid, F and V lower and raise +//! the skew of the horizontal (rectangular) or radial (polar) dividers, and X and C lower and raise +//! that of the vertical or concentric ones. use serde_json::{Value, json}; use vectorcraft_geom::Point; @@ -20,6 +23,9 @@ use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, Tool /// How much ↑ or ↓ changes the arc's slope while it is dragged out. const ARC_SLOPE_STEP: f64 = 10.0; +/// How much F, V, X or C changes a grid's divider skew (percent) while it is dragged out. +const GRID_SKEW_STEP: f64 = 10.0; + pub struct FamilyTool { id: &'static str, start: Option<Point>, @@ -157,6 +163,25 @@ impl FamilyTool { } } + /// The skew a letter changes while a grid is dragged out, as an index into `skew`, and the + /// direction: F lowers and V raises the skew of the horizontal dividers (a rectangular grid's + /// rows) or the radial dividers (a polar grid's), X lowers and C raises that of the vertical + /// dividers (columns) or the concentric dividers. + fn grid_skew_key(&self, key: ToolKey) -> Option<(usize, f64)> { + let (horizontal_or_radial, vertical_or_concentric) = match self.id { + "rectangularGrid" => (0, 1), + "polarGrid" => (1, 0), + _ => return None, + }; + match key { + ToolKey::Letter('f') => Some((horizontal_or_radial, -1.0)), + ToolKey::Letter('v') => Some((horizontal_or_radial, 1.0)), + ToolKey::Letter('x') => Some((vertical_or_concentric, -1.0)), + ToolKey::Letter('c') => Some((vertical_or_concentric, 1.0)), + _ => None, + } + } + /// A grid's options a drag draws with: its dividers, skews and switches (the Default Size and /// Reference Point are for a click's dialog). fn grid_options(&self) -> Value { @@ -316,6 +341,14 @@ impl Tool for FamilyTool { self.columns = self.columns.saturating_sub(1); true } + ("rectangularGrid" | "polarGrid", ToolKey::Letter(_)) => match self.grid_skew_key(key) { + Some((i, sign)) => { + let max = vectorcraft_geom::shapes::GRID_SKEW_MAX; + self.skew[i] = (self.skew[i] + sign * GRID_SKEW_STEP).clamp(-max, max); + true + } + None => false, + }, _ => false, }; if changed { @@ -338,8 +371,14 @@ impl Tool for FamilyTool { } } /// The Arc tool takes C and F while an arc is dragged out: C switches it between open and closed, and F switches its base axis. + /// The grid tools take F, V, X and C while a grid is dragged out, for its divider skews. fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { - self.id == "arc" && self.began && self.start.is_some() && matches!(key, ToolKey::Letter('c' | 'f')) + self.began + && self.start.is_some() + && match self.id { + "arc" => matches!(key, ToolKey::Letter('c' | 'f')), + _ => self.grid_skew_key(key).is_some(), + } } fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> { let mut o = self.snap.guides().to_vec(); @@ -458,6 +497,48 @@ mod tests { assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 90.0, 60.0)), vec![Action::Commit]); } + /// While a grid is dragged out, F/V lower/raise the skew of the horizontal (rectangular) or + /// radial (polar) dividers by 10 and X/C change that of the vertical or concentric ones, within + /// ±500; the grid drawn next keeps them. + #[test] + fn grid_drag_keys_change_the_divider_skews() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + let key = ToolKey::Letter; + for (id, horizontal_or_radial, vertical_or_concentric) in + [("rectangularGrid", "rowSkew", "columnSkew"), ("polarGrid", "radialSkew", "concentricSkew")] + { + let mut t = FamilyTool::new(id); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + assert!(!t.claims_key(&cx, key('f')), "{id}: no drag yet"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 60.0, 40.0)); + assert!("fvxc".chars().all(|c| t.claims_key(&cx, key(c))), "{id}"); + assert!(!t.claims_key(&cx, key('e')), "{id}"); + let skews = |a: Vec<Action>| match &a[..] { + [Action::Preview(c, v)] if c == &format!("shape.{id}") => (v[horizontal_or_radial].clone(), v[vertical_or_concentric].clone()), + _ => panic!("{id}: {a:?}"), + }; + assert_eq!(skews(t.key(&cx, key('v'), Mods::default())), (json!(10.0), json!(0.0)), "{id}: V"); + assert_eq!(skews(t.key(&cx, key('f'), Mods::default())), (json!(0.0), json!(0.0)), "{id}: F"); + assert_eq!(skews(t.key(&cx, key('f'), Mods::default())), (json!(-10.0), json!(0.0)), "{id}: F"); + assert_eq!(skews(t.key(&cx, key('c'), Mods::default())), (json!(-10.0), json!(10.0)), "{id}: C"); + assert_eq!(skews(t.key(&cx, key('x'), Mods::default())), (json!(-10.0), json!(0.0)), "{id}: X"); + for _ in 0..60 { + t.key(&cx, key('x'), Mods::default()); + t.key(&cx, key('v'), Mods::default()); + } + assert_eq!(skews(t.key(&cx, key('x'), Mods::default())), (json!(500.0), json!(-500.0)), "{id}: within ±500"); + assert_eq!(skews(t.key(&cx, key('v'), Mods::default())), (json!(500.0), json!(-500.0)), "{id}: within ±500"); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 60.0, 40.0)), vec![Action::Commit]); + assert!(!t.claims_key(&cx, key('v')), "{id}: the drag is over"); + let o = t.options(); + assert_eq!((o[horizontal_or_radial].clone(), o[vertical_or_concentric].clone()), (json!(500.0), json!(-500.0)), "{id}"); + } + } + /// #1377: a drag draws with the tool's stored options, which keep to their types and range. #[test] fn a_grid_drag_uses_the_stored_options() { @@ -739,8 +820,8 @@ mod tests { assert!(!t.claims_key(&cx, c), "the drag is over"); let o = t.options(); assert_eq!((o["closed"].clone(), o["baseAlong"].clone(), o["slope"].clone()), (json!(false), json!("y"), json!(100.0))); - // The other tools of the family leave C and F to their shortcuts. - let mut g = FamilyTool::new("rectangularGrid"); + // The Spiral tool leaves C and F to their shortcuts. + let mut g = FamilyTool::new("spiral"); g.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); g.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 60.0, 40.0)); assert!(!g.claims_key(&cx, c) && !g.claims_key(&cx, f)); diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index ad71fb3977..27e0f5bbf0 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -845,6 +845,38 @@ fn arrows_while_dragging_a_grid_change_its_rows_and_columns() { assert_eq!(grid(&mut app, &[Key::ArrowLeft, Key::ArrowDown]), (rows, columns + 1)); } +/// Grid letters change the stored skews once per press while a polar grid is dragged, plain or +/// with Shift; with Alt, Ctrl or Cmd they do not reach the grid. +#[test] +fn grid_drag_letters_take_plain_and_shift_presses() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("polarGrid"); + let view = app.view_info(); + app.session.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 80.0), view).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 220.0), view).unwrap(); + let skews = |app: &VectorcraftApp| (app.session.tool_options()["radialSkew"].clone(), app.session.tool_options()["concentricSkew"].clone()); + frame(&mut app, press(Key::V, Modifiers::NONE)); + assert_eq!(skews(&app), (json!(10.0), json!(0.0))); + frame(&mut app, press(Key::F, Modifiers::SHIFT)); + assert_eq!(skews(&app), (json!(0.0), json!(0.0))); + frame(&mut app, press(Key::V, Modifiers::SHIFT)); + assert_eq!(skews(&app), (json!(10.0), json!(0.0))); + frame(&mut app, press(Key::X, Modifiers::SHIFT)); + assert_eq!(skews(&app), (json!(10.0), json!(-10.0))); + frame(&mut app, press(Key::C, Modifiers::SHIFT)); + assert_eq!(skews(&app), (json!(10.0), json!(0.0))); + frame(&mut app, press(Key::X, Modifiers::ALT)); + assert_eq!(skews(&app), (json!(10.0), json!(0.0))); + for key in [Key::F, Key::X] { + frame(&mut app, press(key, command_key())); + assert_eq!(skews(&app), (json!(10.0), json!(0.0)), "{key:?} with Ctrl/Cmd"); + } + app.session.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 220.0), view).unwrap(); + assert_eq!(skews(&app), (json!(10.0), json!(0.0)), "the options stay after release"); +} + /// A press of `key` with `m` held. fn press(key: Key, m: Modifiers) -> Vec<egui::Event> { vec![egui::Event::ModifiersChanged(m), egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: m }] diff --git a/docs/mcp.md b/docs/mcp.md index 7acb9e5f41..333d7e85b2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -421,7 +421,7 @@ objects' fills or strokes differ (`fillMixed` / `strokeMixed`, drawn as a "?" pr | `draw_path` | `{points \| d, closed?, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `points` is `[[x,y],…]` or `[{x,y,in?,out?,smooth?},…]`. `d` is SVG path data. The options are below. | | `draw_shape` | `{shape, …geometry, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `rectangle`/`ellipse`: `x,y,width,height` (plus `radius` for corners). `polygon`: `cx,cy,radius,sides`. `star`: `cx,cy,radius1,radius2,points`. `line`: `x1,y1,x2,y2`. | | `set_paint` | `{fill?, stroke?, strokeWidth?, ids?}` | Applies to the selection (or `ids`) and becomes the default for new art. Returns `{applied, objects}`: `objects` is the number of objects painted, as the `objects` of the `paint.setFill`, `paint.setStroke` and `stroke.set` replies (the largest of them): a selected group counts the objects inside it. When it is 0, a `note` says that only the paint for new art changed. | -| `press_key` | `{key, mods?}` | Remote: a real key event. Headless: runs the command or tool bound to that shortcut, or sends the key to the busy tool (digits too: `5` while dragging with the Perspective Selection tool; `e` while dragging a Selection or Group Selection marquee; `c` and `f` while dragging out an arc). | +| `press_key` | `{key, mods?}` | Remote: a real key event. Headless: runs the command or tool bound to that shortcut, or sends the key to the busy tool (digits too: `5` while dragging with the Perspective Selection tool; `e` while dragging a Selection or Group Selection marquee; `c` and `f` while dragging out an arc; `f`, `v`, `x` and `c` while dragging out a rectangular or polar grid). | | `type_text` | `{text}` | Remote only. | | `answer_dialog` | `{set?: [{field, value?}], action?}` | Remote only. Sets fields of the app's open dialog in the order given with one `ui.dialog.set {fields}` (a missing `value` is `null`). The app stores all of them or none. When the app refuses the `ui.dialog.set`, for example because no dialog is open, the call is an error and `action` is not sent. Then `action` `confirm` (OK, `ui.dialog.confirm`) or `cancel` (`ui.dialog.cancel`). Give `set`, `action` or both; `set` holds at most 256 fields. `inspect_ui` shows the open dialog and its fields as `ui.dialog`. Returns `{dialog, result}`: the dialog after the fields were set (or `null`) and the reply to `confirm` or `cancel` (or `null`). After `invoke_menu` `app.quit`, `file.close` or `file.closeAll` replies `{"pending": "saveChanges"}`, `{action: "confirm"}` saves, `{set: [{field: "discard", value: true}], action: "confirm"}` closes without saving and `{action: "cancel"}` cancels the close or quit. | | `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. Includes UI commands such as `view.*` and `window.*` in remote mode. | @@ -500,6 +500,13 @@ the new values, and they stay as the Spiral tool's `segments` and `decay` option {"name":"pointer_gesture","arguments":{"tool":"spiral","events":[{"kind":"down","x":100,"y":100},{"kind":"drag","x":200,"y":100,"mods":{"alt":true}},{"kind":"drag","x":300,"y":100,"mods":{"alt":true}},{"kind":"up","x":300,"y":100}]}} ``` +While a grid is being dragged out with the Rectangular Grid or Polar Grid tool, `press_key {key: "f"}` and +`{key: "v"}` lower and raise the skew of the horizontal dividers (`rowSkew`) or the radial dividers (`radialSkew`) by +10, and `{key: "x"}` and `{key: "c"}` lower and raise that of the vertical dividers (`columnSkew`) or the concentric +dividers (`concentricSkew`), within ±500. Plain and Shift presses change the skew; with Alt, Ctrl or Cmd held they do not. +The grid drawn on release uses these skews, and they stay as the tool's options for the next grid. With nothing +being dragged, the four letters run their shortcuts as before. + Appearance stacks: an object can carry several fills and strokes (`appearance.addFill`, `appearance.addStroke`), indexed in paint order (0 is painted first, the bottom row of the Appearance panel). Cmd+/ runs `appearance.addFill` and Cmd+Alt+/ runs `appearance.addStroke` (`press_key {key: "/", mods: {cmd: true, alt: true}}`). `paint.setFill`, `paint.setStroke`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 377dd2d87e..a19e610fd9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -699,6 +699,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays by 0.1 radian at each drag update in which the pointer's document y grows, and back by as much at each one in which it falls, Shift held keeps their turn, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation (unturned, or turned by a nonzero General › Constrain Angle), and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). + While a grid is dragged out, F lowers `rowSkew` (rectangular) or `radialSkew` (polar) by 10 percentage points and V raises it by 10; X lowers `columnSkew` (rectangular) or `concentricSkew` (polar) by 10 and C raises it by 10. Plain and Shift presses work; with Alt, Ctrl or Cmd held they do not, as for the other letters a tool takes while dragging. Each press changes the skew once and updates the preview; values stay within ±500% and remain in the tool options after release. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list the four drag keys and a 10% change. The signs (positive values follow VectorCraft's existing skew convention, so F and X lower the stored value) and one change per press with key repeat ignored are our own rules. While an arc is dragged out, C switches it between open and closed, F switches its base between the X and Y axes in the same box, and Up/Down raise and lower its slope by 10 within −100…100; each press switches once, and the values stay as the Arc tool's options. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list C, F and Up/Down for an arc being dragged out. F as the base switch, the arrows changing the slope, the step of 10 and one switch per press are our own rules. While a spiral is dragged out, Alt adds or removes whole winds of four segments and Ctrl/Cmd changes the decay. The spiral's inner end keeps the distance from the center it had on the first modified drag event, while the outer end follows the pointer. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list Alt-drag to add or subtract winds and Ctrl-drag to change the decay rate; [Draw spirals](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-spirals.html) defines four segments per full wind. Rounding the fitted count to whole winds from the count on the first Alt-only drag event, the held inner radius, the ranges (2…1000 segments, 5…99.99 % decay), Ctrl/Cmd taking precedence when both are held, and the new values staying as Spiral tool options are our own rules. Switching back to Alt uses the current count as its new base while keeping the held inner end. - **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes). From 217c01836be1cd66f0390ab77f88162920f620c5 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 1 Nov 2026 02:47:50 +0100 Subject: [PATCH 237/260] ci(xtask): print the i18n report without recompiling the workspace (#5001) * ci: i18n report without a rebuild; PR print runs stop saving caches - xtask ci: the i18n report selects the whole workspace as the test stage did. With `-p vectorcraft-ui-egui` alone cargo resolved features differently and recompiled for about 3.5 minutes. `cargo xtask i18n-report` on its own still builds only that crate. - print.yml: only main saves the desktop-print cache. Each PR saved its own 1.3 GB cache that only that PR can read (6.3 GB across five PRs), pushing the repository past its 10 GB limit and evicting caches main's gate restores. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * ci(xtask): i18n report selects the test run's targets too Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> The test run builds --lib --bins --tests; a binary target's dependencies (the desktop app's eframe features) could still resolve differently under --lib alone. Match the selection exactly, and drop --quiet so a rebuild would show in the log. * ci: leave print.yml unchanged print.yml still runs its own jobs, and CLAUDE.md (CI workflows) keeps additions out of such files. The cache churn it causes goes to craft-common-actions instead. This PR is now the xtask change only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: FredApps <FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- xtask/src/main.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 0516321abc..de6ff58154 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -294,7 +294,7 @@ fn cmd_ci() -> Result<(), String> { ("assets", Box::new(|| assets::run(&root()))), ("brands", Box::new(|| brands::run(&root()))), ("cursors", Box::new(|| cursors::run(&root()))), - ("i18n-report", Box::new(cmd_i18n_report)), + ("i18n-report", Box::new(cmd_ci_i18n_report)), ("layers", Box::new(cmd_layers)), ("wasm", Box::new(cmd_wasm)), ]; @@ -349,3 +349,13 @@ fn cmd_i18n_report() -> Result<(), String> { c.args(["test", "-p", "vectorcraft-ui-egui", "--lib", "--", "i18n::tests::untranslated_report", "--exact", "--nocapture"]); run(c, "cargo test -p vectorcraft-ui-egui --lib -- i18n::tests::untranslated_report --exact --nocapture") } + +/// [`cmd_i18n_report`] in `ci`, selecting the packages and targets the test stage did so it +/// reuses that build: with `-p vectorcraft-ui-egui --lib` alone cargo resolves features +/// differently and recompiled for about 3.5 minutes. Every other test binary runs with no test +/// matching the filter. +fn cmd_ci_i18n_report() -> Result<(), String> { + let mut c = cargo(); + c.args(["test", "--workspace", "--lib", "--bins", "--tests", "--", "i18n::tests::untranslated_report", "--exact", "--nocapture"]); + run(c, "cargo test --workspace --lib --bins --tests -- i18n::tests::untranslated_report --exact --nocapture") +} From 317423c5143d1051d94c843b6efcbe241217a200 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 08:37:01 +0700 Subject: [PATCH 238/260] Fix #4908: Glyphs panel highlights the selected character --- crates/ui-egui/src/panels/glyphs.rs | 148 ++++++++++++++++++++++++++-- docs/target-app-parity.md | 5 +- docs/type-parity.md | 5 +- 3 files changed, 148 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index ea7afa5202..e69e97c46b 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -1,11 +1,12 @@ //! Glyphs panel: every character the current font maps (its cmap), drawn from the font's own //! outlines. Double-click inserts the character at the Type tool's caret (or appends it to the -//! selected text objects). +//! selected text objects). The character selected with the Type tool is highlighted in the grid. use std::collections::HashMap; use egui::{Color32, Sense, Stroke, StrokeKind, Ui, vec2}; use serde_json::json; +use vectorcraft_doc::NodeKind; use vectorcraft_geom::{Affine, BezPath, PathEl}; use vectorcraft_text::FontDb; @@ -144,6 +145,28 @@ fn glyph_texture(ctx: &egui::Context, face: &vectorcraft_text::FontFace, gid: u3 tex } +/// The character the grid highlights: the first one of the Type tool's selected range, else the +/// one before its caret. Public behaviour: the Glyphs panel shows the selected character's glyph +/// (the overview page cited at [`CELL_STEPS`]). Walks the runs, not the characters, so it stays +/// cheap on every frame. +fn selected_char(app: &VectorcraftApp) -> Option<char> { + let (id, a, b) = super::character::text_editing(app)?; + let NodeKind::Text(t) = &app.session.active()?.doc.node(id)?.kind else { return None }; + let (at, range) = (a.min(b), a != b); + let mut start = 0; + for run in &t.runs { + let end = start + run.text.len(); + if range && (start..end).contains(&at) { + return run.text.get(at - start..)?.chars().next(); + } + if !range && at > start && at <= end { + return run.text.get(..at - start)?.chars().next_back(); + } + start = end; + } + None +} + /// Insert `ch` at the Type tool's caret, else append it to the selected text. fn insert(app: &mut VectorcraftApp, ctx: &egui::Context, ch: char) { let s = ch.to_string(); @@ -193,17 +216,35 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let px = (cell * ui.ctx().pixels_per_point()).round().clamp(8.0, 256.0) as u32; let list_h = (ui.available_height() - 64.0).max(cell * 3.0); let hover_id = egui::Id::unique("gl-hover"); - egui::ScrollArea::vertical().max_height(list_h).auto_shrink([false, false]).show_rows(ui, cell, rows, |ui, range| { - for r in range { + let selected = selected_char(app); + // The selected character and the rows shown last frame: the grid scrolls to the selected glyph + // only when the selection moves to another character, so it still scrolls freely meanwhile. + let follow_id = egui::Id::unique("gl-follow"); + let (followed, shown): (Option<char>, std::ops::Range<usize>) = ui.ctx().data(|d| d.get_temp(follow_id)).unwrap_or_default(); + let mut area = egui::ScrollArea::vertical().max_height(list_h).auto_shrink([false, false]); + if selected != followed + && let Some(c) = selected + && let Ok(i) = chars.binary_search_by_key(&c, |x| x.0) + && !shown.contains(&(i / cols)) + { + let row_h = cell + ui.spacing().item_spacing.y; + area = area.vertical_scroll_offset(((i / cols) as f32 + 0.5) * row_h - list_h * 0.5); + } + let shown = area.show_rows(ui, cell, rows, |ui, range| { + for r in range.clone() { ui.horizontal(|ui| { ui.spacing_mut().item_spacing = vec2(0.0, 0.0); for &(c, gid) in chars.iter().skip(r * cols).take(cols) { let (rect, resp) = ui.allocate_exact_size(vec2(cell, cell), Sense::click()); + let chosen = selected == Some(c); if resp.hovered() { ui.painter().rect_filled(rect, 2, t.hover); ui.ctx().data_mut(|d| d.insert_temp(hover_id, (c, gid))); + } else if chosen { + ui.painter().rect_filled(rect, 2, t.row_selected); } - ui.painter().rect_stroke(rect.shrink(0.5), 0, egui::Stroke::new(0.5, t.border), egui::StrokeKind::Inside); + let edge = if chosen { Stroke::new(1.5, t.accent) } else { Stroke::new(0.5, t.border) }; + ui.painter().rect_stroke(rect.shrink(0.5), 0, edge, StrokeKind::Inside); let tex = glyph_texture(ui.ctx(), &face, gid, px); ui.painter().image(tex.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), t.text_strong); let resp = resp.on_hover_text(format!("U+{:04X} {c} (glyph {gid})\n{}", c as u32, tl!("Double-click to insert"))); @@ -213,7 +254,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } }); } + range }); + ui.ctx().data_mut(|d| d.insert_temp(follow_id, (selected, shown.inner))); ui.add_space(4.0); let info = ui.ctx().data(|d| d.get_temp::<(char, u32)>(hover_id)); ui.label( @@ -295,14 +338,46 @@ mod tests { use super::*; - fn frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> (Vec<(String, Pos2)>, Vec<f32>) { + fn shapes(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> Vec<Shape> { let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(280.0, 420.0))), events, ..Default::default() }; let mut out = ctx.run_ui(raw, |ui| show(app, ui)); out.textures_delta.clear(); - let shapes: Vec<Shape> = out.shapes.into_iter().map(|c| c.shape).collect(); + out.shapes.into_iter().map(|c| c.shape).collect() + } + + fn frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> (Vec<(String, Pos2)>, Vec<f32>) { + let shapes = shapes(ctx, app, events); (text_anchors(&shapes), square_sides(&shapes)) } + /// The Type tool editing `text` in a new document. + fn editing(text: &str) -> (VectorcraftApp, serde_json::Value) { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 50, "text": text})).unwrap()["id"].clone(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + (app, id) + } + + fn select(app: &mut VectorcraftApp, start: usize, end: usize) { + app.session.set_tool_option("select", &json!({"start": start, "end": end})); + } + + /// Centres of the highlighted (selected-character) cells. + fn highlighted(shapes: &[Shape], t: &Tokens) -> Vec<Pos2> { + fn walk(s: &Shape, fill: Color32, out: &mut Vec<Pos2>) { + match s { + Shape::Rect(r) if r.fill == fill => out.push(r.rect.center()), + Shape::Vec(v) => v.iter().for_each(|s| walk(s, fill, out)), + _ => {} + } + } + let mut out = vec![]; + shapes.iter().for_each(|s| walk(s, t.row_selected, &mut out)); + out + } + fn text_anchors(shapes: &[Shape]) -> Vec<(String, Pos2)> { fn walk(s: &Shape, out: &mut Vec<(String, Pos2)>) { match s { @@ -350,6 +425,67 @@ mod tests { frame(ctx, app, vec![button(false)]); } + #[test] + fn the_selected_character_is_the_range_start_or_the_one_before_the_caret() { + let (mut app, id) = editing("aHé"); + select(&mut app, 1, 2); + assert_eq!(selected_char(&app), Some('H')); + select(&mut app, 2, 2); + assert_eq!(selected_char(&app), Some('H')); + select(&mut app, 4, 1); + assert_eq!(selected_char(&app), Some('H'), "a backward range starts at its lower end"); + select(&mut app, 0, 0); + assert_eq!(selected_char(&app), None, "nothing before the caret"); + // Across runs: a style on `H` alone splits the text into three runs. + app.run("text.setRangeStyle", json!({"id": id, "start": 1, "end": 2, "kerning": 50})).unwrap(); + select(&mut app, 1, 1); + assert_eq!(selected_char(&app), Some('a')); + select(&mut app, 2, 2); + assert_eq!(selected_char(&app), Some('H')); + select(&mut app, 2, 4); + assert_eq!(selected_char(&app), Some('é')); + app.session.select_tool("select", Default::default()).unwrap(); + assert_eq!(selected_char(&app), None, "only the Type tool's selection counts"); + } + + #[test] + fn the_selected_glyph_is_highlighted_and_scrolled_into_view() { + let (mut app, _) = editing("A"); + let ctx = egui::Context::default(); + let t = Tokens::get(&ctx); + let (texts, _) = frame(&ctx, &mut app, vec![]); + if texts.iter().any(|(t, _)| t.contains("No fonts are available")) { + eprintln!("glyphs highlight: no fonts installed, grid not drawn"); + return; + } + let (family, style) = super::super::character::text_style(&app).map(|(s, _)| (s.font_family, s.font_style)).unwrap(); + let face = FontDb::global().face(&family, &style).unwrap(); + let chars: Vec<char> = face.chars().into_iter().map(|(c, _)| c).filter(|c| !c.is_control() && !c.is_whitespace()).collect(); + let (Some(&first), Some(&last)) = (chars.first(), chars.last()) else { return }; + if chars.len() < 200 { + eprintln!("glyphs highlight: font too small to need scrolling"); + return; + } + let (mut app, _) = editing(&format!("{first}{last}")); + let end = first.len_utf8() + last.len_utf8(); + select(&mut app, end, end); + let ctx = egui::Context::default(); + // The caret sits after the last glyph of the font, far below the first screen of the grid. + let lit = highlighted(&shapes(&ctx, &mut app, vec![]), &t); + assert_eq!(lit.len(), 1, "the grid scrolled to the selected glyph and highlighted it: {lit:?}"); + let lit = highlighted(&shapes(&ctx, &mut app, vec![]), &t); + assert_eq!(lit.len(), 1, "it stays highlighted"); + // Highlighting the first character scrolls back up to it. + select(&mut app, 0, 1); + shapes(&ctx, &mut app, vec![]); + let top = highlighted(&shapes(&ctx, &mut app, vec![]), &t); + assert_eq!(top.len(), 1, "{top:?}"); + assert!(top[0].y < lit[0].y, "the first glyph sits at the top of the grid: {top:?} vs {lit:?}"); + // The caret at the start selects nothing. + select(&mut app, 0, 0); + assert!(highlighted(&shapes(&ctx, &mut app, vec![]), &t).is_empty()); + } + #[test] fn zoom_stops_at_the_ends() { assert_eq!(nudge_cell(CELL_DEFAULT, 1), CELL_DEFAULT + 1); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a19e610fd9..dd2f9c55a3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Arrange Tools add-on: Sort Objects, #4917; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Glyphs panel highlights the character selected with the Type tool, #4908; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -127,7 +127,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (four generated libraries, User Defined, Other Library…, Save Brushes); remaining: Art brush Overlap, Pattern brush auto corners, pen pressure on macOS, tilt/bearing/rotation | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | -| Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208) | +| Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guide settings (stored, not drawn) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | @@ -1446,6 +1446,7 @@ Symbols area (#4938), from the public symbol documentation ([create and place sy | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Type core: the Glyphs panel highlights the character selected with the Type tool and scrolls it into view (#4908); evidence added; scores unchanged. | | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Randomize Opacity (#4925); evidence added; scores unchanged. | | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Sort Objects (#4917); evidence added; scores unchanged. | | 2026-11-01 | minor | Symbols panel: Select All Unused (`symbol.unused`) shows the symbols nothing places selected, and Delete Symbol deletes them all, asked once, in one undo step (`symbol.delete {names}`, #4918); scores and hours unchanged | diff --git a/docs/type-parity.md b/docs/type-parity.md index 0b7384d65a..e13ad66806 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Serbian in Cyrillic and Latin and Croatian among the languages, with their quote marks; previously minor: Area Type Options › Text Flow by rows or by columns, #4978; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Glyphs panel: the character selected with the Type tool is highlighted and scrolled into view, #4908; previously minor: Serbian in Cyrillic and Latin and Croatian among the languages, with their quote marks; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -28,7 +28,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Character and Paragraph panels, styles with overrides | done | Character-style Auto-leading resets, partial definitions, local leading overrides, override markers, Undo/Redo and native serialization have regression coverage; differing paragraph alignments leave the shared alignment buttons unselected (headless regressions, full integration CI and visual review pass); mixed-value display for other paragraph fields remains missing | | Character size and horizontal scale after object/group scaling | done | #1034: fields and setters compensate the stored affine; point size follows the transformed em-height axis, not the glyph ink bounds. Range edits, keyboard increments, leading and baseline shift use document points; rotation, reflection and shear remain editable. | | Preserve font sizes while scaling a group | missing | Separate enhancement; scaling still scales text with the other artwork. | -| OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607) | +| OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607). The Glyphs panel highlights the character selected with the Type tool (a range's first character, else the one before the caret) and scrolls it into view as the selection moves (#4908; `panels::glyphs` tests); its Show menu lists Unicode ranges, and Alternates for Current Selection is not there yet | | Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux) | | Missing glyphs set in an installed font made for their script (Thai, Lao, Khmer, Myanmar first; then any font that has them) | done | Thai: Leelawadee UI, Tahoma, Thonburi, Sukhumvit Set, Noto Sans Thai, TLWG | | Full font-name matching (OpenType name ID 4) | done | #1258: loaded/cataloged faces and Missing Fonts searches; localized names and variable default faces; Windows font-service QA pending | @@ -73,6 +73,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Glyphs panel (#4908): the character selected with the Type tool (a range's first, else the one before the caret) is highlighted in the grid and scrolled into view when the selection moves to another character; Show › Alternates for Current Selection not yet; scores unchanged | | 2026-11-01 | minor | Serbian: Cyrillic (`sr-Cyrl`), Serbian: Latin (`sr-Latn`) and Croatian (`hr`) in the language list, with their quote marks (Serbian „…” and ’…’ per the Pravopis srpskoga jezika, Matica srpska 2010, ISBN 978-86-7946-079-0, т. 168, and [CLDR `sr`](https://github.com/unicode-org/cldr/blob/main/common/main/sr.xml); Croatian „…“ and ‚…‘ per [CLDR `hr`](https://github.com/unicode-org/cldr/blob/main/common/main/hr.xml)); Serbian text gets the fonts' Serbian forms (italic б, г, д, п, т); scores unchanged | | 2026-11-01 | minor | Area Type Options › Text Flow (#4978): By Rows / By Columns radio buttons and `text.areaOptions {flow}`; area type with several rows and columns fills them across each row first or down each column first (the default, so existing documents are unchanged; saved only when by rows); scores unchanged | | 2026-11-01 | minor | Digits (#4942): the native digits of Devanagari, Bengali, Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada and Malayalam in the Character panel menu › Digits and `{digits}`; scores unchanged | From 84336967aa0bc8ccf6af993a9793442a0bef3aa6 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 08:56:29 +0700 Subject: [PATCH 239/260] Fix #4922: Expand Dashes into Paths --- ROADMAP.md | 4 +- crates/engine/src/cmd/addons/pathtools.rs | 113 +++++++++++++++- .../engine/src/cmd/addons/pathtools/tests.rs | 123 ++++++++++++++++++ crates/engine/tests/command_sweep.rs | 3 + crates/ui-egui/src/addons/pathtools.rs | 3 +- crates/ui-egui/src/addons/pathtools/tests.rs | 10 ++ crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/bs.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + docs/mcp.md | 11 ++ docs/target-app-parity.md | 7 +- docs/ui-parity.md | 4 +- 35 files changed, 349 insertions(+), 7 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index cbce1fbfaa..c85be5aefd 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -9,7 +9,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Arrange Tools add-on's Sort Objects; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Path Precision Tools add-on's Expand Dashes into Paths; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. @@ -210,6 +211,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Progress log row for the Path Precision Tools add-on's Expand Dashes into Paths (#4922); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Randomize Opacity (#4925); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Sort Objects (#4917); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Document Tools add-on's New Symbols from Layers (#4927); headline numbers unchanged. | diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index 94114a59c4..5d0e5723ff 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -2,7 +2,8 @@ //! the Extend Path tool's extension, the Measure & Inspect tool's readouts, the Anchor Inspector's //! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners //! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's -//! merges with Keep Shared Points Together ([`shared_edge`]), and Divide into Dashes. +//! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes and Expand Dashes +//! into Paths. //! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's //! and the UI's. @@ -17,7 +18,7 @@ mod tests; use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; -use vectorcraft_doc::{AnchorRef, Document, NodeId, NodeKind}; +use vectorcraft_doc::{AnchorRef, Appearance, AppearanceItem, Document, LineCap, NodeId, NodeKind}; use vectorcraft_geom::{PathData, Point, SubPath}; use vectorcraft_pathops::addons::{self as po, pathtools as pt}; @@ -40,7 +41,7 @@ const MIN_RADIUS: f64 = 0.05; const MAX_DIAMETER: f64 = 2500.0; /// The farthest an end is extended at once (pt). const MAX_EXTEND: f64 = 1e6; -/// Most pieces Divide into Dashes makes at once. +/// Most pieces Divide into Dashes and Expand Dashes into Paths make at once. const MAX_PIECES: usize = 100_000; /// Most anchors Add Points puts on each segment. const MAX_ADD: u64 = pt::MAX_ADDED_PER_SEGMENT as u64; @@ -164,6 +165,15 @@ pub fn specs() -> Vec<CommandSpec> { has_selection, divide_dashes ), + cmd!( + "addon.pathtools.expandDashes", + "Expand Dashes into Paths", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{ids?: [id…] (default: the selection)} turn the dashed stroke of each path and compound path under the objects into separate open paths, one per dash, laid out as the stroke draws them (its dash pattern, offset and Align Dashes to Corners and Path Ends), each keeping the path's appearance with the dashes off, so the gaps are real gaps: a dash running all the way round a closed path stays closed, and with a round or projecting cap a dash of no length (a dot) becomes a path on its point. The top stroke's dashes are the ones expanded; its arrowheads go, and the path's fills stay on it, below its dashes. Paths without a dashed stroke stay as they are. One undo step; the dashes are selected; at most 100000 → {ids, dashes}", + has_selection, + expand_dashes + ), ]; v.extend(shape::specs()); v.extend(corners::specs()); @@ -793,3 +803,100 @@ fn divide_dashes(s: &mut Session, p: &Value) -> Result<Value> { })?; Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "dashes": dashes })) } + +// ---------- Expand Dashes into Paths ---------- + +/// The paths and compound paths under `roots` whose top stroke is dashed: a compound path's +/// members stand for it, which holds their paint. Clipping paths are left alone. +fn dashed_paths(d: &Document, roots: &[NodeId]) -> Vec<NodeId> { + let editable = d.editable(); + let mut seen = BTreeSet::new(); + let mut out = vec![]; + for id in paths_under(d, roots) { + let compound = d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })); + let Some(n) = compound.or_else(|| d.node(id)) else { continue }; + let dashed = n.appearance.stroke().and_then(|st| st.dash.as_ref()).is_some_and(|dash| dash.is_dashed()); + if dashed && !matches!(n.kind, NodeKind::Path { clipping: true, .. }) && editable(n.id) && seen.insert(n.id) { + out.push(n.id); + } + } + out +} + +fn expand_dashes(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "addon.pathtools.expandDashes"; + let too_many = || bad(C, "that makes too many pieces (at most 100000): make the dashes longer"); + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + // Each dashed path and its dashes, as the canvas draws them. + let mut changed: Vec<(NodeId, Vec<SubPath>)> = vec![]; + let mut count = 0; + for id in dashed_paths(d, &roots) { + let Some(n) = d.node(id) else { continue }; + let (Some(st), Some(bp)) = (n.appearance.stroke(), n.stroke_path()) else { continue }; + let Some(dash) = &st.dash else { continue }; + // The line the stroke draws: the path, its ends trimmed under any arrowheads. + let line = vectorcraft_render::effects::stroke::stroke_pieces(&bp, st).line; + // A pattern too fine to draw is drawn solid: it has too many dashes to expand. + let dashed = vectorcraft_render::effects::stroke::dash(&line, dash).ok_or_else(too_many)?; + let mut pieces = PathData::from_bezpath(&dashed.path).subpaths; + // A dot paints its cap; a path that stays on its point is drawn so too. Under a butt cap it + // paints nothing. + if st.cap != LineCap::Butt { + pieces.extend(dashed.dots.iter().map(|dot| SubPath::polyline(&[dot.at, dot.at], false))); + } + count += pieces.len(); + if count > MAX_PIECES { + return Err(too_many()); + } + if !pieces.is_empty() { + changed.push((id, pieces)); + } + } + if changed.is_empty() { + return Err(bad(C, "select paths with dashed strokes to expand")); + } + let ids = s.edit("Expand Dashes into Paths", |d, sel| { + let mut all = vec![]; + let mut beside = Beside::replacing(d, &changed.iter().map(|(id, _)| *id).collect::<Vec<_>>()); + for (id, pieces) in changed { + let n = d.node(id).cloned().ok_or(EngineError::NoNode(id))?; + let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &n.kind else { continue }; + let rule = *rule; + let filled = |i: &AppearanceItem| matches!(i, AppearanceItem::Fill(f) if f.visible && !f.paint.is_none()); + // The dashes: open paths with the strokes (the top one's dashes and arrowheads off). + let mut look = Appearance::clone(&n.appearance); + look.items.retain(|i| !matches!(i, AppearanceItem::Fill(_))); + if let Some(st) = look.stroke_mut() { + (st.dash, st.start_arrow, st.end_arrow) = (None, None, None); + } + let mut dash = n.clone(); + dash.kind = NodeKind::Path { path: PathData::default(), rule, live: None, clipping: false, guide: false }; + dash.appearance = look.into(); + // The fills stay on the path, below its dashes; without fills it goes. + let mut parts = vec![]; + if n.appearance.items.iter().any(filled) { + let mut fill = n.clone(); + let mut look = Appearance::clone(&n.appearance); + look.items.retain(filled); + fill.appearance = look.into(); + parts.push(fill); + } + for sp in pieces { + let mut piece = d.reid(&dash); + if let NodeKind::Path { path, .. } = &mut piece.kind { + *path = PathData::single(sp); + } + all.push(piece.id); + parts.push(piece); + } + beside.put(d, id, parts)?; + } + beside.finish(d)?; + // The dashes join the objects selected (whole, in one go: there may be many). + let before = std::mem::take(&mut sel.objects); + sel.set(before.into_iter().filter(|id| d.node(*id).is_some()).chain(all.iter().copied())); + Ok(all) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "dashes": ids.len() })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index cc745385cd..32bcc0c3b3 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -748,3 +748,126 @@ fn divide_into_dashes_refuses_bad_params_and_too_many_pieces() { s.execute("select.none", &json!({})).unwrap(); refuses(&mut s, "addon.pathtools.divideDashes", &[json!({})]); } + +/// The dashes made of `r`'s ids: (first x, last x) of each, by its anchors. +fn dash_spans(s: &Session, r: &Value) -> Vec<(f64, f64)> { + ids(r).iter().map(|id| path(s, *id).bounds().map(|b| (b.x0, b.x1)).unwrap()).collect() +} + +fn near(a: &[(f64, f64)], b: &[(f64, f64)]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6) +} + +#[test] +fn expand_dashes_makes_an_open_path_of_each_dash_keeping_the_stroke() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)], false); + select(&mut s, &[l]); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("stroke.set", &json!({"weight": 3, "cap": "round", "dash": [30, 10]})).unwrap(); + let n = steps(&s); + let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert!(near(&dash_spans(&s, &r), &[(0.0, 30.0), (40.0, 70.0), (80.0, 100.0)]), "{:?}", dash_spans(&s, &r)); + assert_eq!(r["dashes"], json!(3)); + let st = s.doc().unwrap(); + for id in ids(&r) { + let node = st.doc.node(id).unwrap(); + let stroke = node.appearance.stroke().unwrap(); + assert_eq!((stroke.width, stroke.cap, stroke.dash.clone()), (3.0, vectorcraft_doc::LineCap::Round, None), "the stroke stays, dashes off"); + assert!(!path(&s, id).subpaths[0].closed); + } + assert_eq!(st.selection.objects, ids(&r)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(l).unwrap().appearance.stroke().unwrap().dash.is_some()); + // The offset shifts the pattern as the stroke draws it: 20 into the first dash. + s.execute("stroke.set", &json!({"dashOffset": 20})).unwrap(); + let r = s.execute("addon.pathtools.expandDashes", &json!({"ids": [l.0]})).unwrap(); + assert!(near(&dash_spans(&s, &r), &[(0.0, 10.0), (20.0, 50.0), (60.0, 90.0)]), "{:?}", dash_spans(&s, &r)); +} + +#[test] +fn expand_dashes_keeps_the_fill_below_and_follows_aligned_corners() { + let mut s = session(); + let rect = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 60})).unwrap()); + select(&mut s, &[rect]); + s.execute("stroke.set", &json!({"dash": [20, 20]})).unwrap(); + let had_fill = !s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint().is_none(); + let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap(); + // 320 round: eight dashes of 20, a dash bending round each corner it meets. + let pieces = ids(&r); + assert_eq!(pieces.len(), 8); + let st = s.doc().unwrap(); + let layer: Vec<NodeId> = st.doc.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + if had_fill { + let kept = st.doc.node(rect).unwrap(); + assert!(kept.appearance.stroke().is_none() && kept.appearance.fill().is_some(), "the fill stays on the rectangle"); + assert_eq!(layer, [vec![rect], pieces.clone()].concat(), "the fill below its dashes"); + } else { + assert_eq!(layer, pieces); + } + assert!(pieces.iter().all(|id| st.doc.node(*id).unwrap().appearance.fill().is_none()), "an open dash isn't filled"); + s.execute("edit.undo", &json!({})).unwrap(); + // Aligned to corners: a dash centred on each corner, the four sides each starting and ending + // on half a dash; 12 dashes along the sides. + s.execute("stroke.set", &json!({"dash": [10, 10], "alignDashes": true})).unwrap(); + let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap(); + let corners = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 60.0), Point::new(0.0, 60.0)]; + let mut centred = 0; + for id in ids(&r) { + let sp = path(&s, id).subpaths[0].clone(); + if let [a, b, c] = sp.anchors.as_slice() + && corners.iter().any(|k| b.p.distance(*k) < 1e-6) + { + assert!((a.p.distance(b.p) - 5.0).abs() < 1e-6 && (c.p.distance(b.p) - 5.0).abs() < 1e-6, "{sp:?}"); + centred += 1; + } + } + assert_eq!((ids(&r).len(), centred), (16, 4)); +} + +#[test] +fn expand_dashes_turns_dots_into_paths_on_their_point_and_releases_compound_paths() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)], false); + select(&mut s, &[l]); + s.execute("stroke.set", &json!({"dash": [0, 20], "cap": "round"})).unwrap(); + let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap(); + assert_eq!(ids(&r).len(), 6, "a dot every 20 from 0 to 100"); + assert!(ids(&r).iter().all(|id| path(&s, *id).bounds().unwrap().width() == 0.0)); + s.execute("edit.undo", &json!({})).unwrap(); + // Under a butt cap a dot paints nothing, so there is nothing to expand. + s.execute("stroke.set", &json!({"cap": "butt"})).unwrap(); + refuses(&mut s, "addon.pathtools.expandDashes", &[json!({})]); + // A compound path's dashes are paths of their own with its stroke. + let a = line(&mut s, &[(0.0, 100.0), (50.0, 100.0)], false); + let b = line(&mut s, &[(0.0, 120.0), (50.0, 120.0)], false); + select(&mut s, &[a, b]); + let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + s.execute("stroke.set", &json!({"weight": 2, "dash": [20, 10], "cap": "butt"})).unwrap(); + let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap(); + // Each 50 line: 20, gap, 20. + let st = s.doc().unwrap(); + assert_eq!(ids(&r).len(), 4); + for id in ids(&r) { + let n = st.doc.node(id).unwrap(); + assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }), "a plain path"); + assert_eq!(n.appearance.stroke_width(), 2.0); + assert!(n.appearance.stroke().unwrap().dash.is_none()); + } + assert!(st.doc.node(c).is_none_or(|n| n.appearance.stroke().is_none()), "the compound path's dashes are gone from it"); +} + +#[test] +fn expand_dashes_refuses_without_dashes_and_past_the_limit() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (1e5, 0.0)], false); + refuses(&mut s, "addon.pathtools.expandDashes", &[json!({})]); + select(&mut s, &[l]); + refuses(&mut s, "addon.pathtools.expandDashes", &[json!({}), json!({"ids": "x"}), json!({"zzz": 1})]); + // 125000 dashes refused; 1000 are fine. + s.execute("stroke.set", &json!({"dash": [0.4, 0.4]})).unwrap(); + refuses(&mut s, "addon.pathtools.expandDashes", &[json!({})]); + s.execute("stroke.set", &json!({"dash": [50, 50]})).unwrap(); + assert_eq!(s.execute("addon.pathtools.expandDashes", &json!({})).unwrap()["dashes"], json!(1000)); +} diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 330fd45405..38a60e2394 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -600,6 +600,9 @@ fn structured_junk() { ("addon.pathtools.divideDashes", json!({"dash": 1e-308, "gap": -1e308, "fit": "x"})), ("addon.pathtools.divideDashes", json!({"dash": 0.01, "gap": 1e6, "fit": true, "removeGaps": false})), ("addon.pathtools.divideDashes", json!({"dash": f64::MAX, "gap": [0], "removeGaps": null})), + ("addon.pathtools.expandDashes", json!({})), + ("addon.pathtools.expandDashes", json!({"ids": [0, 1, 2, 3, u64::MAX]})), + ("addon.pathtools.expandDashes", json!({"ids": "x", "junk": f64::MAX})), // Refused before anything is written: no format of that name, a time that is no time. ("addon.document.saveTimestampedCopy", json!({"format": "png", "folder": 7})), ("addon.document.saveTimestampedCopy", json!({"format": "svg", "time": [1e308], "folder": null})), diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 9503a35e44..2e5306677b 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,6 +1,6 @@ //! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools), //! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Divide into -//! Dashes ([`dashes`]) and Convert to Parametric Shape; the Anchor Inspector panel (the selected +//! Dashes ([`dashes`]), Expand Dashes into Paths and Convert to Parametric Shape; the Anchor Inspector panel (the selected //! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values, //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel //! ([`shape`]); and its tools' options dialog (a double-click on the tool). Everything acts through `addon.pathtools.*` and @@ -65,6 +65,7 @@ pub fn menu() -> Vec<Item> { Item::Cmd("Add Points at Crossings", "addon.pathtools.crossings", json!({})), Item::Cmd("Split at Crossings", "addon.pathtools.crossings", json!({ "cut": true })), Item::Cmd("Divide into Dashes…", dashes::COMMAND, Value::Null), + Item::Cmd("Expand Dashes into Paths", "addon.pathtools.expandDashes", json!({})), Item::Cmd("Convert to Parametric Shape", "addon.pathtools.shape.convert", json!({})), ] } diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index e69c930425..d477fa0363 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -33,6 +33,16 @@ fn the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector() { assert_eq!(e.command.as_deref(), Some("addon.pathtools.crossings")); assert_eq!(e.params.get("cut").and_then(|v| v.as_bool()).unwrap_or(false), cut); } + // Expand Dashes into Paths runs at once: a dashed line becomes its dashes. + let line = app.run("path.create", json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}]})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [line]})).unwrap(); + app.run("stroke.set", json!({"dash": [30, 10]})).unwrap(); + let expand = under("Expand Dashes into Paths").expect("listed"); + let (cmd, p) = menus::click_target(&expand.label, expand.command.as_deref().unwrap(), &expand.params); + menus::invoke(&mut app, &cmd, p); + let selected = app.session.doc().unwrap().selection.objects.len(); + assert!(selected >= 3, "three dashes selected: {selected}"); + app.run("edit.undo", json!({})).unwrap(); // Artwork Cleanup's submenu and Install Plug-in… are still there. assert!(entries.iter().any(|e| e.path == ["Object", "Plug-ins", "Artwork Cleanup"])); assert!(entries.iter().any(|e| e.path == ["Object", "Plug-ins"] && e.label == "Install Plug-in…")); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index b3bc7e8601..f69921d5d3 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5965,6 +5965,9 @@ breakText Glyphs Глифи Remove Gaps Премахване на разстоянията @msg that makes too many pieces (at most 100000): make the dashes longer така се получават твърде много части (най-много 100000): удължете тиретата @msg select paths, or segments, to divide изберете пътища или сегменти за разделяне +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Разширяване на тиретата в пътища +@msg select paths with dashed strokes to expand изберете пътища с прекъснат щрих за разширяване # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Инструменти за документи Save a Timestamped Copy Запазване на копие с дата и час diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index aaa5ec00f6..9048560989 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5998,6 +5998,9 @@ shape Open Otvoren Remove Gaps Ukloni razmake @msg that makes too many pieces (at most 100000): make the dashes longer to daje previše dijelova (najviše 100000): produžite crtice @msg select paths, or segments, to divide odaberite putanje ili segmente za dijeljenje +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Proširi crtice u putanje +@msg select paths with dashed strokes to expand odaberite putanje s isprekidanim potezom za proširivanje # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Alati za dokument Save a Timestamped Copy Sačuvaj kopiju s datumom i vremenom diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 5e309464e9..2eadca7c13 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6071,6 +6071,9 @@ breakText Glyphs Glifs Remove Gaps Elimina les separacions @msg that makes too many pieces (at most 100000): make the dashes longer això fa massa trossos (com a màxim 100000): allargueu els guions @msg select paths, or segments, to divide seleccioneu camins o segments per dividir +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Expandeix els guions en camins +@msg select paths with dashed strokes to expand seleccioneu camins amb traç discontinu per expandir # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Eines del document Save a Timestamped Copy Desa una còpia amb data i hora diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 700dcf26d3..d45c83723a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6081,6 +6081,9 @@ breakText Glyphs Glyfy Remove Gaps Odstranit mezery @msg that makes too many pieces (at most 100000): make the dashes longer tím vznikne příliš mnoho dílů (nejvýše 100000): prodlužte čárky @msg select paths, or segments, to divide vyberte cesty nebo segmenty k rozdělení +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Rozložit čárky na cesty +@msg select paths with dashed strokes to expand vyberte cesty s čárkovaným tahem k rozložení # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Nástroje dokumentu Save a Timestamped Copy Uložit kopii s datem a časem diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b4cb18ce09..74d5e43d6d 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5980,6 +5980,9 @@ breakText Glyphs Glyffer Remove Gaps Fjern mellemrum @msg that makes too many pieces (at most 100000): make the dashes longer det giver for mange stykker (højst 100000): gør stregerne længere @msg select paths, or segments, to divide vælg stier eller segmenter, der skal opdeles +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Udvid streger til stier +@msg select paths with dashed strokes to expand vælg stier med stiplet streg, der skal udvides # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Dokumentværktøjer Save a Timestamped Copy Gem en kopi med dato og klokkeslæt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 0f9001fa40..f1e17a4d33 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5666,6 +5666,9 @@ breakText Glyphs Glyphen Remove Gaps Lücken entfernen @msg that makes too many pieces (at most 100000): make the dashes longer das ergibt zu viele Teile (höchstens 100000): machen Sie die Striche länger @msg select paths, or segments, to divide wählen Sie Pfade oder Segmente zum Aufteilen aus +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Striche in Pfade umwandeln +@msg select paths with dashed strokes to expand wählen Sie Pfade mit gestrichelter Kontur zum Umwandeln aus # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Dokumentwerkzeuge Save a Timestamped Copy Kopie mit Zeitstempel speichern diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 931624d4d4..9c046d74f3 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6033,6 +6033,9 @@ breakText Glyphs Γλύφοι Remove Gaps Αφαίρεση κενών @msg that makes too many pieces (at most 100000): make the dashes longer αυτό δίνει πάρα πολλά κομμάτια (το πολύ 100000): κάντε τις παύλες μεγαλύτερες @msg select paths, or segments, to divide επιλέξτε διαδρομές ή τμήματα για διαίρεση +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Επέκταση παυλών σε διαδρομές +@msg select paths with dashed strokes to expand επιλέξτε διαδρομές με διακεκομμένο περίγραμμα για επέκταση # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Εργαλεία εγγράφου Save a Timestamped Copy Αποθήκευση αντιγράφου με ημερομηνία και ώρα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 7bb969e1bf..eaa3f66d70 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6023,6 +6023,9 @@ breakText Glyphs Glifos Remove Gaps Quitar separaciones @msg that makes too many pieces (at most 100000): make the dashes longer eso da demasiados trozos (como máximo 100000): alargue los guiones @msg select paths, or segments, to divide seleccione trazados o segmentos para dividir +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Expandir guiones en trazados +@msg select paths with dashed strokes to expand seleccione trazados con trazo discontinuo para expandir # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Herramientas de documento Save a Timestamped Copy Guardar una copia con fecha y hora diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a0017ed4d2..a4c7a87740 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6111,6 +6111,9 @@ breakText Glyphs Merkit Remove Gaps Poista välit @msg that makes too many pieces (at most 100000): make the dashes longer siitä tulee liian monta osaa (enintään 100000): pidennä viivoja @msg select paths, or segments, to divide valitse jaettavat polut tai segmentit +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Laajenna viivat poluiksi +@msg select paths with dashed strokes to expand valitse laajennettavat polut, joissa on katkoviiva # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Asiakirjatyökalut Save a Timestamped Copy Tallenna kopio aikaleimalla diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index a4c3483b79..774b000ba6 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6078,6 +6078,9 @@ breakText Glyphs Glyphes Remove Gaps Supprimer les écarts @msg that makes too many pieces (at most 100000): make the dashes longer cela donne trop de morceaux (100000 au plus) : allongez les tirets @msg select paths, or segments, to divide sélectionnez des tracés ou des segments à diviser +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Décomposer les tirets en tracés +@msg select paths with dashed strokes to expand sélectionnez des tracés à contour pointillé à décomposer # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Outils de document Save a Timestamped Copy Enregistrer une copie horodatée diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c44637ba98..46bb0c9917 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6067,6 +6067,9 @@ breakText Glyphs Glifák Remove Gaps Hézagok eltávolítása @msg that makes too many pieces (at most 100000): make the dashes longer ez túl sok darabot adna (legfeljebb 100000): hosszabbítsa meg a szaggatásokat @msg select paths, or segments, to divide jelöljön ki felosztandó útvonalakat vagy szakaszokat +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Szaggatások kibontása útvonalakká +@msg select paths with dashed strokes to expand jelöljön ki szaggatott körvonalú útvonalakat a kibontáshoz # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Dokumentumeszközök Save a Timestamped Copy Másolat mentése időbélyeggel diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e1b6202777..8e87dd93a0 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5980,6 +5980,9 @@ breakText Glyphs Glif Remove Gaps Hapus celah @msg that makes too many pieces (at most 100000): make the dashes longer itu menghasilkan terlalu banyak potongan (paling banyak 100000): perpanjang garisnya @msg select paths, or segments, to divide pilih jalur atau segmen yang akan dibagi +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Perluas garis putus menjadi jalur +@msg select paths with dashed strokes to expand pilih jalur dengan stroke putus-putus yang akan diperluas # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Alat dokumen Save a Timestamped Copy Simpan salinan bercap waktu diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 77d8c0a202..2cf4742605 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5700,6 +5700,9 @@ breakText Glyphs Glifi Remove Gaps Rimuovi le distanze @msg that makes too many pieces (at most 100000): make the dashes longer così si ottengono troppi pezzi (al massimo 100000): allunga i trattini @msg select paths, or segments, to divide seleziona tracciati o segmenti da dividere +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Espandi trattini in tracciati +@msg select paths with dashed strokes to expand seleziona tracciati con traccia tratteggiata da espandere # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Strumenti documento Save a Timestamped Copy Salva una copia con data e ora diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index fea3338489..8cdb79a678 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5767,6 +5767,9 @@ breakText Glyphs 字形 Remove Gaps 間隔を削除 @msg that makes too many pieces (at most 100000): make the dashes longer 分割数が多すぎます(最大 100000):ダッシュを長くしてください @msg select paths, or segments, to divide 分割するパスまたはセグメントを選択してください +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths 破線をパスに拡張 +@msg select paths with dashed strokes to expand 拡張する破線のパスを選択してください # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools ドキュメントツール Save a Timestamped Copy 日時付きのコピーを保存 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 586b59cc56..22894ea3b1 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6070,6 +6070,9 @@ breakText Glyphs გლიფები Remove Gaps ღრეჩოების მოცილება @msg that makes too many pieces (at most 100000): make the dashes longer ეს ძალიან ბევრ ნაწილს იძლევა (მაქსიმუმ 100000): გაზარდეთ ტირეების სიგრძე @msg select paths, or segments, to divide აირჩიეთ დასაყოფი კონტურები ან სეგმენტები +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths ტირეების კონტურებად გაშლა +@msg select paths with dashed strokes to expand აირჩიეთ გასაშლელი ტირეებიანი ხაზის კონტურები # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools დოკუმენტის ხელსაწყოები Save a Timestamped Copy ასლის შენახვა თარიღითა და დროით diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 05d5ed4e69..9c9d8dbd32 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5663,6 +5663,9 @@ breakText Glyphs 글리프 Remove Gaps 간격 제거 @msg that makes too many pieces (at most 100000): make the dashes longer 조각이 너무 많아집니다(최대 100000개). 대시를 더 길게 하십시오 @msg select paths, or segments, to divide 나눌 패스나 세그먼트를 선택하십시오 +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths 대시를 패스로 확장 +@msg select paths with dashed strokes to expand 확장할 점선 획의 패스를 선택하십시오 # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools 문서 도구 Save a Timestamped Copy 날짜와 시간이 붙은 사본 저장 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 98a89cc6b7..4918f150f7 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6024,6 +6024,9 @@ breakText Glyphs Glyphs Remove Gaps Tussenruimten verwijderen @msg that makes too many pieces (at most 100000): make the dashes longer dat geeft te veel stukken (hoogstens 100000): maak de streepjes langer @msg select paths, or segments, to divide selecteer paden of segmenten om te verdelen +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Streepjes uitbreiden tot paden +@msg select paths with dashed strokes to expand selecteer paden met een streepjeslijn om uit te breiden # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Documentgereedschappen Save a Timestamped Copy Een kopie met tijdstempel opslaan diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 08ab910c42..8d9e8ba9da 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5936,6 +5936,9 @@ breakText Glyphs Glify Remove Gaps Usuń odstępy @msg that makes too many pieces (at most 100000): make the dashes longer to daje za dużo części (najwyżej 100000): wydłuż kreski @msg select paths, or segments, to divide zaznacz ścieżki lub segmenty do podzielenia +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Rozszerz kreski na ścieżki +@msg select paths with dashed strokes to expand zaznacz ścieżki z przerywanym konturem do rozszerzenia # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Narzędzia dokumentu Save a Timestamped Copy Zapisz kopię z datą i godziną diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4c8c885726..b7aaabd1d6 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6000,6 +6000,9 @@ breakText Glyphs Glifos Remove Gaps Remover distâncias @msg that makes too many pieces (at most 100000): make the dashes longer isso gera peças demais (no máximo 100000): aumente os traços @msg select paths, or segments, to divide selecione demarcadores ou segmentos para dividir +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Expandir traços em demarcadores +@msg select paths with dashed strokes to expand selecione demarcadores com traçado tracejado para expandir # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Ferramentas de Documento Save a Timestamped Copy Salvar uma Cópia com Data e Hora diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d330e4ccc1..d9d95ae35e 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6058,6 +6058,9 @@ breakText Glyphs Глифы Remove Gaps Убрать зазоры @msg that makes too many pieces (at most 100000): make the dashes longer так получится слишком много частей (не более 100000): удлините штрихи @msg select paths, or segments, to divide выделите контуры или сегменты для разделения +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Разобрать штрихи на контуры +@msg select paths with dashed strokes to expand выделите контуры со штриховой обводкой для разбора # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Инструменты документа Save a Timestamped Copy Сохранить копию с датой и временем diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index d18203ddfe..e378d833fc 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6133,6 +6133,9 @@ breakText Glyphs Glyfer Remove Gaps Ta bort mellanrum @msg that makes too many pieces (at most 100000): make the dashes longer det blir för många delar (högst 100000): gör strecken längre @msg select paths, or segments, to divide markera banor eller segment att dela upp +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Expandera streck till banor +@msg select paths with dashed strokes to expand markera banor med streckad kontur att expandera # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Dokumentverktyg Save a Timestamped Copy Spara en kopia med tidsstämpel diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7bf6aa584d..981f2a3ecb 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6038,6 +6038,9 @@ breakText Glyphs Glifler Remove Gaps Boşlukları Kaldır @msg that makes too many pieces (at most 100000): make the dashes longer bu çok fazla parça oluşturur (en fazla 100000): tireleri uzatın @msg select paths, or segments, to divide bölünecek yolları veya bölümleri seçin +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Tireleri Yollara Genişlet +@msg select paths with dashed strokes to expand genişletilecek kesikli konturlu yolları seçin # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Belge Araçları Save a Timestamped Copy Zaman Damgalı Bir Kopya Kaydet diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index f4ed70ce24..4b4bda6bc6 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5680,6 +5680,9 @@ breakText Glyphs Гліфи Remove Gaps Прибрати проміжки @msg that makes too many pieces (at most 100000): make the dashes longer так вийде забагато частин (не більше 100000): подовжте штрихи @msg select paths, or segments, to divide виділіть контури або сегменти для розділення +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Розібрати штрихи на контури +@msg select paths with dashed strokes to expand виділіть контури зі штриховим обведенням для розбору # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Інструменти документа Save a Timestamped Copy Зберегти копію з датою і часом diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 82e7600d29..6b8c543302 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5683,6 +5683,9 @@ breakText Glyphs Glyph Remove Gaps Gỡ các khoảng hở @msg that makes too many pieces (at most 100000): make the dashes longer như vậy tạo ra quá nhiều mảnh (tối đa 100000): hãy kéo dài nét @msg select paths, or segments, to divide chọn các đường dẫn hoặc đoạn để chia +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths Mở rộng nét đứt thành đường dẫn +@msg select paths with dashed strokes to expand chọn các đường dẫn có nét đứt để mở rộng # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Công cụ tài liệu Save a Timestamped Copy Lưu bản sao có ngày giờ diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 9cba58ad33..a9d0563da0 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5923,6 +5923,9 @@ breakText Glyphs 字形 Remove Gaps 移除间隙 @msg that makes too many pieces (at most 100000): make the dashes longer 这会产生过多片段(最多 100000 个):请加长短划线 @msg select paths, or segments, to divide 请选择要分割的路径或线段 +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths 将短划线扩展为路径 +@msg select paths with dashed strokes to expand 请选择要扩展的虚线描边路径 # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools 文档工具 Save a Timestamped Copy 保存带时间戳的副本 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index ec99ae2e2b..ceec87f9d6 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5720,6 +5720,9 @@ breakText Glyphs 字符 Remove Gaps 移除間隙 @msg that makes too many pieces (at most 100000): make the dashes longer 這會產生過多片段(最多 100000 個):請加長短破折號 @msg select paths, or segments, to divide 請選取要分割的路徑或線段 +# Path Precision Tools add-on: Expand Dashes into Paths. + Expand Dashes into Paths 將短破折號展開為路徑 +@msg select paths with dashed strokes to expand 請選取要展開的虛線筆畫路徑 # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools 文件工具 Save a Timestamped Copy 儲存附時間戳記的拷貝 diff --git a/docs/mcp.md b/docs/mcp.md index 333d7e85b2..b1ca3a3477 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6071,6 +6071,17 @@ Commands: last piece of each run is what is left. The pieces are selected; more than 100,000 is refused. → `{ids, dashes}`. Divide into Dashes… opens a dialog (`ui.menuDialog {command}`, kind `divideDashes`) whose fields are these parameters, with Preview. +- `addon.pathtools.expandDashes {ids?}` turns the dashed stroke of each path and compound path under `ids` (default: + the selection) into separate open paths, one per dash, as one undo step (Object › Plug-ins › Path Precision Tools › + Expand Dashes into Paths). The dashes are laid out exactly as the stroke draws them: its dash pattern (an odd one + repeats with dashes and gaps swapped), its dash offset and Align Dashes to Corners and Path Ends, restarting on each + subpath and running on through the start of a closed one; a dash running all the way round a closed path stays + closed. Each dash keeps the path's appearance with the top stroke's dashes off, so the gaps become real gaps; with a + round or projecting cap a dash of no length (a dot) becomes a path on its point, which draws the cap (under a butt + cap it paints nothing, so it makes nothing). The stroke's arrowheads go, the line is first trimmed under them as + drawn, and the path's fills stay on it, below its dashes (a path without fills goes). A compound path's dashes are + plain paths with its appearance. Paths without a dashed stroke stay as they are, and it is an error if none has one. + The dashes are selected; more than 100,000 (or a pattern too fine to draw) is refused. → `{ids, dashes}`. - `addon.pathtools.cornerSet {ids?, anchors?, items?, radius, kind?}` cuts live corners, the ones Direct Selection's corner widgets and the Corners dialog edit, as one undo step. `ids` (default: the selection) are the paths and `anchors` the anchor indices of each path's outline with no corners cut; without `anchors`, a path's direct-selected diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index dd2f9c55a3..8bfe80641a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Glyphs panel highlights the character selected with the Type tool, #4908; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Path Precision Tools add-on: Expand Dashes into Paths, #4922; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -1430,6 +1430,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Divide into Dashes… cuts the selected paths into separate open paths along the curve (arc length, not straight distance): each `dash` long (0.01 to 1000000 pt, 10 by default) with `gap` between them (0 by default: the pieces touch); the gap pieces are left out unless Remove Gaps is off. With direct-selected segments (or anchors) only those runs are divided, the pattern running on across segments that follow one another, and the rest of such a path stays as pieces of its own. Fit to Corners and Ends gives every run between corners and ends a whole number of dashes, all stretched or squeezed alike so it starts and ends on a dash (a closed path without corners holds whole periods); otherwise the lengths are exact and each run's last piece is what is left. Every piece keeps the path's appearance and is selected; one undo step; at most 100000 pieces (more is refused). The dialog takes lengths in any unit and previews on the canvas. Tests: `dashes::tests` in `vectorcraft-pathops` (exact and fitted lengths, curves measured along them, picked segments on open and closed paths, the piece cap and bad patterns), `divide_into_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (gaps removed or kept, fitted lengths, the stroke kept, one undo step, selected segments only, bad params and too many pieces refused), `divide_into_dashes_opens_its_dialog_previews_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. +## Path Precision Tools add-on: Expand Dashes into Paths (2026-11-01) + +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns the dashed stroke of each selected path and compound path into separate open paths, one per dash, for cutters and plotters that need the centre lines rather than Outline Stroke's filled outlines. The dashes are laid out by the renderer's own dash code, so they match what the canvas draws: the dash pattern, its offset and Align Dashes to Corners and Path Ends, a dash running on through the start of a closed path, a dash all the way round staying closed, and under a round or projecting cap each dot (a dash of no length) as a path on its point. Each dash keeps the path's appearance with the top stroke's dashes and arrowheads off; the path's fills stay on it, below its dashes; a compound path's dashes are plain paths. One undo step; the dashes are selected; at most 100000 (more, or a pattern too fine to draw, is refused). Tests: `expand_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (the stroke kept with dashes off, the offset, one undo step, the fill kept below, dashes centred on corners when aligned, dots under round and butt caps, compound paths, refusals and the piece cap), `the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. + ## Document Tools add-on: Save a Timestamped Copy (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Document Tools › Save a Timestamped Copy writes a copy of the document named `<name>_YYYY-MM-DD_HH-MM.<ext>` (the date and time in UTC, through chrono; `-2`, `-3`… added when that name is taken) next to the document, or into a folder picked (the folder picker) when it was never saved, in the document's own format or another save format. It writes through File › Save a Copy's save, so the document keeps its path, title and modified state, no undo step is made, and the write stays inside the automation roots in force. It is off on the web, which has no clock. Tests: `cmd::addons::document::tests` in `vectorcraft-engine` (the name and place, numbered names, the document unchanged and its content in the copy, an unsaved document needing a folder, other formats, bad params refused, automation roots), `addons::document::tests` in `vectorcraft-ui-egui` (the submenu, beside the document, the folder picked or cancelled) and `command_sweep`. Commands: `docs/mcp.md` › Document Tools add-on. @@ -1446,6 +1450,7 @@ Symbols area (#4938), from the public symbol documentation ([create and place sy | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Path Precision Tools add-on (a VectorCraft addition): Expand Dashes into Paths (#4922); evidence added; scores unchanged. | | 2026-11-01 | minor | Type core: the Glyphs panel highlights the character selected with the Type tool and scrolls it into view (#4908); evidence added; scores unchanged. | | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Randomize Opacity (#4925); evidence added; scores unchanged. | | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Sort Objects (#4917); evidence added; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 6dc32fc855..221211281d 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Arrange Tools add-on: Sort Objects, #4917) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Path Precision Tools add-on: Expand Dashes into Paths, #4922) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -341,6 +341,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its seven tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.rs` and their tests; not a feature of the reference app, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns each selected path's dashed stroke into separate open paths, one per dash, laid out as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off; one undo step | done | #4922; `addon.pathtools.expandDashes` (in `crates/engine/src/cmd/addons/pathtools.rs`, using the renderer's dash layout) and its tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its four tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/shape.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its six tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | @@ -391,6 +392,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Path Precision Tools add-on (a VectorCraft addition): Expand Dashes into Paths (#4922); scores and estimates unchanged | | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Randomize Opacity (#4925); scores and estimates unchanged | | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Sort Objects (#4917); scores and estimates unchanged | | 2026-11-01 | minor | Blob Brush and Eraser: the tip's outline (size, angle, roundness, at the zoom) follows the pointer before and while painting, around a small centre dot, updating at once with `[` / `]` and Tool Options; precise cursors (Caps Lock) show only the crosshair (#4977); scores and estimates unchanged (estimated) | From c38607a5aed62151b4455887aacbf1a1f317ff04 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 19:02:04 -0700 Subject: [PATCH 240/260] Tests: .doc import fuzzing also damages the compound-file container A new text_import_fuzz case builds a valid Word 97-2003 document (version 3 or 4 compound file, its streams in the mini stream or in FAT sectors), checks that it places, and then damages the container itself: header fields, the sector and mini sector shifts, FAT and mini FAT entries, directory entry fields and stream sizes, single bytes, and truncation. Session::execute turns a panic into EngineError::Internal, so the cases in this file did not fail when an import panicked. They now go through no_panic, as import_fuzz.rs does. --- crates/engine/tests/text_import_fuzz.rs | 231 ++++++++++++++++++++++-- 1 file changed, 217 insertions(+), 14 deletions(-) diff --git a/crates/engine/tests/text_import_fuzz.rs b/crates/engine/tests/text_import_fuzz.rs index 3ea6f94d9a..1ea656a158 100644 --- a/crates/engine/tests/text_import_fuzz.rs +++ b/crates/engine/tests/text_import_fuzz.rs @@ -1,6 +1,6 @@ //! Untrusted text files placed with File → Place never crash: any bytes, with any Text Import //! Options, place as area type or fail with an error, and so do hostile RTF files, Word documents -//! and Word 97-2003 documents. +//! and Word 97-2003 documents, including ones whose compound file container is damaged. //! //! `PROPTEST_CASES=20000 cargo test -p vectorcraft-engine --test text_import_fuzz` runs a deeper search. // Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). @@ -38,8 +38,8 @@ proptest! { "replaceSpaces": spaces, }); let p = json!({"name": "fuzz.txt", "dataBase64": vectorcraft_format::base64_encode(&data), "text": text, "thumbnail": 8}); - let _ = s.execute("file.place.info", &p); - let _ = s.execute("file.place", &p); + let _ = no_panic(s.execute("file.place.info", &p)); + let _ = no_panic(s.execute("file.place", &p)); }); prop_assert!(r.is_ok(), "panicked: {:?}", r.err()); } @@ -55,8 +55,8 @@ proptest! { let mut s = vectorcraft_engine::Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&data), "thumbnail": 8}); - let _ = s.execute("file.place.info", &p); - let _ = s.execute("file.place", &p); + let _ = no_panic(s.execute("file.place.info", &p)); + let _ = no_panic(s.execute("file.place", &p)); }); prop_assert!(r.is_ok(), "panicked: {:?}", r.err()); } @@ -86,8 +86,8 @@ proptest! { let mut s = vectorcraft_engine::Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&data), "thumbnail": 8}); - let _ = s.execute("file.place.info", &p); - let _ = s.execute("file.place", &p); + let _ = no_panic(s.execute("file.place.info", &p)); + let _ = no_panic(s.execute("file.place", &p)); }); prop_assert!(r.is_ok(), "panicked: {:?}", r.err()); } @@ -117,20 +117,223 @@ proptest! { let i = at.index(stream.len()); stream[i] = byte; } - let mut cf = cfb::CompoundFile::create(std::io::Cursor::new(Vec::new())).unwrap(); - std::io::Write::write_all(&mut cf.create_stream("WordDocument").unwrap(), &wd).unwrap(); - std::io::Write::write_all(&mut cf.create_stream("1Table").unwrap(), &table).unwrap(); - cf.flush().unwrap(); - let data = cf.into_inner().into_inner(); + let data = compound_file(&wd, &table, cfb::Version::V4); let r = catch_quiet(|| { let mut s = vectorcraft_engine::Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&data), "thumbnail": 8}); - let _ = s.execute("file.place.info", &p); - let _ = s.execute("file.place", &p); + let _ = no_panic(s.execute("file.place.info", &p)); + let _ = no_panic(s.execute("file.place", &p)); }); prop_assert!(r.is_ok(), "panicked: {:?}", r.err()); } + + #[test] + fn any_damaged_doc_container_places_without_panics( + text in prop::collection::vec(prop::sample::select(DOC_CHARS.chars().collect::<Vec<_>>()), 1..60), + compressed in any::<bool>(), + v3 in any::<bool>(), + large in any::<bool>(), + damage in prop::collection::vec(arb_cfb_damage(), 1..4), + name in prop::sample::select(vec!["fuzz.doc", "fuzz.bin"]), + ) { + vectorcraft_text::FontDb::global().set_system_fallback(false); + // A letter first, so that the undamaged document has text to place. + let text: String = std::iter::once('a').chain(text).collect(); + let (mut wd, table) = word97(&text, compressed, &[], 0, &[], &[], &[]); + // Past the mini stream cutoff (4,096 bytes) the WordDocument stream is kept in sectors the + // FAT chains; below it, both streams are kept in the mini stream the mini FAT chains. + if large { + wd.resize(9000, 0); + } + let mut data = compound_file(&wd, &table, if v3 { cfb::Version::V3 } else { cfb::Version::V4 }); + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let p = json!({"name": "fuzz.doc", "dataBase64": vectorcraft_format::base64_encode(&data)}); + let placed = s.execute("file.place", &p); + prop_assert!(placed.is_ok(), "the undamaged document doesn't place: {:?}", placed.err()); + let layout = CfbLayout::of(&data); + for d in &damage { + d.apply(&mut data, &layout); + } + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&data), "thumbnail": 8}); + let _ = no_panic(s.execute("file.place.info", &p)); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "panicked: {:?}", r.err()); + } +} + +/// `r`, after failing the case if the command panicked. The engine's guard reports a panic as +/// `EngineError::Internal`. +fn no_panic(r: Result<serde_json::Value, vectorcraft_engine::EngineError>) -> Result<serde_json::Value, vectorcraft_engine::EngineError> { + if let Err(vectorcraft_engine::EngineError::Internal { cmd, msg }) = &r { + panic!("{cmd} panicked: {msg}"); + } + r +} + +/// A compound file of `version` holding the WordDocument stream `wd` and the table stream `table`. +fn compound_file(wd: &[u8], table: &[u8], version: cfb::Version) -> Vec<u8> { + let mut cf = cfb::CompoundFile::create_with_version(version, std::io::Cursor::new(Vec::new())).unwrap(); + std::io::Write::write_all(&mut cf.create_stream("WordDocument").unwrap(), wd).unwrap(); + std::io::Write::write_all(&mut cf.create_stream("1Table").unwrap(), table).unwrap(); + cf.flush().unwrap(); + cf.into_inner().into_inner() +} + +/// The compound file header's fields (\[MS-CFB\] §2.2) a damage changes: their offset and width. +const CFB_HEADER: [(usize, usize); 17] = [ + (0, 4), // signature + (24, 2), // minor version + (26, 2), // major version + (28, 2), // byte order + (30, 2), // sector shift + (32, 2), // mini sector shift + (40, 4), // directory sectors + (44, 4), // FAT sectors + (48, 4), // first directory sector + (52, 4), // transaction signature + (56, 4), // mini stream cutoff + (60, 4), // first mini FAT sector + (64, 4), // mini FAT sectors + (68, 4), // first DIFAT sector + (72, 4), // DIFAT sectors + (76, 4), // DIFAT[0] + (80, 4), // DIFAT[1] +]; + +/// A directory entry's fields (\[MS-CFB\] §2.6.1) a damage changes: their offset and width. +const CFB_ENTRY: [(usize, usize); 10] = [ + (0, 2), // first character of the name + (64, 2), // name length + (66, 1), // object type + (67, 1), // color + (68, 4), // left sibling + (72, 4), // right sibling + (76, 4), // child + (116, 4), // starting sector + (120, 4), // stream size, low + (124, 4), // stream size, high +]; + +/// Where an undamaged compound file keeps its directory, FAT and mini FAT. +struct CfbLayout { + /// The bytes of one sector. + sector: usize, + /// The offsets of the first directory sector, the first FAT sector and the first mini FAT + /// sector. + directory: usize, + fat: usize, + mini_fat: usize, +} + +impl CfbLayout { + fn of(data: &[u8]) -> Self { + let u32_at = |at: usize| u32::from_le_bytes(data[at..at + 4].try_into().unwrap()) as usize; + let sector = 1 << u16::from_le_bytes(data[30..32].try_into().unwrap()); + let at = |n: usize| (n + 1) * sector; + let layout = Self { sector, directory: at(u32_at(48)), fat: at(u32_at(76)), mini_fat: at(u32_at(60)) }; + // The root entry's name opens the directory, the FAT marks its own sector, and the mini FAT + // has a sector. + assert_eq!(&data[layout.directory..layout.directory + 4], b"R\0o\0"); + assert_eq!(u32_at(layout.fat + 4 * u32_at(76)), 0xFFFF_FFFD); + assert!(u32_at(64) >= 1); + layout + } +} + +/// A change to the container of a compound file rather than to the bytes of its streams. +#[derive(Clone, Debug)] +enum CfbDamage { + /// A header field set to a value. + Header(prop::sample::Index, u32), + /// A field of one of the first directory sector's entries set to a value. + Entry(prop::sample::Index, prop::sample::Index, u32), + /// An entry of the first FAT sector (the next sector of a chain) set to a value. + Fat(prop::sample::Index, u32), + /// An entry of the first mini FAT sector set to a value. + MiniFat(prop::sample::Index, u32), + /// A byte anywhere set to a value. + Byte(prop::sample::Index, u8), + /// The file cut short. + Truncate(prop::sample::Index), +} + +impl CfbDamage { + fn apply(&self, data: &mut Vec<u8>, layout: &CfbLayout) { + let mut put = |at: usize, width: usize, value: u32| { + if let Some(b) = data.get_mut(at..at + width) { + b.copy_from_slice(&value.to_le_bytes()[..width]); + } + }; + match self { + Self::Header(field, value) => { + let (at, width) = CFB_HEADER[field.index(CFB_HEADER.len())]; + put(at, width, *value); + } + Self::Entry(entry, field, value) => { + let (at, width) = CFB_ENTRY[field.index(CFB_ENTRY.len())]; + put(layout.directory + 128 * entry.index(layout.sector / 128) + at, width, *value); + } + Self::Fat(entry, value) => put(layout.fat + 4 * entry.index(layout.sector / 4), 4, *value), + Self::MiniFat(entry, value) => put(layout.mini_fat + 4 * entry.index(layout.sector / 4), 4, *value), + // A file cut to nothing has no byte to change and nothing to cut. + Self::Byte(..) | Self::Truncate(_) if data.is_empty() => {} + Self::Byte(at, value) => { + let i = at.index(data.len()); + data[i] = *value; + } + Self::Truncate(at) => data.truncate(at.index(data.len())), + } + } +} + +/// A sector number, size, count or shift: the special sector numbers (\[MS-CFB\] §2.1), small and +/// huge values, or any. +fn arb_cfb_value() -> impl Strategy<Value = u32> { + prop_oneof![ + 3 => prop::sample::select(vec![ + 0, + 1, + 2, + 3, + 6, + 7, + 9, + 12, + 13, + 16, + 31, + 64, + 0x1000, + 0x1001, + 0x7FFF_FFFF, + 0xFFFF_FFFA, + 0xFFFF_FFFB, + 0xFFFF_FFFC, + 0xFFFF_FFFD, + 0xFFFF_FFFE, + 0xFFFF_FFFF, + ]), + 1 => any::<u32>(), + ] +} + +/// A [`CfbDamage`]. +fn arb_cfb_damage() -> impl Strategy<Value = CfbDamage> { + let index = any::<prop::sample::Index>; + prop_oneof![ + 3 => (index(), arb_cfb_value()).prop_map(|(f, v)| CfbDamage::Header(f, v)), + 3 => (index(), index(), arb_cfb_value()).prop_map(|(e, f, v)| CfbDamage::Entry(e, f, v)), + 2 => (index(), arb_cfb_value()).prop_map(|(e, v)| CfbDamage::Fat(e, v)), + 2 => (index(), arb_cfb_value()).prop_map(|(e, v)| CfbDamage::MiniFat(e, v)), + 1 => (index(), any::<u8>()).prop_map(|(at, v)| CfbDamage::Byte(at, v)), + 1 => index().prop_map(CfbDamage::Truncate), + ] } /// Characters of a Word document's text: letters, marks of paragraphs, cells and breaks, fields, From b253356b4d2c812bc8a1ab8bc892094dda967e57 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 1 Nov 2026 09:24:13 +0700 Subject: [PATCH 241/260] Knife: a straight cut's ends snap to the anchors and paths Smart Guides snap to Squashed from #5044 onto main. --- crates/tools/src/draw2/gesture.rs | 48 ++++++++++-- crates/tools/src/draw2/gesture/tests.rs | 97 +++++++++++++++++++++++++ crates/tools/src/guides/snap.rs | 8 ++ crates/tools/src/guides/targets.rs | 55 +++++++++----- crates/tools/src/guides/tests.rs | 33 +++++++++ docs/target-app-parity.md | 1 + 6 files changed, 216 insertions(+), 26 deletions(-) diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index a3c3cd93ec..cdddc451cf 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -114,8 +114,11 @@ pub struct GestureTool { pub edit_within: f64, /// "Close paths when ends are within N pixels". pub close_within: f64, - /// Smart Guides for the Pencil's ends. + /// Smart Guides for the Pencil's ends and the press of a straight Knife cut. snap: DrawSnap, + /// Where the pointer went down, before any snap: a straight Knife cut released there cuts + /// nothing, even when its press snapped elsewhere. + pressed: Point, /// Where the Blob Brush's or the Eraser's tip outline shows: the pointer over the canvas, /// unless Cmd/Ctrl lends a selection tool or Alt the Smooth tool. tip_at: Option<Point>, @@ -194,6 +197,7 @@ impl GestureTool { edit_within: 12.0, close_within: 15.0, snap: DrawSnap::default(), + pressed: Point::ZERO, tip_at: None, } } @@ -203,6 +207,31 @@ impl GestureTool { self.id == "pencil" } + /// Does a straight Knife cut snap to anchors and paths? Only with Smart Guides on, which Snap to + /// Pixel and Snap to Grid turn off (`PointSnap::new`). Its ends snap as the Pencil's straight + /// line's do: the press, and the release unless Shift keeps it on a 45° step. + fn knife_snaps(&self, cx: &ToolContext) -> bool { + self.id == "knife" && self.straight && cx.smart_guides && !cx.snap_to_pixel && !cx.snap_to_grid + } + + /// Does the end of a straight line snap: the Pencil's Alt line's, or a straight Knife cut's + /// without Shift? + fn line_end_snaps(&self, cx: &ToolContext) -> bool { + self.straight && self.unconstrained && (self.snaps() || self.knife_snaps(cx)) + } + + /// Where a stroke or straight line released at `p` ends: where it snaps when its end snaps. + fn release_end(&mut self, cx: &ToolContext, p: Point) -> Point { + if (self.snaps() && !self.smoothing && !self.straight) || self.line_end_snaps(cx) { self.snap.drag(cx, p, None) } else { p } + } + + /// Is a straight line with its end at `end` back at its press point (within a pixel), so that + /// there is no line? A Knife cut also is when the pointer, at `pointer`, is back where it went + /// down, though its press snapped elsewhere. + fn back_at_press(&self, cx: &ToolContext, pointer: Point, end: Point) -> bool { + self.points.first().is_some_and(|s| s.distance(end) < cx.tol(1.0)) || (self.id == "knife" && self.pressed.distance(pointer) < cx.tol(1.0)) + } + fn draws_path(&self) -> bool { matches!(self.id, "pencil" | "paintbrush") } @@ -532,10 +561,14 @@ impl Tool for GestureTool { end } else if self.snaps() && !self.smoothing && self.extend.is_none() && self.redraw.is_none() { self.snap.press(cx, p, &[], None) + } else if self.knife_snaps(cx) { + // A straight Knife cut, its overlay and Shift's 45° steps start from the snapped point. + self.snap.press_on_paths(cx, p) } else { p }; self.clear(); + self.pressed = p; self.push(start, ev.pressure); vec![] } @@ -554,19 +587,20 @@ impl Tool for GestureTool { // Where the stroke would end: shown, taken on release. end = self.snap.drag(cx, p, None); } - let p = if self.straight && self.unconstrained && self.snaps() { - // Alt's line ends where a stroke would: shown, taken on release. + let p = if self.line_end_snaps(cx) { + // Alt's line ends where a stroke would, and a Knife cut's on the anchors and + // paths its press snaps to: shown, taken on release. self.snap.drag(cx, p, None) } else { p }; if self.straight { - if !self.unconstrained { + if !self.line_end_snaps(cx) { // The press's Smart Guides would stay on screen: the line's end doesn't snap. self.snap.clear(); } // The line runs from the press point to the pointer, wherever the drag went. - if self.points.first().is_some_and(|s| s.distance(p) < cx.tol(1.0)) { + if self.back_at_press(cx, ev.pos, p) { // Back at the press point there is no line: the one shown goes. self.points.truncate(1); return if std::mem::take(&mut self.began) { vec![Action::Cancel] } else { vec![] }; @@ -618,12 +652,12 @@ impl Tool for GestureTool { // Alt only on release cannot turn a freehand Knife drag into a straight cut. self.knife_shift(ev.mods); let p = self.constrained(cx, p, ev.mods); - let end = if self.snaps() && !self.smoothing && (!self.straight || self.unconstrained) { self.snap.drag(cx, p, None) } else { p }; + let end = self.release_end(cx, p); self.snap.clear(); let mut cancel = false; if self.straight { self.points.truncate(1); - if self.points.first().is_some_and(|s| s.distance(end) >= cx.tol(1.0)) { + if !self.back_at_press(cx, ev.pos, end) { self.push(end, ev.pressure); } else { cancel = self.began; diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 29fe7614fa..d9bd9a3658 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -1351,6 +1351,103 @@ fn knife_shift_alt_cuts_at_45_degree_steps() { assert_eq!(knife_points(acts.last().unwrap()), vec![(0.0, 0.0), (30.0, -10.0), (50.0, -60.0)]); } +/// With Smart Guides on, a straight Knife cut starts at the anchor or path its press snaps to, +/// and its release snaps the same way, as the Pencil's straight line's ends do. Centers and lines +/// up do not move the press. The overlay shows the same line. +#[test] +fn knife_alt_cut_snaps_where_smart_guides_snap() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Default::default() }; + let mut t = GestureTool::new("knife"); + // Near the rectangle's corner anchor: the cut starts on it, and the release near the opposite + // corner ends on that one. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 101.0, 99.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 201.0, 198.0).with_mods(alt)); + assert_eq!(overlay_points(&t, &cx), vec![(100.0, 100.0), (200.0, 200.0)]); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 201.0, 198.0).with_mods(alt)); + assert_eq!(knife_points(&a), vec![(100.0, 100.0), (200.0, 200.0)]); + assert!(t.overlays(&cx).is_empty()); + // Near the top side, away from its anchors: the cut starts on the path. + let acts = drag_held(&mut t, &cx, &[(130.0, 101.5), (260.0, 240.0)], alt); + assert_eq!(knife_points(acts.last().unwrap()), vec![(130.0, 100.0), (260.0, 240.0)]); + // Near the rectangle's center, or in line with its top side, the press stays where it is. + for press in [(151.0, 149.0), (50.0, 101.5)] { + let acts = drag_held(&mut t, &cx, &[press, (260.0, 240.0)], alt); + assert_eq!(knife_points(acts.last().unwrap()), vec![press, (260.0, 240.0)]); + } + // An Alt-click on the snapped press cuts nothing, and neither does a drag back to where the + // pointer went down. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 101.0, 99.0).with_mods(alt)); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 101.0, 99.0).with_mods(alt)), vec![]); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 101.0, 99.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 201.0, 198.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 101.2, 99.0).with_mods(alt)); + assert!(!t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Path { dashed: true, .. })), "the line goes"); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 101.2, 99.0).with_mods(alt)), vec![]); + // A freehand cut keeps its press. + let acts = drag(&mut t, &cx, &[(101.0, 99.0), (150.0, 120.0), (201.0, 198.0)], Mods::default()); + assert_eq!(knife_points(acts.last().unwrap()), vec![(101.0, 99.0), (150.0, 120.0), (201.0, 198.0)]); +} + +/// With Smart Guides off, a straight Knife cut starts where it is pressed, with Snap to Point on +/// or off. +#[test] +fn knife_alt_cut_without_smart_guides_keeps_its_press() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + let alt = Mods { alt: true, ..Default::default() }; + let mut t = GestureTool::new("knife"); + for snap_to_point in [false, true] { + cx.snap_to_point = snap_to_point; + let acts = drag_held(&mut t, &cx, &[(101.0, 99.0), (201.0, 198.0)], alt); + assert_eq!(knife_points(acts.last().unwrap()), vec![(101.0, 99.0), (201.0, 198.0)], "Snap to Point {snap_to_point}"); + } +} + +/// With Smart Guides on, a straight Knife cut does not start on art in a hidden layer, whose own +/// visibility is still on. +#[test] +fn knife_alt_cut_does_not_snap_to_hidden_art() { + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + d.node_mut(l).unwrap().visible = false; + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Default::default() }; + let mut t = GestureTool::new("knife"); + let acts = drag_held(&mut t, &cx, &[(101.0, 99.0), (201.0, 198.0)], alt); + assert_eq!(knife_points(acts.last().unwrap()), vec![(101.0, 99.0), (201.0, 198.0)]); +} + +/// With Smart Guides on, Shift and Alt keep the Knife's cut at 45° steps from the snapped press, +/// and an anchor near the release does not pull the cut off that step. +#[test] +fn knife_shift_alt_cut_steps_from_the_snapped_press() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let shift_alt = Mods { shift: true, alt: true, ..Default::default() }; + let mut t = GestureTool::new("knife"); + // Pressed by the bottom-left corner, released by the top-right one. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 101.0, 199.0).with_mods(shift_alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 203.0, 104.0).with_mods(shift_alt)); + let shown = overlay_points(&t, &cx); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 203.0, 104.0).with_mods(shift_alt)); + let cut = knife_points(&a); + assert_eq!(shown, cut); + assert_eq!(cut[0], (100.0, 200.0)); + let step = 103f64.hypot(96.0) / 2f64.sqrt(); + assert!((cut[1].0 - (100.0 + step)).abs() < 1e-9 && (cut[1].1 - (200.0 - step)).abs() < 1e-9, "{cut:?}"); +} + /// The Eraser's Angle and Roundness (Eraser Tool Options) go with its stroke, kept within /// −180–180° and 1–100%; while it drags, a tip that is not round shows the outline of the area /// it covers, and a round one the drag as wide as the tip. diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index 4766455f88..0b117b95b5 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -348,6 +348,14 @@ impl DrawSnap { self.snap(cx, p, from) } + /// Snap the point pressed at `p` onto the art's anchors and paths alone, within the Smart + /// Guides snapping tolerance (the Knife's straight cut). The targets serve this press only. + pub fn press_on_paths(&mut self, cx: &ToolContext, p: Point) -> Point { + let targets = Targets::for_drawing(cx.doc, &[], visible(cx), None).styled(cx).anchors_and_paths(); + self.targets = Some((None, PointSnap { targets: Some((targets, cx.snapping_tolerance)) })); + self.snap(cx, p, None) + } + /// Gather `targets` other than the art for the drag a press starts (a point being dragged /// leaves itself out); the next hover gathers its own again. pub fn hold(&mut self, cx: &ToolContext, targets: impl FnOnce() -> Targets) { diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index edddd1a485..36947c9314 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -81,11 +81,11 @@ fn within<T>(sorted: &[T], key: impl Fn(&T) -> f64, v: f64, tol: f64) -> &[T] { sorted.get(lo..hi).unwrap_or_default() } -/// Visit `nodes` and everything inside them, but the nodes in `skip` and everything inside those: -/// one pass, however many are skipped. A Shaper Group's original shapes, its first child, are -/// not shown and are skipped too. +/// Visit `nodes` and everything inside them, but the nodes in `skip`, the hidden nodes and +/// everything inside those: one pass, however many are skipped. A Shaper Group's original +/// shapes, its first child, are not shown and are skipped too. fn walk_but<'a>(nodes: &'a [Arc<Node>], skip: &HashSet<NodeId>, f: &mut impl FnMut(&'a Node)) { - for n in nodes.iter().filter(|n| !skip.contains(&n.id)) { + for n in nodes.iter().filter(|n| n.visible && !skip.contains(&n.id)) { f(n); if let Some(ch) = n.children() { walk_but(ch.get(usize::from(n.extras().shaper.is_some())..).unwrap_or_default(), skip, f); @@ -500,6 +500,19 @@ impl Targets { self } + /// Only these targets' anchors and path segments pull, and where segments cross: no centers, + /// bounds, lines up, extensions or glyph guides. + pub(super) fn anchors_and_paths(mut self) -> Self { + self.points.retain(|(_, k)| *k == Kind::Anchor); + self.xs.clear(); + self.ys.clear(); + self.rulers.clear(); + self.boxes.clear(); + self.extensions.clear(); + self.angled.clear(); + self + } + /// View → Snap to Point: only these targets' anchors pull, and the ruler guides (shown and /// unlocked, as the selection tools pick them) pull the pointer into line where they run. pub(super) fn for_snap_to_point(self, cx: &ToolContext) -> Self { @@ -550,23 +563,27 @@ impl Targets { } /// Anchors and centres of the visible leaves under `roots` (the roots included) whose bounds - /// reach into `near`. + /// reach into `near`. Nothing inside a hidden group or layer counts. pub(super) fn points_near(doc: &Document, roots: &[NodeId], near: Rect) -> Self { let mut t = Targets::default(); - for n in roots.iter().filter_map(|id| doc.node(*id)) { - crate::draw2::walk_shown(n, &mut |c| { - if c.is_container() || !c.visible { - return; - } - let Some(b) = c.geometric_bounds() else { return }; - if b.x0 > near.x1 || b.x1 < near.x0 || b.y0 > near.y1 || b.y1 < near.y0 { - return; - } - if let NodeKind::Path { path, .. } = &c.kind { - t.points.extend(path.anchors().map(|(_, _, a)| (a.p, Kind::Anchor))); - } - t.points.push((b.center(), Kind::Center)); - }); + let mut push = |c: &Node| { + if c.is_container() { + return; + } + let Some(b) = c.geometric_bounds() else { return }; + if b.x0 > near.x1 || b.x1 < near.x0 || b.y0 > near.y1 || b.y1 < near.y0 { + return; + } + if let NodeKind::Path { path, .. } = &c.kind { + t.points.extend(path.anchors().map(|(_, _, a)| (a.p, Kind::Anchor))); + } + t.points.push((b.center(), Kind::Center)); + }; + for n in roots.iter().filter_map(|id| doc.node(*id)).filter(|n| n.visible) { + push(n); + if let Some(ch) = n.children() { + walk_but(ch.get(usize::from(n.extras().shaper.is_some())..).unwrap_or_default(), &HashSet::new(), &mut push); + } } t.index() } diff --git a/crates/tools/src/guides/tests.rs b/crates/tools/src/guides/tests.rs index 7ecdc2f1c9..e82618fb36 100644 --- a/crates/tools/src/guides/tests.rs +++ b/crates/tools/src/guides/tests.rs @@ -260,6 +260,39 @@ fn shaper_sources_are_no_targets() { assert!(gives_corner(&Targets::points_near(&d, &[b], near))); } +/// Art inside a hidden group or layer is no target, even while its own visibility is on: not +/// for drawing, the Knife's straight cut, a move or a transform tool's reference point on the +/// shown group around it. +#[test] +fn art_in_hidden_groups_and_layers_is_no_target() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, Node}; + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let square = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(300.0, 300.0, 400.0, 400.0)), Appearance::default_art()); + let mut inner = Node::group(d.alloc_id(), vec![Arc::new(square)]); + inner.visible = false; + let outer = Node::group(d.alloc_id(), vec![Arc::new(inner)]); + let g = outer.id; + d.insert(Some(l), 1, outer).unwrap(); + let corner = Point::new(300.0, 300.0); + let gives = |t: &Targets, at: Point| { + t.points.iter().any(|(p, _)| *p == at) + || t.xs.iter().chain(&t.ys).any(|(_, p, _)| *p == at) + || t.segments.iter().any(|(_, s)| s.start() == at || s.end() == at) + }; + assert!(!gives(&Targets::collect(&d, &[], None), corner)); + assert!(!gives(&Targets::for_drawing(&d, &[], None, None), corner)); + assert!(!gives(&Targets::for_drawing(&d, &[], None, None).anchors_and_paths(), corner)); + assert!(!gives(&Targets::points_near(&d, &[g], Rect::new(296.0, 296.0, 304.0, 304.0)), corner)); + // The shown rectangle on the same layer still is one, until the layer is hidden. + let shown = Point::new(100.0, 100.0); + assert!(gives(&Targets::for_drawing(&d, &[], None, None).anchors_and_paths(), shown)); + d.node_mut(l).unwrap().visible = false; + assert!(!gives(&Targets::collect(&d, &[], None), shown)); + assert!(!gives(&Targets::for_drawing(&d, &[], None, None).anchors_and_paths(), shown)); +} + /// #2120: the dragged end of a straight segment at any angle lands on the segment's own /// extension (Line Extension), past its other end or short of it, the guide drawn from that /// end; with two anchors moving there is none to keep to. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8bfe80641a..c5588ef6d8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -705,6 +705,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes). While Alt is held, the Scissors tool works as the Add Anchor Point tool ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): a click on a segment adds an anchor point without cutting (`path.insertAnchor`), and the pointer shows the Add Anchor Point cursor. When Alt is let go, a click cuts again. Alt-drag with the Knife cuts in a straight line, and Shift+Alt-drag cuts at 45° or 90°, as [Cut objects using the Knife and Scissors tools](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) and [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) describe. Alt counts only when held at the press; the dashed line runs from the press point to the pointer, stays straight after Alt is let go, and release sends `path.knife` with those two points. Alt pressed after the press leaves the cut freehand. Shift+Alt keeps the endpoint at 45° steps from the horizontal and vertical, whatever the Constrain Angle. + With Smart Guides on, a straight Knife cut snaps to anchor points and paths: [Cut objects using the Knife and Scissors tools](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) describes the Knife snapping to anchor points and paths while Smart Guides are on. Its ends snap as the ends of the Pencil's straight line do, to anchor points and path segments of art that is shown: the press, and the release of an Alt-drag. Shift+Alt steps 45° from the snapped press, and its release stays on that step. With Smart Guides off, or with Snap to Pixel or Snap to Grid on, the cut is not snapped. The dashed line and `path.knife` use the snapped points. Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`). - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). From 8362b7532c13798ea2ff9816dcf291570d84a212 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 1 Nov 2026 09:24:18 +0700 Subject: [PATCH 242/260] Eyedropper: Shift-click samples a blend's steps and an envelope's distorted art Squashed from #4949 onto main. --- crates/doc/src/blend.rs | 23 ++- crates/doc/src/hit.rs | 164 +++++++++++++++++- crates/doc/src/hit/tests.rs | 145 ++++++++++++++++ crates/doc/src/node/ops.rs | 8 +- crates/engine/src/session/documents.rs | 5 + crates/tools/src/xform/eyedropper.rs | 224 ++++++++++++++++++++++++- 6 files changed, 558 insertions(+), 11 deletions(-) diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index ced9472a74..ce20d29cd8 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -20,7 +20,7 @@ use std::sync::Arc; use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint}; use vectorcraft_geom::kurbo::ParamCurveArclen; -use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, SubPath, Vec2}; +use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2}; use crate::appearance::{Appearance, AppearanceItem, Dash, StrokeLayer, WidthProfile}; use crate::live::{BlendOrientation, BlendSpacing, BlendSpec}; @@ -1029,6 +1029,27 @@ impl Rail { } } +/// A box round everything a blend of `keys` can paint once [`Rail::place`] puts its keys and steps +/// on its spine, turned to it with Align to Path: the spine's box grown by three times the farthest +/// any key paints from its centre. A step's shape lies within that distance of the point on the +/// spine it is moved to, and so does its own centre, which it turns about. `None` when nothing +/// moves. +pub(crate) fn rail_reach(keys: &[Arc<Node>], spec: &BlendSpec, symbols: Option<&crate::SymbolBoxes>) -> Option<Rect> { + if spec.spine.is_none() && spec.orientation != BlendOrientation::AlignToPath { + return None; + } + let spine = blend_spine(keys, spec)?.0.bounds()?; + let radius = keys + .iter() + .filter_map(|k| { + let (c, b) = (center_of(k), k.visual(symbols)?); + let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)]; + Some(corners.into_iter().map(|q| (q - c).hypot()).fold(0.0, f64::max)) + }) + .fold(0.0, f64::max); + Some(spine.inflate(3.0 * radius, 3.0 * radius)) +} + // ===================================================================================== // Blend evaluation // ===================================================================================== diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index b754e0d565..d20c1ffe4e 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -1,7 +1,9 @@ //! Hit testing over the document tree. +use std::cell::RefCell; use std::collections::HashSet; -use std::sync::OnceLock; +use std::rc::Rc; +use std::sync::{Arc, OnceLock}; use vectorcraft_geom::hit::{fill_contains, stroke_contains}; use vectorcraft_geom::{BezPath, FillRule, Point, Rect}; @@ -99,6 +101,128 @@ pub(crate) fn image_paint(n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(n)) } +/// One level of evaluation of a live object in a document, as the canvas draws it: type in an +/// envelope as its distorted glyph outlines, symbol instances as their art. Effects are evaluated +/// above this crate, so the engine registers one with [`set_live_art`]. It reads the object, the +/// document's symbols and patterns, and what [`LiveInputs`] stands for, and nothing else. +pub type LiveArt = fn(Option<&Document>, &Node) -> Vec<Node>; + +/// A number that changes whenever something outside the document that [`LiveArt`] reads changes, +/// such as the installed fonts or the plug-ins. +pub type LiveInputs = fn() -> u64; + +static LIVE_ART: OnceLock<(LiveArt, LiveInputs)> = OnceLock::new(); + +/// Register how a live object's art is evaluated for clicks, and the number that changes with what +/// else it reads (the first registration stays). +pub fn set_live_art(f: LiveArt, inputs: LiveInputs) { + // Already set: the same engine, registered by another session. + let _ = LIVE_ART.set((f, inputs)); +} + +/// The registered [`LiveInputs`] now, 0 while nothing is registered. +fn live_inputs() -> u64 { + LIVE_ART.get().map_or(0, |(_, inputs)| inputs()) +} + +/// A live object evaluated by [`live_art`] on this thread: the object, its document's symbols (by +/// name and art) and patterns and the [`LiveInputs`] as they were, the art and its [`art_size`]. +struct EvaluatedLive { + node: Node, + symbols: Vec<(String, Arc<Node>)>, + patterns: Vec<crate::PatternDef>, + inputs: u64, + art: Rc<Vec<Node>>, + size: usize, +} + +impl EvaluatedLive { + /// Is this the evaluation of `n` in `doc`, with inputs `inputs`, as they are now? + fn is_of(&self, doc: &Document, n: &Node, inputs: u64) -> bool { + self.inputs == inputs + && self.symbols.len() == doc.symbols.len() + && self.symbols.iter().zip(&doc.symbols).all(|((name, art), s)| *name == s.name && Arc::ptr_eq(art, &s.art)) + && self.node == *n + && self.patterns == doc.patterns + } +} + +/// How many evaluations [`live_art`] keeps on each thread: the pointer moving in a blend's or an +/// envelope's stroke band hits it again and again, and an envelope can hold a blend. +const LIVE_KEPT: usize = 4; + +/// Most [`art_size`] the evaluations [`live_art`] keeps on one thread add up to. Art larger than +/// this is not kept. +const LIVE_KEPT_SIZE: usize = 250_000; + +/// The size of `art` for [`LIVE_KEPT_SIZE`]: its objects and the anchors of their paths. +fn art_size(art: &[Node]) -> usize { + let mut size = 0usize; + for n in art { + n.walk(&mut |c| size = size.saturating_add(1 + c.path_data().map_or(0, |p| p.anchor_count()))); + } + size +} + +/// Does `n`, or the art of a symbol or a pattern of `doc`, hold a placed document? Its art changes +/// when the file is read, so [`live_art`] does not keep an evaluation of `n`. +fn holds_placed(doc: &Document, n: &Node) -> bool { + let mut placed = false; + let mut find = |c: &Node| placed |= matches!(c.kind, NodeKind::PlacedDocument(_)); + n.walk(&mut find); + doc.symbols.iter().for_each(|s| s.art.walk(&mut find)); + doc.patterns.iter().flat_map(|p| &p.art).for_each(|a| a.walk(&mut find)); + placed +} + +thread_local! { + /// The evaluations [`live_art`] keeps, the latest first. + static EVALUATED: RefCell<Vec<EvaluatedLive>> = const { RefCell::new(Vec::new()) }; +} + +/// The art live object `n` of `doc` draws ([`set_live_art`]); [`crate::live::expand_live`] while +/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc`, a pattern of +/// `doc` or the [`LiveInputs`] have changed since, and on every click while it or the document's +/// symbols or patterns hold a placed document ([`holds_placed`]). +fn live_art(doc: &Document, n: &Node) -> Rc<Vec<Node>> { + let inputs = live_inputs(); + let kept = EVALUATED.with_borrow_mut(|kept| { + let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?; + let e = kept.remove(i); + let art = e.art.clone(); + kept.insert(0, e); + Some(art) + }); + if let Some(art) = kept { + return art; + } + #[cfg(test)] + LIVE_EVALUATED.with(|c| c.set(c.get() + 1)); + let art = Rc::new(LIVE_ART.get().map_or_else(|| crate::live::expand_live(n), |(f, _)| f(Some(doc), n))); + let size = art_size(&art); + if size > LIVE_KEPT_SIZE || holds_placed(doc, n) { + return art; + } + let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(); + let e = EvaluatedLive { node: n.clone(), symbols, patterns: doc.patterns.clone(), inputs, art: art.clone(), size }; + EVALUATED.with_borrow_mut(|kept| { + kept.insert(0, e); + kept.truncate(LIVE_KEPT); + let mut total = 0usize; + kept.retain(|e| { + total = total.saturating_add(e.size); + total <= LIVE_KEPT_SIZE + }); + }); + art +} + +#[cfg(test)] +thread_local! { + /// How many live objects [`live_art`] evaluated on this thread. + static LIVE_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + /// Topmost editable object under `p`. pub fn hit_test(doc: &Document, p: Point, opt: HitOptions) -> Option<Hit> { hit_test_skipping(doc, p, opt, &|_| false, true) @@ -565,7 +689,15 @@ fn hit_stroke(n: &Node, bp: &vectorcraft_geom::BezPath, rule: vectorcraft_geom:: stroke_contains(bp, 0.0, opt.tol, p).then_some(HitKind::Outline) } +#[cfg(test)] +thread_local! { + /// How many objects [`hit_leaf`] tested on this thread. + static LEAVES_TESTED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> { + #[cfg(test)] + LEAVES_TESTED.with(|c| c.set(c.get() + 1)); match &n.kind { NodeKind::Path { path, rule, .. } => { let bp = path.to_bezpath(); @@ -612,9 +744,18 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill), }) } - NodeKind::Text(_) | NodeKind::PlacedDocument(_) | NodeKind::SymbolInstance { .. } | NodeKind::Blend { .. } | NodeKind::Envelope { .. } => { + NodeKind::Text(_) | NodeKind::PlacedDocument(_) | NodeKind::SymbolInstance { .. } => { n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds) } + // A blend or an envelope is hit within its bounds, and outside them where its evaluated + // art paints: a blend's keys and steps on a spine can reach past the keys and the spine, + // and the strokes of an envelope's distorted contents past its bounds. + NodeKind::Blend { .. } | NodeKind::Envelope { .. } => { + if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) { + return Some(HitKind::Bounds); + } + live_art(symbols.document(), n).iter().find_map(|g| hit_any(g, p, opt, symbols)) + } NodeKind::Repeat(r) => r.expand(Some(symbols.document())).iter().find_map(|g| hit_any(g, p, opt, symbols)), NodeKind::Mesh(m) => { let bp = m.outline().to_bezpath(); @@ -651,8 +792,25 @@ fn on_type_path(n: &Node, t: &crate::TextObject, p: Point, tol: f64) -> bool { /// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]). fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> { + // Hidden art does not hit. + if !n.visible { + return None; + } + // Nor art whose reach does not hold `p`, as in [`may_hit`]: a blend's steps far from `p` are + // passed by without being measured. + if !edits_contents(n) && n.extras().shaper.is_none() && n.reach_bounds_with(symbols).is_some_and(|b| !b.inflate(opt.tol, opt.tol).contains(p)) { + return None; + } match &n.kind { - NodeKind::Group { children, .. } => children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)), + // A clip group only hits inside its clipping path. + NodeKind::Group { children, clip } => { + if *clip && children.first().is_some_and(|c| !clip_contains(c, p)) { + return None; + } + children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)) + } + // An intertwine group hits by its members, as on the canvas. + NodeKind::Intertwine { children } => children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)), _ => hit_leaf(n, p, opt, symbols), } } diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index e5ee6c4c8e..c4d6c565e0 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -429,6 +429,151 @@ fn a_marquee_meets_blends_and_envelopes_by_their_box() { } } +/// A click just outside a blend's bounds, in the reach of its keys' strokes, tests only the steps +/// whose own reach holds the point, not every step of the evaluated blend. +#[test] +fn a_click_in_a_blends_stroke_band_tests_only_the_steps_that_reach_it() { + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + // 10 pt circles with 4 pt strokes, y 295 to 305, from x 10 to x 890: 200 steps about 4.3 pt apart. + let stroked = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0); + let circle = |id, x: f64| Arc::new(Node::path(id, shapes::ellipse(Rect::new(x, 295.0, x + 10.0, 305.0)), stroked.clone())); + let blend = d.alloc_id(); + let keys = vec![circle(d.alloc_id(), 10.0), circle(d.alloc_id(), 880.0)]; + let spec = crate::live::BlendSpec { spacing: crate::live::BlendSpacing::Steps(200), ..Default::default() }; + d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Box::new(spec) })).unwrap(); + let count = |p: Point| { + LEAVES_TESTED.with(|c| c.set(0)); + let h = hit_test(&d, p, HitOptions::default()).map(|h| h.leaf); + (h, LEAVES_TESTED.with(std::cell::Cell::get)) + }; + // On the steps' strokes halfway between the keys, 4 pt above the bounds: a few steps reach it. + let (h, tested) = count(Point::new(450.0, 291.0)); + assert_eq!(h, Some(blend)); + assert!(tested < 20, "{tested} objects tested"); + // In the corner of the reach, outside every stroke: nothing hits. + let (h, tested) = count(Point::new(6.0, 291.0)); + assert_eq!(h, None); + assert!(tested < 20, "{tested} objects tested"); +} + +/// An intertwine group in a live object's evaluated art (a blend key a spine moves) hits by its +/// members. +#[test] +fn evaluated_art_hits_an_intertwine_group_by_its_members() { + let d = Document::new(200.0, 200.0); + let square = Arc::new(Node::path(NodeId(7), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art())); + let group = Node::new(NodeId(8), NodeKind::Intertwine { children: vec![square] }); + let symbols = d.symbol_boxes(); + assert_eq!(hit_any(&group, Point::new(10.0, 10.0), HitOptions::default(), &symbols), Some(HitKind::Fill)); + assert_eq!(hit_any(&group, Point::new(50.0, 50.0), HitOptions::default(), &symbols), None); +} + +/// The pointer moving in a blend's stroke band evaluates the blend once, and again after the blend +/// or a symbol of the document changes. +#[test] +fn clicks_in_a_blends_stroke_band_evaluate_it_once_until_it_changes() { + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let stroked = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0); + let circle = |id, x: f64| Arc::new(Node::path(id, shapes::ellipse(Rect::new(x, 295.0, x + 10.0, 305.0)), stroked.clone())); + let blend = d.alloc_id(); + let keys = vec![circle(d.alloc_id(), 10.0), circle(d.alloc_id(), 880.0)]; + let spec = crate::live::BlendSpec { spacing: crate::live::BlendSpacing::Steps(200), ..Default::default() }; + d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Box::new(spec) })).unwrap(); + let evaluated = || LIVE_EVALUATED.with(std::cell::Cell::get); + let before = evaluated(); + for x in [448.0, 450.0, 452.0] { + assert_eq!(hit_test(&d, Point::new(x, 291.0), HitOptions::default()).map(|h| h.leaf), Some(blend)); + } + assert_eq!(evaluated(), before + 1); + // 100 steps 8.7 pt apart: a step still reaches (450, 291). + if let Some(NodeKind::Blend { spec, .. }) = d.node_mut(blend).map(|n| &mut n.kind) { + spec.spacing = crate::live::BlendSpacing::Steps(100); + } + assert_eq!(hit_test(&d, Point::new(450.0, 291.0), HitOptions::default()).map(|h| h.leaf), Some(blend)); + assert_eq!(evaluated(), before + 2); + let art = circle(d.alloc_id(), 0.0); + d.symbols.push(crate::Symbol { dynamic: false, name: "dot".into(), art }); + hit_test(&d, Point::new(450.0, 291.0), HitOptions::default()); + assert_eq!(evaluated(), before + 3); + hit_test(&d, Point::new(450.0, 291.0), HitOptions::default()); + assert_eq!(evaluated(), before + 3); +} + +/// Evaluated art larger than [`LIVE_KEPT_SIZE`] is not kept: each click in the blend's stroke band +/// evaluates it again. +#[test] +fn evaluated_art_past_the_kept_size_is_not_kept() { + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let stroked = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0); + // A 10 pt circle drawn with 2,000 anchors: 202 objects of 2,000 anchors each with 200 steps. + let circle = |id, x: f64| { + let points: Vec<Point> = (0..2000) + .map(|i| { + let a = f64::from(i) * std::f64::consts::TAU / 2000.0; + Point::new(x + 5.0 + 5.0 * a.cos(), 300.0 + 5.0 * a.sin()) + }) + .collect(); + let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&points, true)); + Arc::new(Node::path(id, path, stroked.clone())) + }; + let blend = d.alloc_id(); + let keys = vec![circle(d.alloc_id(), 10.0), circle(d.alloc_id(), 880.0)]; + let spec = crate::live::BlendSpec { spacing: crate::live::BlendSpacing::Steps(200), ..Default::default() }; + d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Box::new(spec) })).unwrap(); + let evaluated = || LIVE_EVALUATED.with(std::cell::Cell::get); + let before = evaluated(); + for x in [448.0, 450.0] { + assert_eq!(hit_test(&d, Point::new(x, 291.0), HitOptions::default()).map(|h| h.leaf), Some(blend)); + } + assert_eq!(evaluated(), before + 2); +} + +/// While the document's symbols hold a placed document, whose art changes when its file is read, +/// each click in a blend's stroke band evaluates the blend again. +#[test] +fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() { + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let stroked = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0); + let circle = |id, x: f64| Arc::new(Node::path(id, shapes::ellipse(Rect::new(x, 295.0, x + 10.0, 305.0)), stroked.clone())); + let blend = d.alloc_id(); + let keys = vec![circle(d.alloc_id(), 10.0), circle(d.alloc_id(), 880.0)]; + let spec = crate::live::BlendSpec { spacing: crate::live::BlendSpacing::Steps(200), ..Default::default() }; + d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Box::new(spec) })).unwrap(); + let placed = crate::PlacedDocument { + link: crate::LinkInfo::new("/art/logo.vectorcraft"), + key: "logo".into(), + bounding: false, + page_box: crate::PageBox::Crop, + width: 80.0, + height: 40.0, + xf: vectorcraft_geom::Affine::IDENTITY, + placement: Default::default(), + }; + let art = Arc::new(Node::new(d.alloc_id(), NodeKind::PlacedDocument(Box::new(placed)))); + d.symbols.push(crate::Symbol { dynamic: false, name: "logo".into(), art }); + let evaluated = || LIVE_EVALUATED.with(std::cell::Cell::get); + let before = evaluated(); + for x in [448.0, 450.0] { + assert_eq!(hit_test(&d, Point::new(x, 291.0), HitOptions::default()).map(|h| h.leaf), Some(blend)); + } + assert_eq!(evaluated(), before + 2); +} + +/// A kept evaluation is the evaluation of the object only while the fonts and plug-ins +/// ([`LiveInputs`]) are as they were. +#[test] +fn a_kept_evaluation_is_stale_after_the_live_inputs_change() { + let d = Document::new(100.0, 100.0); + let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + let e = EvaluatedLive { node: n.clone(), symbols: vec![], patterns: vec![], inputs: 7, art: std::rc::Rc::new(vec![]), size: 0 }; + assert!(e.is_of(&d, &n, 7)); + assert!(!e.is_of(&d, &n, 8)); +} + /// A rectangle (40, 40)–(140, 140) clipping a filled 200 × 200 square drawn over its edges, in a /// clip group (or, `layer`, as the first layer's clipping mask): the group (or the layer), the /// clipping path and the art. diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index e5c98886a2..b5ae03e8b1 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -198,7 +198,8 @@ impl Node { /// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in /// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers /// without a clipping mask and Intertwine groups take in their members' boxes, grown by their - /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. + /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box + /// takes in where its spine can put its keys and steps. pub fn reach_bounds(&self) -> Option<Rect> { self.reach(None) } @@ -234,6 +235,11 @@ impl Node { let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o))) }), + // Keys and steps placed on a spine, turned to it with Align to Path, can reach past the + // keys and the spine. + NodeKind::Blend { children, spec } => { + vectorcraft_geom::union_opt(self.visual(symbols), crate::blend::rail_reach(children, spec, symbols)) + } _ => self.visual(symbols), } } diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index b7e7f51fe2..0285ae1561 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -20,6 +20,11 @@ impl Session { }); // Clicks find an image's own fills and strokes where their effects draw them. vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint); + // Clicks find a blend's steps and an envelope's distorted art where the canvas draws them, + // evaluated again when the fonts or the plug-ins change. + vectorcraft_doc::hit::set_live_art(vectorcraft_render::effects::expand_live, || { + vectorcraft_text::FontDb::global().generation().rotate_left(32) ^ vectorcraft_render::effects::plugin_revision() + }); // Exports bake Vector Halftone into the dots the renderer samples. vectorcraft_render::effects::addons::halftone::set_art(vectorcraft_render::addons::halftone::art); // OpenType SVG glyphs are drawn as the SVG importer reads their documents. diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index f2f2149358..acba01a74a 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -5,9 +5,10 @@ //! onto the clicked object (`reverse`); Shift+Alt-click: add the clicked object's appearance to the //! selection's (`append`). Shift-click: sample only the colour under the cursor into the active //! fill/stroke (`paint.sampleColor`; in a CMYK document an RGB color is stored as CMYK): a -//! gradient's color at that point, a pattern's tile art there (after the pattern's transform), or -//! a gradient mesh's interpolated patch color. Clicking an image samples its pixels (averaged over -//! the options' raster sample size; a CMYK image gives its ink amounts). +//! gradient's color at that point, a pattern's tile art there (after the pattern's transform), a +//! gradient mesh's interpolated patch color, or the art a blend or an envelope draws there (a +//! blend's steps, an envelope's distorted contents). Clicking an image samples its pixels +//! (averaged over the options' raster sample size; a CMYK image gives its ink amounts). //! //! The Gradient panel's eyedropper sets the `stop` option (the tool to return to): the next click //! samples the colour under the cursor into the selected gradient stop (`paint.sampleColor @@ -119,8 +120,8 @@ pub(crate) fn sample_source(cx: &ToolContext, p: Point) -> Option<(vectorcraft_d Some((paint_owner(cx.doc, h.leaf), h.kind)) } -/// The visible color under `p`, including image pixels, pattern tiles, mesh colors and -/// intermediate gradient colors. +/// The visible color under `p`, including image pixels, pattern tiles, mesh colors, intermediate +/// gradient colors, the steps a blend draws and an envelope's distorted contents. pub(crate) fn sample_color_at(cx: &ToolContext, p: Point) -> Option<Color> { let (doc, opts, raster_sample) = (cx.doc, sample_options(cx), cx.raster_sample); vectorcraft_doc::depth::with_deep_stack(|| { @@ -134,7 +135,9 @@ pub(crate) fn sample_color_at(cx: &ToolContext, p: Point) -> Option<Color> { /// The color the front-most object of `doc` hit at `p` with `opts` shows there. Where a stroke /// gives no color at `p` (a gap between its pattern's tiles), the object's own fill there does; -/// an object that gives none at all is passed over for the ones below it. `levels` holds the +/// an object that gives none at all is passed over for the ones below it. A hit on a blend or an +/// envelope, or on an object it holds, samples the art it draws ([`live_color_at`]), and where +/// that art leaves `p` empty the whole blend or envelope is passed over. `levels` holds the /// scratch documents for art inside art, one for each level deeper. fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option<Document>], p: Point, opts: HitOptions) -> Option<Color> { let mut passed: HashSet<NodeId> = HashSet::new(); @@ -150,6 +153,15 @@ fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option<Document>], }; s.spend(cost)?; let h = hit_test_visible_skipping(doc, p, opts, &|id| passed.contains(&id))?; + if let Some(live) = drawn_live(doc, &h.ancestry) { + if let Some(c) = live_color_at(s, levels, live, p) { + return Some(c); + } + if !passed.insert(live.id) { + return None; + } + continue; + } let id = paint_owner(doc, h.leaf); let n = doc.node(id)?; let on_stroke = h.kind == HitKind::Stroke; @@ -177,6 +189,23 @@ fn fill_covers(n: &Node, p: Point) -> bool { } } +/// The outermost blend or envelope (other than one whose contents are being edited) in `ancestry`, +/// a hit's path through `doc`: the canvas draws its evaluated art, not the objects it holds. +fn drawn_live<'d>(doc: &'d Document, ancestry: &[NodeId]) -> Option<&'d Node> { + ancestry.iter().filter_map(|id| doc.node(*id)).find(|n| matches!(n.kind, NodeKind::Blend { .. } | NodeKind::Envelope { editing: false, .. })) +} + +/// The color the art blend or envelope `n` draws shows at `p`, sampled as [`art_color_at`] samples +/// art: a blend's keys and steps, an envelope's distorted contents, symbol instances in them by +/// their symbols' art. Evaluating it counts the objects it holds, and the art made counts its +/// objects. +fn live_color_at(s: &mut Sampler, levels: &mut [Option<Document>], n: &Node, p: Point) -> Option<Color> { + s.spend(n.count())?; + let art = vectorcraft_effects::expand_live_deep(Some(s.doc), n); + s.spend(art.count())?; + art_color_at(s, levels, [art], p) +} + /// The color `n` shows at `p`: an image's pixels, a mesh's interpolated patch color, a symbol /// instance's art, or the color of its fill (or its stroke, when the stroke was hit or there is no /// fill) there. Images, symbols and patterns are looked up in the sampled document. @@ -1198,4 +1227,187 @@ mod tests { assert_eq!(paint_color_at(&paint, None, Point::new(0.0, -50.0)).unwrap().to_hex(), "#000000"); assert_eq!(paint_color_at(&paint, None, Point::new(50.0, 0.0)).unwrap().to_hex(), "#808080"); } + + /// An unstroked rectangle of `d` filled with `color`. + fn solid_rect(d: &mut vectorcraft_doc::Document, r: vectorcraft_geom::Rect, color: Color) -> Node { + let a = vectorcraft_doc::Appearance::basic(Paint::solid(color), Paint::None, 0.0); + Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), a) + } + + /// [`doc_with_rect`] plus a green rectangle (290, 290)–(430, 350) and, over it, `live` made by + /// `make` from the document. + fn doc_with_live_over_green(make: impl FnOnce(&mut vectorcraft_doc::Document) -> Node) -> vectorcraft_doc::Document { + use vectorcraft_geom::Rect; + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let green = solid_rect(&mut d, Rect::new(290.0, 290.0, 430.0, 350.0), Color::rgb(0.0, 1.0, 0.0)); + d.insert(Some(l), usize::MAX, green).unwrap(); + let live = make(&mut d); + d.insert(Some(l), usize::MAX, live).unwrap(); + d + } + + /// Shift-click on a blend samples the step drawn under the cursor, and a gap between its steps + /// samples what lies below. + #[test] + fn shift_click_samples_the_blend_step_under_the_cursor() { + use vectorcraft_doc::live::{BlendSpacing, BlendSpec}; + use vectorcraft_geom::Rect; + // Red (300, 300)–(320, 320) and blue (400, 300)–(420, 320) with 1 step, half red and half + // blue, at x 350 to 370. + let d = doc_with_live_over_green(|d| { + let red = solid_rect(d, Rect::new(300.0, 300.0, 320.0, 320.0), Color::rgb(1.0, 0.0, 0.0)); + let blue = solid_rect(d, Rect::new(400.0, 300.0, 420.0, 320.0), Color::rgb(0.0, 0.0, 1.0)); + let spec = BlendSpec { spacing: BlendSpacing::Steps(1), ..Default::default() }; + Node::new(d.alloc_id(), NodeKind::Blend { children: vec![std::sync::Arc::new(red), std::sync::Arc::new(blue)], spec: Box::new(spec) }) + }); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let at = |x: f64| EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, x, 310.0).with_mods(shift)); + let mid = Color::rgb(0.5, 0.0, 0.5).to_hex(); + assert_eq!(sampled_hex(&at(360.0)), mid); + assert_eq!(crate::xform::eyedropper::sample_color_at(&cx(&d, &s, &p), Point::new(360.0, 310.0)).map(|c| c.to_hex()), Some(mid)); + assert_eq!(sampled_hex(&at(310.0)), "#ff0000"); + // Between the red key and the step (x 320 to 350), and below the step. + assert_eq!(sampled_hex(&at(335.0)), "#00ff00"); + let below = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 360.0, 325.0).with_mods(shift)); + assert_eq!(sampled_hex(&below), "#00ff00"); + } + + /// A blend of two instances of one symbol draws its steps as instances too: Shift-click on a + /// step samples the symbol's art there, and where that art leaves the point empty, what lies + /// below. + #[test] + fn shift_click_samples_symbol_art_in_a_blends_steps() { + use vectorcraft_doc::live::{BlendSpacing, BlendSpec}; + use vectorcraft_geom::{Affine, Rect}; + // A red 20 pt square at the symbol's origin, placed at x 300 and 400, with 1 step at x 350. + let d = doc_with_live_over_green(|d| { + let art = solid_rect(d, Rect::new(0.0, 0.0, 20.0, 20.0), Color::rgb(1.0, 0.0, 0.0)); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Dot".into(), art: std::sync::Arc::new(art) }); + let mut instance = |x: f64| { + let kind = NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((x, 300.0)) }; + std::sync::Arc::new(Node::new(d.alloc_id(), kind)) + }; + let children = vec![instance(300.0), instance(400.0)]; + let spec = BlendSpec { spacing: BlendSpacing::Steps(1), ..Default::default() }; + Node::new(d.alloc_id(), NodeKind::Blend { children, spec: Box::new(spec) }) + }); + let (s, p) = (Selection::default(), paint()); + let sample = |x: f64, y: f64| crate::xform::eyedropper::sample_color_at(&cx(&d, &s, &p), Point::new(x, y)).map(|c| c.to_hex()); + assert_eq!(sample(360.0, 310.0), Some("#ff0000".into())); + assert_eq!(sample(335.0, 310.0), Some("#00ff00".into())); + assert_eq!(sample(360.0, 325.0), Some("#00ff00".into())); + } + + /// Align to Path turns a blend's keys and steps to its spine, past the keys' bounds: a click + /// there hits the blend and samples what it draws. + #[test] + fn shift_click_samples_blend_art_turned_past_its_bounds() { + use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec}; + use vectorcraft_geom::Rect; + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let green = solid_rect(&mut d, Rect::new(20.0, 20.0, 280.0, 280.0), Color::rgb(0.0, 1.0, 0.0)); + d.insert(Some(l), usize::MAX, green).unwrap(); + // 100 × 10 keys centred on (100, 100) and (200, 200): Align to Path turns them 45°, and the + // red one reaches (70, 66), above the keys' bounds (y 95 to 205). + let red = solid_rect(&mut d, Rect::new(50.0, 95.0, 150.0, 105.0), Color::rgb(1.0, 0.0, 0.0)); + let blue = solid_rect(&mut d, Rect::new(150.0, 195.0, 250.0, 205.0), Color::rgb(0.0, 0.0, 1.0)); + let spec = BlendSpec { spacing: BlendSpacing::Steps(1), orientation: BlendOrientation::AlignToPath, ..Default::default() }; + let id = d.alloc_id(); + let blend = Node::new(id, NodeKind::Blend { children: vec![std::sync::Arc::new(red), std::sync::Arc::new(blue)], spec: Box::new(spec) }); + d.insert(Some(l), usize::MAX, blend).unwrap(); + let (s, p) = (Selection::default(), paint()); + let at = Point::new(70.0, 66.0); + assert!(d.node(id).unwrap().geometric_bounds().is_some_and(|b| !b.contains(at))); + assert_eq!(hit_test(&d, at, cx(&d, &s, &p).hit_options()).map(|h| h.leaf), Some(id)); + assert_eq!(crate::xform::eyedropper::sample_color_at(&cx(&d, &s, &p), at).map(|c| c.to_hex()), Some("#ff0000".into())); + // Where the turned key leaves the point empty, the click passes the blend by. + assert_eq!(crate::xform::eyedropper::sample_color_at(&cx(&d, &s, &p), Point::new(60.0, 90.0)).map(|c| c.to_hex()), Some("#00ff00".into())); + // A hidden red key does not hit there. + if let Some(NodeKind::Blend { children, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + std::sync::Arc::make_mut(&mut children[0]).visible = false; + } + assert_eq!(hit_test(&d, at, cx(&d, &s, &p).hit_options()).map(|h| h.leaf), Some(d.layers[0].children().unwrap()[1].id)); + // A red key clipped to its right half, centred on (125, 100): the line to the blue key's + // centre turns it about 53°, and its hidden left half reaches (89, 52). + let mut clip = solid_rect(&mut d, Rect::new(100.0, 95.0, 150.0, 105.0), Color::BLACK); + clip.appearance = Default::default(); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let red = solid_rect(&mut d, Rect::new(50.0, 95.0, 150.0, 105.0), Color::rgb(1.0, 0.0, 0.0)); + let key = Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(clip), std::sync::Arc::new(red)], clip: true }); + if let Some(NodeKind::Blend { children, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + children[0] = std::sync::Arc::new(key); + } + let hidden = Point::new(89.0, 52.0); + assert!(d.node(id).unwrap().geometric_bounds().is_some_and(|b| !b.contains(hidden))); + assert_eq!(hit_test(&d, hidden, cx(&d, &s, &p).hit_options()).map(|h| h.leaf), Some(d.layers[0].children().unwrap()[1].id)); + assert_eq!(crate::xform::eyedropper::sample_color_at(&cx(&d, &s, &p), hidden).map(|c| c.to_hex()), Some("#00ff00".into())); + } + + /// The stroke of an envelope's distorted contents paints past the envelope's bounds: a click + /// there hits the envelope and samples the stroke. + #[test] + fn shift_click_samples_an_envelopes_stroke_past_its_bounds() { + use vectorcraft_geom::{Affine, Rect}; + let mut id = None; + let d = doc_with_live_over_green(|d| { + let a = vectorcraft_doc::Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 10.0); + let red = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(300.0, 300.0, 420.0, 320.0)), a); + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true }; + let content = vec![std::sync::Arc::new(red)]; + let n = Node::new( + d.alloc_id(), + NodeKind::Envelope { + content, + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options: Default::default(), + frame: Box::new(Affine::IDENTITY), + }, + ); + id = Some(n.id); + n + }); + let (s, p) = (Selection::default(), paint()); + // The middle of the band's top edge stays at y 300, and its 10 pt stroke reaches y 295. + let at = Point::new(360.0, 296.0); + assert!(d.node(id.unwrap()).unwrap().geometric_bounds().is_some_and(|b| !b.inflate(3.0, 3.0).contains(at))); + assert_eq!(hit_test(&d, at, cx(&d, &s, &p).hit_options()).map(|h| h.leaf), id); + assert_eq!(crate::xform::eyedropper::sample_color_at(&cx(&d, &s, &p), at).map(|c| c.to_hex()), Some("#0000ff".into())); + } + + /// Shift-click on an envelope samples its distorted contents where they are drawn, and a point + /// in its bounds that they leave empty samples what lies below. + #[test] + fn shift_click_samples_the_envelopes_distorted_contents() { + use vectorcraft_geom::{Affine, Rect}; + let d = doc_with_live_over_green(|d| { + let red = solid_rect(d, Rect::new(300.0, 300.0, 420.0, 320.0), Color::rgb(1.0, 0.0, 0.0)); + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true }; + let content = vec![std::sync::Arc::new(red)]; + let options = Default::default(); + Node::new( + d.alloc_id(), + NodeKind::Envelope { content, kind: Box::new(kind), fidelity: 50.0, editing: false, options, frame: Box::new(Affine::IDENTITY) }, + ) + }); + let (s, p) = (Selection::default(), paint()); + let sample = |x: f64, y: f64| crate::xform::eyedropper::sample_color_at(&cx(&d, &s, &p), Point::new(x, y)).map(|c| c.to_hex()); + let art = vectorcraft_effects::expand_live_deep(Some(&d), d.layers[0].children().unwrap().last().unwrap()); + let b = art.geometric_bounds().unwrap(); + // The arc bends the ends of the band down, below the 20 pt it was, and keeps its middle. + assert!(b.y1 > 330.0, "{b:?}"); + assert_eq!(sample(360.0, 310.0), Some("#ff0000".into())); + assert_eq!(sample(310.0, 332.0), Some("#ff0000".into())); + // Only what the art paints counts: just past the bent end's edge, within the click + // tolerance of it, the green below shows. + assert_eq!(sample(305.0, 332.0), Some("#00ff00".into())); + assert_eq!(sample(360.0, 332.0), Some("#00ff00".into())); + assert_eq!(sample(b.x0 + 0.5, b.y0 + 1.0), Some("#00ff00".into())); + } } From 18b9c6113e4c8c25479d32d6b755c597655c04ae Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 1 Nov 2026 09:24:23 +0700 Subject: [PATCH 243/260] .ai import: one object the reader can't read comes in as the page's art, and the layers stay Squashed from #5050 onto main. --- .../engine/src/cmd/fileio/tests_aiimport.rs | 22 + crates/eps/src/import/ai.rs | 2 +- crates/eps/src/import/ai/obj.rs | 2 + crates/eps/src/import/ai/read.rs | 20 +- crates/eps/src/import/ai/read/art.rs | 68 +- crates/eps/src/import/ai/read/containers.rs | 156 +++- crates/eps/src/import/ai/read/directives.rs | 76 +- crates/eps/src/import/ai/read/document.rs | 16 +- crates/eps/src/import/ai/read/ops.rs | 26 +- crates/eps/src/import/ai/read/types.rs | 8 + crates/eps/src/import/ai/tests.rs | 288 ++++++- crates/eps/src/import/native.rs | 4 +- crates/eps/src/import/native/build.rs | 754 +++++++++++++++++- crates/eps/src/import/native/slots.rs | 1 + crates/eps/src/import/tests_native.rs | 720 +++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + docs/file-format-parity.md | 2 +- docs/target-app-parity.md | 1 + 43 files changed, 2190 insertions(+), 53 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index edccacd50a..6f603b2006 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -82,6 +82,28 @@ fn an_illustrator_ai_file_opens_from_its_editing_data() { assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art", "Hidden"]); } +#[test] +fn an_ai_unread_group_keeps_its_layers_and_live_neighbor() { + let live = format!("0 0 1 0 k\n{}f", ai::rect(10.0, 10.0, 14.0, 14.0)); + let unread = format!("u\n0 0 1 0 k\n{}f\nZZ\nU\n{}", ai::rect(50.0, 10.0, 54.0, 14.0), ai::named("Unread")); + let data = ai::editing_data(200.0, 100.0, &(ai::layer("Live", &live) + &ai::layer("Mixed", &unread))); + let page = "0 0 1 0 k 10 10 4 4 re f 1 0 0 0 k 50 10 4 4 re f"; + let mut session = Session::new(); + let result = open(&mut session, "unread.ai", &ai::ai(&compressed(data.as_bytes()), page), json!({})).unwrap(); + let doc = &session.doc().unwrap().doc; + assert_eq!(names(&doc.layers), ["Live", "Mixed"], "{result}"); + assert!(matches!(doc.layers[0].children().unwrap()[0].kind, NodeKind::Path { .. }), "{result}"); + assert!(matches!(doc.layers[1].children().unwrap()[0].kind, NodeKind::Group { .. }), "{result}"); + assert_eq!(doc.layers[1].children().unwrap()[0].name.as_deref(), Some("Unread"), "{result}"); + let replacement = &doc.layers[1].children().unwrap()[0].children().unwrap()[0]; + assert!( + matches!(replacement.appearance.items.first(), Some(vectorcraft_doc::AppearanceItem::Fill(fill)) + if fill.paint == vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0))), + "{result}" + ); + assert!(result["warnings"].to_string().contains("`ZZ` (1)"), "{result}"); +} + /// A palette of three swatches and a color group `Inks` holding a fourth. const INKS_PALETTE: &str = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\n0.04 0.3 0 0 81.96 21 -8 (Pink ink) 0 2 Xx\n(Pink ink)\nPc\n\ 0.06 0.98 1 0 (Red ink) 0 x\n(Red ink)\nPc\n1 (Inks) 1 Pg\n0.02 0.1 1 0 (Yellow ink) 0 x\n(Yellow ink)\nPc\nPB\n%AI5_EndPalette\n"; diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 5e60e7e81f..50fcec2416 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -34,7 +34,7 @@ use crate::ps; pub(crate) use frames::text_frames; pub use read::{IMAGE_TOO_LARGE, PaletteSwatches, Structure, artboards, palette, read, variables}; -pub(crate) use read::{slot_frame, slot_of}; +pub(crate) use read::{join_and, slot_frame, slot_of}; #[cfg(test)] mod tests; diff --git a/crates/eps/src/import/ai/obj.rs b/crates/eps/src/import/ai/obj.rs index d91f153a88..10027f0107 100644 --- a/crates/eps/src/import/ai/obj.rs +++ b/crates/eps/src/import/ai/obj.rs @@ -68,6 +68,8 @@ pub(super) struct Obj { pub content: Vec<V>, /// Vector art enclosed by `X=` … `X+` in an opacity-mask dictionary. pub art: Option<std::sync::Arc<vectorcraft_doc::Node>>, + /// What that art has that isn't read, reported once the mask is known to be enabled. + pub unread: Vec<String>, } impl Obj { diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 5cf477d75c..8e7753dd77 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -73,6 +73,7 @@ mod document; mod ops; mod types; +pub(crate) use art::join_and; use art::preview_png; pub use document::{PaletteSwatches, VariableLibrary, artboards, palette, variables}; pub(crate) use document::{slot_frame, slot_of}; @@ -101,6 +102,10 @@ pub struct Structure { pub template: Option<[f64; 4]>, /// What layers that don't show have that isn't read (operators, objects): left out of them. pub hidden_unread: BTreeSet<String>, + /// Top-level object ids and the unread kinds within them. + pub unread: Vec<(NodeId, Vec<String>)>, + /// Other bounds for previewless placed files whose page art uses the file box's corner. + pub unread_elsewhere: Vec<(NodeId, Rect)>, /// The names of text objects, by their slot's id. pub slot_names: HashMap<NodeId, String>, /// Where the drawn looks lay that objects read with their art style took the place of (the @@ -162,6 +167,12 @@ struct Reader<'a> { unknown: BTreeSet<String>, /// What layers that don't show have that this reader doesn't read. hidden_unread: BTreeSet<String>, + unread: Vec<(NodeId, Vec<String>)>, + symbol_bounds: HashMap<String, Rect>, + /// Depth shared by pattern and symbol readers. + subreader_depth: usize, + pending_unread_fill: bool, + pending_unread_stroke: bool, /// The header's bounding boxes and template box. bbox: Option<[f64; 4]>, hires: Option<[f64; 4]>, @@ -209,6 +220,7 @@ struct Reader<'a> { restyled: Vec<Rect>, /// See [`Structure::placed_elsewhere`]. placed_elsewhere: Vec<(NodeId, Affine)>, + unread_elsewhere: Vec<(NodeId, Rect)>, /// CMYK samples converted, by value. cmyk_cache: HashMap<[u8; 4], [u8; 3]>, /// A `/ForeignObject`'s `/Data`: its PDF as ASCII85 in comment lines, until the object closes. @@ -277,6 +289,11 @@ impl<'a> Reader<'a> { unsupported: BTreeSet::new(), unknown: BTreeSet::new(), hidden_unread: BTreeSet::new(), + unread: Vec::new(), + symbol_bounds: HashMap::new(), + subreader_depth: 0, + pending_unread_fill: false, + pending_unread_stroke: false, bbox: None, hires: None, template: None, @@ -301,6 +318,7 @@ impl<'a> Reader<'a> { palette: super::palette::Palette::default(), restyled: vec![], placed_elsewhere: vec![], + unread_elsewhere: vec![], mesh: None, cmyk_cache: HashMap::new(), done: false, @@ -332,7 +350,7 @@ impl<'a> Reader<'a> { let w = std::str::from_utf8(w).unwrap_or("?"); self.op(w, hidden)?; } - Tok::Comment(c) => self.comment(c)?, + Tok::Comment(c) => self.comment(c, hidden)?, Tok::Data(d) => self.image(d)?, Tok::Preview(d) => { if let Some(p) = self.place.as_mut() { diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 89df83cd41..3f60ebe11e 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -12,7 +12,7 @@ impl<'a> Reader<'a> { /// A text object (`/AI11Text`): an empty group standing for it, named after its story. pub(super) fn text_slot(&mut self, o: &Obj) -> Result<(), String> { if self.pattern.is_some() { - self.unreadable("type in a pattern"); + self.unreadable("type in a pattern", false); } // `1 /FreeUndo`: the type in the drawn look of a text object that has an appearance. Its // story is one of another text document (`/AI11UndoFreeTextDocument`), which counts its @@ -171,6 +171,8 @@ impl<'a> Reader<'a> { "b" => (true, true), _ => (false, false), }; + // A gradient instance's paint replaces the missing pattern. + let unread = (fill && self.pending_unread_fill && fill_paint.is_none()) || (stroke && self.pending_unread_stroke && stroke_paint.is_none()); let mut items = Vec::new(); if fill && !clip { items.push(AppearanceItem::Fill(FillLayer { @@ -212,7 +214,28 @@ impl<'a> Reader<'a> { .into(); copy }); + let unread_bounds = unread.then(|| node.visual_bounds()).flatten(); + let unread_id = node.id; self.add(node, hidden)?; + if unread && self.pattern.is_some() { + // Art in a pattern's definition painted with a pattern it doesn't have: the tile can't be read. + self.unsupported.insert("pattern fills".into()); + } else if unread && ((hidden && !self.in_mask()) || gs.hidden || !self.shown()) { + self.hidden_unread.insert("pattern fills".into()); + } else if unread && self.in_mask() { + self.unreadable("pattern fills", false); + } else if unread { + match unread_bounds { + Some(b) if sane(b) && b.area() > 0.0 => { + if !self.mark_unread("pattern fills".into()) { + self.unread.push((unread_id, vec!["pattern fills".into()])); + } + } + _ => { + self.unsupported.insert("pattern fills".into()); + } + } + } if let Some(copy) = copy { self.clip_fills.insert(copy.id); self.add(copy, hidden)?; @@ -224,7 +247,7 @@ impl<'a> Reader<'a> { pub(super) fn end_mesh(&mut self) -> Result<(), String> { let Some((m, hidden)) = self.mesh.take() else { return Ok(()) }; if m.unread || m.patches.is_empty() { - self.unreadable("gradient meshes it can't read"); + self.unreadable("gradient meshes it can't read", hidden && self.pattern.is_none()); return Ok(()); } let gs = self.gs.clone(); @@ -461,10 +484,39 @@ impl<'a> Reader<'a> { /// shows the preview the data keeps of it, as a linked image whose file is missing does. One /// without a preview, a path or a matrix isn't read. pub(super) fn end_place(&mut self, hidden: bool) -> Result<(), String> { - let Some(Place { matrix: Some(m), bounds: Some(b), path, preview: Some((png, w, h)) }) = self.place.take().filter(|p| !p.path.is_empty()) - else { - self.unreadable("placed files"); - return Ok(()); + let (m, b, path, png, w, h) = match self.place.take() { + Some(Place { matrix: Some(m), bounds: Some(b), path, preview: Some((png, w, h)) }) if !path.is_empty() => (m, b, path, png, w, h), + other => { + let boxed = other.as_ref().and_then(|p| Some((p.matrix?, p.bounds?))).filter(|(_, b)| sane(*b) && b.area() > 0.0); + let mut have_bounds = false; + if self.shown() + && !self.gs.hidden + && !hidden + && let Some((m, b)) = boxed + { + let centre = self.template.map(|t| ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0)); + let origin = centre.map_or(b.origin(), |(x, y)| Point::new(CANVAS_CENTRE - x, CANVAS_CENTRE + y)); + let box_at_canvas = Rect::new(origin.x, origin.y, origin.x + b.width(), origin.y + b.height()); + let bounds = (self.space() * m).transform_rect_bbox(box_at_canvas); + have_bounds = sane(bounds) && bounds.area() > 0.0; + if have_bounds { + let placeholder_id = self.unread_box("placed files", bounds, hidden)?; + if let Some(placeholder_id) = placeholder_id.filter(|_| self.unread_elsewhere.len() < MAX_PLACED_ELSEWHERE) { + let corner = (self.space() * m).transform_rect_bbox(b); + if sane(corner) && corner.area() > 0.0 && corner != bounds { + self.unread_elsewhere.push((placeholder_id, corner)); + } + } + return Ok(()); + } + } + if self.shown() && !self.gs.hidden && !hidden && !have_bounds { + self.unsupported.insert("placed files".into()); + } else { + self.unreadable("placed files", hidden); + } + return Ok(()); + } }; // The file's pixels (y down) start at the canvas point of art space's origin (the box's own // corner when the file doesn't say where the canvas is); the preview's are spread over them. @@ -481,7 +533,7 @@ impl<'a> Reader<'a> { .filter(|a| a.as_coeffs().iter().all(|v| v.is_finite())); let xf = self.space() * m * over_file; if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { - self.unreadable("placed files"); + self.unreadable("placed files", hidden); return Ok(()); } // The preview is all the document has of the file: what a missing link shows. @@ -581,7 +633,7 @@ fn cmyk_rgb([c, m, y, k]: [u8; 4]) -> [u8; 3] { } /// `a`, `a and b`, `a, b and c`. -pub(super) fn join_and(items: &[&str]) -> String { +pub(crate) fn join_and(items: &[&str]) -> String { match items { [] => String::new(), [one] => (*one).to_string(), diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 992a9c5643..39f398a2e2 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -21,9 +21,12 @@ impl<'a> Reader<'a> { after: self.after_object, mesh_ended: self.mesh_ended, gs: self.gs.clone(), + pending_unread_fill: self.pending_unread_fill, + pending_unread_stroke: self.pending_unread_stroke, base, clips: Vec::new(), compound_members: false, + unread: Vec::new(), state: None, }); self.after_object = false; @@ -76,10 +79,27 @@ impl<'a> Reader<'a> { "*U" => self.close(what, |k| matches!(k, Kind::Compound))?, _ => self.close(what, |k| matches!(k, Kind::Clip))?, }; - let Frame { kind, children: kids, gs, clips, hidden: opened_hidden, compound_members, .. } = f; + let Frame { + kind, + children: kids, + gs, + clips, + hidden: opened_hidden, + compound_members, + unread, + pending_unread_fill, + pending_unread_stroke, + .. + } = f; + if matches!(kind, Kind::Clip) { + self.gs = gs.clone(); + self.pending_unread_fill = pending_unread_fill; + self.pending_unread_stroke = pending_unread_stroke; + } // A group holding only clipping paths (`q … u <path> W n U … Q`) doesn't clip on its own: `u`/`U` don't save // the graphics state as `q`/`Q` do, so its paths clip the clipping group around it, as the file's PDF part draws it. if matches!(kind, Kind::Group) + && unread.is_empty() && !clips.is_empty() && clips.len() == kids.len() && matches!(self.frames.last(), Some(Frame { kind: Kind::Clip, .. })) @@ -109,7 +129,14 @@ impl<'a> Reader<'a> { // painted copies make a compound of their own, under what it clips. let (fills, kids): (Vec<Node>, Vec<Node>) = ungrouped(kids).into_iter().partition(|n| self.clip_fills.contains(&n.id)); painted = self.compound(fills, &gs); - let Some(n) = self.compound(kids, &gs) else { return Ok(()) }; + let Some(n) = self.compound(kids, &gs) else { + if gs.hidden || !self.shown() { + self.hidden_unread.extend(unread); + } else { + self.unsupported.extend(unread); + } + return Ok(()); + }; n } // A group with a clipping path (`q` … `Q`, or a `W` path in a group) is a clipping group. @@ -124,6 +151,13 @@ impl<'a> Reader<'a> { if compound_members { self.compound_groups.insert(node.id); } + if !unread.is_empty() { + if !node.visible || !self.shown() { + self.hidden_unread.extend(unread); + } else { + self.unread.push((node.id, unread)); + } + } self.add(node, opened_hidden || hidden)?; if let Some(p) = painted { self.clip_fills.insert(p.id); @@ -173,6 +207,8 @@ impl<'a> Reader<'a> { } pub(super) fn end_layer(&mut self) -> Result<(), String> { + self.pending_unread_fill = false; + self.pending_unread_stroke = false; let mut f = self.close("LB", |k| matches!(k, Kind::Layer(_)))?; let state = self.layer_state.take(); // An `Xy` right after the layer's last mesh or blend, then `LB`: the layer's, not theirs. @@ -208,15 +244,16 @@ impl<'a> Reader<'a> { Ok(()) } - /// An operator the reader doesn't know: on hidden art it is only noted, on shown art the file - /// is read from its PDF part. - pub(super) fn note_unknown(&mut self, w: &str) { + /// An operator the reader doesn't know is scoped to its top-level object when possible. + pub(super) fn note_unknown(&mut self, w: &str, hidden: bool) { let op: String = w.chars().take(24).collect(); - if !self.shown() { + // A pattern definition or an owning mask can be on `%_` lines while still + // determining visible art. Unknown operators there must remain unread. + if (self.gs.hidden && self.pattern.is_none()) || (hidden && self.pattern.is_none() && !self.in_mask()) || !self.shown() { if self.hidden_unread.len() < 16 { self.hidden_unread.insert(format!("`{op}`")); } - } else if self.unknown.len() < 16 { + } else if !self.defer_to_mask(&format!("`{op}`")) && !self.mark_unread(format!("`{op}`")) && self.unknown.len() < 16 { self.unknown.insert(op); } } @@ -234,6 +271,8 @@ impl<'a> Reader<'a> { self.open(Kind::Obj(Box::new(Obj { ty, ..Obj::default() })), hidden)?; // A dictionary's state starts afresh (styles set theirs inside). self.gs = GState::default(); + self.pending_unread_fill = false; + self.pending_unread_stroke = false; Ok(()) } @@ -244,6 +283,8 @@ impl<'a> Reader<'a> { let (children, clip) = self.clip_first(f.children, &f.clips); let art = self.new_node(NodeKind::Group { children, clip }, &f.gs); self.gs = f.gs; + self.pending_unread_fill = f.pending_unread_fill; + self.pending_unread_stroke = f.pending_unread_stroke; self.after_object = f.after; self.mesh_ended = f.mesh_ended; let Some(Frame { kind: Kind::Obj(o), .. }) = self.frames.last_mut() else { @@ -252,6 +293,7 @@ impl<'a> Reader<'a> { if o.art.replace(Arc::new(art)).is_some() { return Err("a mask has more than one art block".into()); } + o.unread = f.unread; Ok(()) } @@ -261,13 +303,15 @@ impl<'a> Reader<'a> { return Ok(()); } let Some(f) = self.frames.pop() else { return Ok(()) }; - let Frame { kind, children, base, hidden, gs, after, mesh_ended, state, .. } = f; + let Frame { kind, children, base, hidden, gs, pending_unread_fill, pending_unread_stroke, after, mesh_ended, state, .. } = f; let Kind::Obj(mut o) = kind else { return Ok(()) }; obj::close(&mut o, &mut self.stack, base); self.obj_hidden = hidden; // Art made inside a dictionary (type's paths, a mask's art) isn't kept, and doesn't end what // follows the object the dictionary is about: a mesh's state comes after its mask. self.gs = gs; + self.pending_unread_fill = pending_unread_fill; + self.pending_unread_stroke = pending_unread_stroke; if let Some(state) = state { self.keep_state(state); } @@ -295,7 +339,7 @@ impl<'a> Reader<'a> { } "Document" => self.document(&o), "AI11Text" => self.text_slot(&o)?, - "SymbolInstance" => self.unreadable("symbols"), + "SymbolInstance" => self.symbol_instance(&o)?, "ForeignObject" => self.foreign_art(&o)?, _ => {} } @@ -330,14 +374,95 @@ impl<'a> Reader<'a> { /// Note something the data has that isn't read: an error on a layer that shows, left out of a /// layer that doesn't. - pub(super) fn unreadable(&mut self, what: &str) { - if self.shown() { - self.unsupported.insert(what.into()); + pub(super) fn unreadable(&mut self, what: &str, hidden: bool) { + if (!hidden || self.in_mask()) && !self.gs.hidden && self.shown() { + if !self.defer_to_mask(what) && !self.mark_unread(what.to_string()) { + self.unsupported.insert(what.into()); + } } else { self.hidden_unread.insert(what.into()); } } + /// Keep what an opacity mask's art doesn't read with the mask, until its dictionary says + /// whether the mask is enabled. Whether art of a mask is being read. Operators it doesn't know + /// are kept up to 16, as [`Reader::note_unknown`] keeps them. + fn defer_to_mask(&mut self, what: &str) -> bool { + let Some(f) = self.frames.iter_mut().rev().find(|f| matches!(f.kind, Kind::Mask)) else { return false }; + let full = what.starts_with('`') && f.unread.iter().filter(|w| w.starts_with('`')).count() >= 16; + if !full && !f.unread.iter().any(|w| w == what) { + f.unread.push(what.into()); + } + true + } + + /// Mark the first object container below the innermost layer. + pub(super) fn mark_unread(&mut self, what: String) -> bool { + let Some(layer) = self.frames.iter().rposition(|f| matches!(f.kind, Kind::Layer(_))) else { return false }; + let Some(frame) = self.frames.get_mut(layer + 1).filter(|f| matches!(f.kind, Kind::Group | Kind::Compound | Kind::Clip)) else { + return false; + }; + if !frame.unread.contains(&what) { + frame.unread.push(what); + } + true + } + + /// Stand in for one unread object with a box that the page can match. + pub(super) fn unread_box(&mut self, what: &str, bounds: super::Rect, hidden: bool) -> Result<Option<NodeId>, String> { + if (hidden && !self.in_mask()) || self.gs.hidden || !self.shown() { + self.hidden_unread.insert(what.into()); + return Ok(None); + } + // A mask's art isn't an object of the layers: its object, or the file, is what isn't read. + if self.in_mask() { + self.unreadable(what, false); + return Ok(None); + } + let in_container = self + .frames + .iter() + .rposition(|f| matches!(f.kind, Kind::Layer(_))) + .is_some_and(|layer| self.frames.get(layer + 1).is_some_and(|f| matches!(f.kind, Kind::Group | Kind::Compound | Kind::Clip))); + if !super::art::sane(bounds) || bounds.area() <= 0.0 { + self.unsupported.insert(what.into()); + return Ok(None); + } + let path = vectorcraft_geom::shapes::rectangle(bounds); + let gs = self.gs.clone(); + let node = self.new_node(NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false }, &gs); + let id = node.id; + if in_container { + self.mark_unread(what.into()); + } + self.add(node, hidden)?; + if !in_container { + self.unread.push((id, vec![what.into()])); + } + Ok(Some(id)) + } + + fn symbol_instance(&mut self, o: &Obj) -> Result<(), String> { + let bounds = o.get("SymbolRef").and_then(|v| v.iter().find_map(V::text)).and_then(|name| self.symbol_bounds.get(&name).copied()); + let matrix = o + .get("Matrix") + .or_else(|| o.get("Transform")) + .map(|v| v.iter().find_map(|item| if let V::Arr(a) = item { Some(Self::nums(a)) } else { None }).unwrap_or_else(|| Self::nums(v))); + let box_at_canvas = match (bounds, matrix.as_deref()) { + (Some(b), Some([a, c, d, e, x, y])) if [*a, *c, *d, *e, *x, *y].iter().all(|n| n.is_finite()) => { + Some(self.space().transform_rect_bbox(super::Affine::new([*a, *c, *d, *e, *x, *y]).transform_rect_bbox(b))) + } + _ => None, + }; + match box_at_canvas { + Some(b) => self.unread_box("symbols", b, self.obj_hidden).map(|_| ()), + None => { + self.unreadable("symbols", self.obj_hidden); + Ok(()) + } + } + } + /// Drop the object just read when it is an envelope's own: a group on `%_` lines, before the /// envelope's dictionary. It holds the mesh that shapes the envelope, or, while the envelope's /// contents are being edited, those contents (the mesh then is in the dictionary); either way the @@ -365,10 +490,15 @@ impl<'a> Reader<'a> { } /// Do the layers being read show? - fn shown(&self) -> bool { + pub(super) fn shown(&self) -> bool { self.frames.iter().all(|f| !matches!(&f.kind, Kind::Layer(a) if !a.visible)) } + /// Is the art being read an opacity mask's? It is on `%_` lines and still shapes what shows. + pub(super) fn in_mask(&self) -> bool { + self.frames.iter().any(|f| matches!(f.kind, Kind::Mask)) + } + /// A blend's record read: the blend's own art (the group of its key objects and spine, on `%_` /// lines) and its drawn steps (the group after it) become one live blend, or, where they can't, /// the drawn steps stay, without the blend's own art drawn over them (see [`super::blend`]). diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index d2a4b6cc5f..1d5806a3cc 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -1,5 +1,5 @@ use super::art::{four, sane, two}; -use super::types::{FLIP, Kind, MAX_HEX, MAX_PATTERNS, MAX_STACK, PatternHead, Place, Raster, SKIPPED, VERSIONED_UNENDED}; +use super::types::{FLIP, Kind, MAX_HEX, MAX_PATTERNS, MAX_STACK, MAX_SUBREADERS, PatternHead, Place, Raster, SKIPPED, VERSIONED_UNENDED}; use super::{Arc, Node, PatternDef, Reader, Rect, Tok, V, marker}; impl<'a> Reader<'a> { @@ -23,7 +23,7 @@ impl<'a> Reader<'a> { // ---- comments -------------------------------------------------------------------------- - pub(super) fn comment(&mut self, c: &[u8]) -> Result<(), String> { + pub(super) fn comment(&mut self, c: &[u8], hidden: bool) -> Result<(), String> { let line = String::from_utf8_lossy(c); let line = line.trim_end(); if let Some((len, hex)) = self.blend_record.as_mut() { @@ -56,6 +56,11 @@ impl<'a> Reader<'a> { self.define_pattern(section); return Ok(()); } + if m == "BeginSymbol" { + let section = self.section("EndSymbol")?; + self.symbol_bounds(section); + return Ok(()); + } if m == "BeginArtStyles" { let section = self.section("EndArtStyles")?; self.styles = crate::import::ai::style::art_styles(section); @@ -107,8 +112,8 @@ impl<'a> Reader<'a> { self.place = Some(Place::default()); } else if line.starts_with("AI5_EndPlace") { // One that `~` didn't end isn't read. - if self.place.take().is_some() { - self.unreadable("placed files"); + if self.place.is_some() { + self.end_place(hidden)?; } } else if self.frames.is_empty() && let Some(v) = line.strip_prefix("%HiResBoundingBox:") @@ -185,13 +190,15 @@ impl<'a> Reader<'a> { /// A pattern's definition (`section`: what follows `%AI3_BeginPattern`), read by a reader of its /// own into a pattern swatch, its art in the pattern's space (y down). A definition it can't - /// read whole (an operator it doesn't know, type, unbalanced groups, no tile) isn't kept: art + /// read whole (an operator it doesn't know, type, a pattern it doesn't have, unbalanced groups, + /// no tile) isn't kept: art /// filled with it can't be read. fn define_pattern(&mut self, section: &[u8]) { - if self.pattern_tiles.len() >= MAX_PATTERNS { + if self.pattern_tiles.len() >= MAX_PATTERNS || self.subreader_depth >= MAX_SUBREADERS { return; } let mut sub = Reader::new(section); + sub.subreader_depth = self.subreader_depth + 1; sub.pattern = Some(PatternHead::default()); // The gradients defined so far, lent (and those it defines kept). sub.gradients = std::mem::take(&mut self.gradients); @@ -200,7 +207,13 @@ impl<'a> Reader<'a> { let read = sub.open(Kind::Group, false).and_then(|()| sub.run()); self.nodes = sub.nodes; self.gradients = std::mem::take(&mut sub.gradients); - let whole = read.is_ok() && sub.unsupported.is_empty() && sub.unknown.is_empty() && sub.frames.len() == 1; + // Unread art in the definition, hidden or not, leaves the tile incomplete. + let whole = read.is_ok() + && sub.unsupported.is_empty() + && sub.unknown.is_empty() + && sub.unread.is_empty() + && sub.hidden_unread.is_empty() + && sub.frames.len() == 1; let (Some(head), Some(frame)) = (sub.pattern.take(), sub.frames.pop()) else { return }; let Some(tile) = head.tile.filter(|t| whole && sane(*t) && t.width() > 0.0 && t.height() > 0.0 && !frame.children.is_empty()) else { return; @@ -224,6 +237,34 @@ impl<'a> Reader<'a> { } } + /// Read a definition's box for an instance whose art must come from the page. + fn symbol_bounds(&mut self, section: &[u8]) { + if self.symbol_bounds.len() >= MAX_PATTERNS || self.subreader_depth >= MAX_SUBREADERS { + return; + } + let mut lex = super::Lexer::new(section); + let name = match lex.next_token().map(|t| t.tok) { + Some(Tok::Str(bytes)) => super::obj::text(&bytes), + _ => return, + }; + let mut sub = Reader::new(section); + sub.subreader_depth = self.subreader_depth + 1; + sub.cropmarks = self.cropmarks; + sub.template = self.template; + sub.nodes = self.nodes; + let read = sub.open(Kind::Group, false).and_then(|()| sub.run()); + self.nodes = sub.nodes; + if read.is_err() || !sub.unsupported.is_empty() || !sub.unknown.is_empty() || sub.frames.len() != 1 { + return; + } + let Some(frame) = sub.frames.pop() else { return }; + let bounds = frame.children.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, n.visual_bounds())); + let Some(bounds) = bounds.map(|b| sub.space().inverse().transform_rect_bbox(b)) else { return }; + if sane(bounds) && bounds.area() > 0.0 { + self.symbol_bounds.insert(name, bounds); + } + } + /// In a pattern's definition, the operands of its first operator start with its head, /// `(name) llx lly urx ury`: taken off them. pub(super) fn take_head(&mut self, mut vals: Vec<V>) -> Vec<V> { @@ -237,3 +278,24 @@ impl<'a> Reader<'a> { vals.split_off(at + 5) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn deeply_nested_symbol_definitions_stop_at_subreader_limit() { + let mut definition = String::from("(Outer) 0 Ae\n"); + for i in 0..300 { + definition.push_str(&format!("%AI14_BeginSymbol\n(S{i}) 0 Ae\n")); + } + definition.push_str("0 0 m\n4 0 L\n4 4 L\n0 4 L\nf\n"); + for _ in 0..300 { + definition.push_str("%AI10_EndSymbol\n0 0 m\n4 0 L\n4 4 L\n0 4 L\nf\n"); + } + let mut reader = Reader::new(b""); + reader.subreader_depth = MAX_SUBREADERS; + reader.symbol_bounds(definition.as_bytes()); + assert!(reader.symbol_bounds.is_empty()); + } +} diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index fb540f1d1f..eeaf108543 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -243,10 +243,20 @@ impl<'a> Reader<'a> { if let Some(n) = self.last_object().filter(|n| !matches!(n.kind, NodeKind::Layer { .. })) { n.extras_mut().mask = Some(Box::new(value)); } else if !on("Disabled") { - self.unreadable("opacity masks without an owning object"); + self.unreadable("opacity masks without an owning object", false); + } + // What the art doesn't read matters only when the mask shapes what shows. + for what in &mask.unread { + if on("Disabled") { + self.hidden_unread.insert(what.clone()); + } else if let Some(op) = what.strip_prefix('`').and_then(|w| w.strip_suffix('`')) { + self.note_unknown(op, false); + } else { + self.unreadable(what, false); + } } } else if mask.nums("Disabled").first().copied() != Some(1.0) { - self.unreadable("opacity masks without readable art"); + self.unreadable("opacity masks without readable art", false); } } let name = match o.text("AIArtName") { @@ -453,6 +463,8 @@ impl<'a> Reader<'a> { artboard, template: self.template, hidden_unread: self.hidden_unread, + unread: self.unread, + unread_elsewhere: self.unread_elsewhere, slot_names: self.slot_names, restyled: self.restyled, placed_elsewhere: self.placed_elsewhere, diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 9deba88891..8eff92907b 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -80,7 +80,7 @@ impl<'a> Reader<'a> { // Only `Bh` reads an undefined number. Anywhere else it would reach a point or a size, so // the operator is one the reader doesn't know, as before. if w != "Bh" && !self.frames.is_empty() && vals.iter().any(|v| matches!(v, V::Num(n) if n.is_nan())) { - self.note_unknown("--"); + self.note_unknown("--", hidden); return Ok(()); } if let Some(d) = self.gradient_def.as_mut() { @@ -303,7 +303,7 @@ impl<'a> Reader<'a> { _ if IGNORED.contains(&w) => {} // Before the art, the setup runs procedures of the printing format. _ if self.frames.is_empty() => {} - _ => self.note_unknown(w), + _ => self.note_unknown(w, hidden), } Ok(()) } @@ -340,22 +340,38 @@ impl<'a> Reader<'a> { } let name = vals.iter().find_map(|v| if let V::Str(_) = v { v.text() } else { None }); let Some(tile) = name.as_deref().and_then(|n| self.pattern_tiles.get(n)).copied() else { - self.unreadable("pattern fills"); + self.unread_pattern(w); return; }; let matrix = vals.iter().rev().find_map(|v| if let V::Arr(a) = v { paint::affine(&Self::nums(a)) } else { None }); let Some(xf) = pattern_xf(self.space(), matrix, tile) else { - self.unreadable("pattern fills"); + self.unread_pattern(w); return; }; let p = Paint::Pattern { pattern: name.unwrap_or_default(), xf }; if w == "p" { + self.pending_unread_fill = false; self.gs.fill = p; } else { + self.pending_unread_stroke = false; self.gs.stroke = p; } } + fn unread_pattern(&mut self, w: &str) { + if self.shown() { + if w == "p" { + self.pending_unread_fill = true; + } else { + self.pending_unread_stroke = true; + } + } + // In a pattern's definition, only art painted with it makes the tile unreadable (see `paint`). + if self.pattern.is_none() && (!self.shown() || self.gs.hidden) { + self.hidden_unread.insert("pattern fills".into()); + } + } + fn color(&mut self, w: &str, vals: &[V]) { let Some((p, named)) = paint::color_op(w, vals) else { return }; // Registration (`Xs`, `Xz`) says nothing of the document's colour model. @@ -373,9 +389,11 @@ impl<'a> Reader<'a> { if w.ends_with(|c: char| c.is_ascii_lowercase()) { self.gs.fill = p; self.pending_fill = None; + self.pending_unread_fill = false; } else { self.gs.stroke = p; self.pending_stroke = None; + self.pending_unread_stroke = false; } } diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index 6d948ae81f..a2792e84c1 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -3,6 +3,9 @@ use super::{Affine, BlendMode, Dash, FillRule, Knockout, LayerColor, LineCap, Li /// Deepest nesting of layers, groups and dictionaries. pub(super) const MAX_DEPTH: usize = 256; +/// Most nested pattern and symbol readers on one call stack. +pub(super) const MAX_SUBREADERS: usize = 32; + /// Most operands on the stack. pub(super) const MAX_STACK: usize = 1 << 20; @@ -147,12 +150,17 @@ pub(super) struct Frame { /// The state when it opened (a container's lock and visibility; a dictionary's state to go /// back to). pub(super) gs: GState, + /// Unresolved pattern paint saved by `q`, which restores graphics state at `Q`. + pub(super) pending_unread_fill: bool, + pub(super) pending_unread_stroke: bool, /// The operand stack's height when it opened. pub(super) base: usize, /// The clipping paths' indexes among the children. pub(super) clips: Vec<usize>, /// A compound member group explicitly declares its subpaths' winding with `D`. pub(super) compound_members: bool, + /// Unread kinds belonging to this top-level object. + pub(super) unread: Vec<String>, /// A dictionary in the art: the transparency (`Xy`) its art set last, which stays after it. pub(super) state: Option<(f32, BlendMode, bool, Knockout, bool)>, } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 34b35e13e4..21227eef65 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -33,6 +33,13 @@ fn read_ok(body: &str) -> Structure { } } +fn assert_unread(r: &Structure, kind: &str) { + assert_eq!(r.unread.len(), 1); + let (id, kinds) = &r.unread[0]; + assert_eq!(kinds, &[kind]); + assert!(r.doc.node(*id).is_some(), "the unread object has a placeholder"); +} + #[test] fn ruler_units_from_the_header_set_the_documents_units() { let body = layer(""); @@ -286,18 +293,41 @@ fn a_pattern_it_cant_read_is_an_error_only_where_it_fills() { let s = read_ok(&format!("{unread}{}", layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n")))); assert!(s.doc.patterns.is_empty() && s.doc.swatches.iter().all(|w| !matches!(w.paint, Paint::Pattern { .. }))); for name in ["Old", "Odd", "Flat"] { - let e = read( + let r = read( stream(&format!("{unread}{}", layer(&format!("({name}) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(0.0, 0.0, 1.0, 1.0))))) .as_bytes(), ) - .unwrap_err(); - assert!(e.contains("pattern fills"), "{name}: {e}"); + .unwrap(); + assert_unread(&r, "pattern fills"); } // Type in a pattern isn't read either. let typed = "%AI3_BeginPattern: (Words)\n(Words) 0 0 8 8\n%_/AI11Text :\n%_0 /StoryIndex ,\n%_;\nE\n%AI3_EndPattern\n"; assert!(read_ok(&format!("{typed}{}", layer(""))).doc.patterns.is_empty()); } +/// A pattern whose definition paints with a pattern it doesn't have isn't kept, on `%_` lines or +/// not: a fill with it is something the file has that isn't read. +#[test] +fn a_pattern_painting_with_an_unread_pattern_is_not_kept() { + for prefix in ["%_", ""] { + let tile = rect_path(0.0, 0.0, 8.0, 8.0).replace('\n', &format!("\n{prefix}")); + let def = format!( + "%AI3_BeginPattern: (Nest)\n(Nest) 0 0 8 8\n{prefix}(Missing) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{prefix}{tile}f\nE\n%AI3_EndPattern\n" + ); + let s = read_ok(&format!("{def}{}", layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n")))); + assert!(s.doc.patterns.is_empty(), "{prefix:?}: {:?}", s.doc.patterns.iter().map(|p| &p.name).collect::<Vec<_>>()); + let r = read( + stream(&format!("{def}{}", layer(&format!("(Nest) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(0.0, 0.0, 1.0, 1.0))))).as_bytes(), + ) + .unwrap(); + assert_unread(&r, "pattern fills"); + // A color set before the tile is drawn replaces the missing pattern, and the pattern is kept. + let repainted = def.replace(&format!("{prefix}{tile}f"), &format!("{prefix}0 g\n{prefix}{tile}f")); + let s = read_ok(&format!("{repainted}{}", layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n")))); + assert!(s.doc.pattern("Nest").is_some(), "{prefix:?}"); + } +} + #[test] fn compound_paths_and_clipping() { let art_ = format!( @@ -982,6 +1012,42 @@ fn a_placed_file_on_commented_lines_is_read() { assert_eq!((img.get_pixel(0, 0).0, img.get_pixel(1, 0).0), ([255, 0, 0, 255], [0, 127, 0, 128]), "its preview"); } +#[test] +fn hidden_placed_file_ended_by_comment_stays_hidden() { + let mut data = hide_placed(&placed(true, "[5 0 0 -5 0 200]", "/pics/photo.png", None, "")); + let end = data.windows(4).position(|w| w == b"%_~\r").unwrap(); + data.drain(end..end + 4); + let r = read(&data).unwrap(); + assert!(art(&r.doc).is_empty()); + assert!(r.unread.is_empty(), "hidden placement has no shown placeholder"); + assert!(r.hidden_unread.contains("placed files")); +} + +#[test] +fn previewless_placement_records_box_corner_as_alternative() { + let mut data = placed(true, "[1 0 0 -1 -7970 8070]", "missing.png", None, ""); + let at = data.windows(15).position(|w| w == b"%AI5_BeginLayer").unwrap(); + data.splice(at..at, *b"%AI3_TemplateBox: 100 50 100 50\n"); + let r = read(&data).unwrap(); + assert_unread(&r, "placed files"); + assert_eq!(r.unread_elsewhere.len(), 1); + assert_eq!(r.unread_elsewhere[0].0, r.unread[0].0); + assert_ne!(r.unread_elsewhere[0].1, r.doc.node(r.unread[0].0).unwrap().visual_bounds().unwrap()); +} + +/// A previewless locked placement keeps its edit lock on the page-art placeholder. +#[test] +fn previewless_placement_placeholder_inherits_lock() { + let mut data = placed(true, "[5 0 0 -5 0 200]", "missing.png", None, ""); + let at = data.windows(15).position(|w| w == b"%AI5_BeginPlace").unwrap(); + data.splice(at..at, *b"1 A\n"); + let result = read(&data).unwrap(); + assert_unread(&result, "placed files"); + let node = result.doc.node(result.unread[0].0).unwrap(); + assert!(node.locked); + assert!(node.visible); +} + #[test] fn placed_files_are_linked_images_showing_their_preview() { // A 2×1 preview (premultiplied ARGB, a padded row) of a file of 4×2 pixels. @@ -1011,8 +1077,7 @@ fn placed_files_are_linked_images_showing_their_preview() { let xf = pixels(&r.doc).1; assert_eq!((xf * Point::ZERO, xf * Point::new(2.0, 1.0)), (Point::new(100.0, 50.0), Point::new(110.0, 30.0))); - // Without a preview it can read (none, cut short, not 32 bits, absurd sizes), without a path or - // a matrix, the file isn't read from its editing data. + // A placed file with a box but no usable preview is marked for page-art replacement. let cut = &preview[..preview.len() - 6]; let huge = b"70000 70000 280000 32 17 \0\0\0\0"; let overflow = b"1 2 18446744073709551615 32 17 \0\0\0\0\0\0\0\0"; @@ -1027,8 +1092,13 @@ fn placed_files_are_linked_images_showing_their_preview() { ("[0 0 0 0 0 0]", "a.png", Some(&preview[..])), ("[1 2 3]", "a.png", Some(&preview[..])), ] { - let e = read(&placed(true, matrix, path, preview, "")).unwrap_err(); - assert!(e.contains("placed files"), "{matrix} {path} {preview:?}: {e}"); + let result = read(&placed(true, matrix, path, preview, "")); + if matrix == "[0 0 0 0 0 0]" || matrix == "[1 2 3]" { + let e = result.err().unwrap_or_else(|| panic!("expected missing bounds for {matrix} {path}")); + assert!(e.contains("placed files"), "{matrix} {path} {preview:?}: {e}"); + } else { + assert_unread(&result.unwrap(), "placed files"); + } } // On a layer that doesn't show, such a file is left out of it. let r = read(&placed(false, "[5 0 0 -5 0 200]", "a.png", None, "")).unwrap(); @@ -1070,8 +1140,8 @@ fn text_objects_are_slots_named_after_their_story() { fn what_it_doesnt_read_is_an_error_where_it_shows() { let e = read(stream(&layer("1 2 frobnicate\n")).as_bytes()).unwrap_err(); assert!(e.contains("`frobnicate`"), "{e}"); - let e = read(stream(&layer("(Jive) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n")).as_bytes()).unwrap_err(); - assert!(e.contains("pattern fills"), "{e}"); + let r = read(stream(&layer(&format!("(Jive) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(0.0, 0.0, 1.0, 1.0)))).as_bytes()).unwrap(); + assert_unread(&r, "pattern fills"); let e = read(stream(&layer("/SymbolInstance :\n(Dot) /SymbolRef ,\n;\n")).as_bytes()).unwrap_err(); assert!(e.contains("symbols"), "{e}"); // A mask with no owner must still be reported (#2004). @@ -1093,6 +1163,206 @@ fn what_it_doesnt_read_is_an_error_where_it_shows() { read_ok(&format!("Adobe_level2_AI5 /initialize get exec\n{}", layer(""))); } +#[test] +fn unresolved_pattern_reset_before_group_path_keeps_live_art() { + for (operator, draw, reset) in [("p", "f", "0 0 0 1 k"), ("P", "S", "0 0 0 1 K")] { + let body = format!("u\n(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] {operator}\n{reset}\n{}{draw}\nU\n", rect_path(0.0, 0.0, 4.0, 4.0),); + let result = read_ok(&layer(&body)); + assert!(result.unread.is_empty(), "{operator}: {:?}", result.unread); + let children = art(&result.doc); + assert_eq!(children.len(), 1, "{operator}: group count"); + let group_art = children[0].children().expect("group children"); + assert_eq!(group_art.len(), 1, "{operator}: live path count"); + assert!(matches!(group_art[0].kind, NodeKind::Path { .. })); + } +} + +#[test] +fn unresolved_pattern_in_dictionary_does_not_mark_following_path_unread() { + for (operator, draw) in [("p", "f"), ("P", "S")] { + let body = format!("/Unused :\n(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] {operator}\n;\n{}{draw}\n", rect_path(0.0, 0.0, 4.0, 4.0),); + let result = read_ok(&layer(&body)); + assert!(result.unread.is_empty(), "{operator}: {:?}", result.unread); + let children = art(&result.doc); + assert_eq!(children.len(), 1, "{operator}: live path count"); + assert!(matches!(children[0].kind, NodeKind::Path { .. })); + } +} + +#[test] +fn color_in_dictionary_does_not_clear_outer_unresolved_pattern() { + for (operator, draw, color) in [("p", "f", "0 0 0 1 k"), ("P", "S", "0 0 0 1 K")] { + let body = format!("(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] {operator}\n/Unused :\n{color}\n;\n{}{draw}\n", rect_path(0.0, 0.0, 4.0, 4.0),); + let result = read_ok(&layer(&body)); + assert_unread(&result, "pattern fills"); + assert_eq!(art(&result.doc).len(), 1, "{operator}: unread path placeholder"); + } +} + +#[test] +fn gradient_instance_after_unresolved_pattern_is_read() { + let defs = + "%AI5_BeginGradient: (G)\n(G) 0 2 Bd\n[\n<00FF>\n0\n%_0 0 0 0 1 0 0 2 1 6 50 0 Bs\n%_0 0 0 0 0 0 1 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + for (operator, flag, draw) in [("p", "", "f"), ("P", "1 ", "S")] { + let body = format!( + "(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] {operator}\n{}{draw}\n{}{flag}Bb\n1 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\n10 0 0 10 100 50 Xm\n{draw}\n0 BB\n", + rect_path(0.0, 0.0, 4.0, 4.0), + rect_path(10.0, 0.0, 14.0, 4.0), + ); + let result = read(stream(&format!("{defs}{}", layer(&body))).as_bytes()).unwrap(); + assert_unread(&result, "pattern fills"); + let a = art(&result.doc); + assert_eq!(a.len(), 2, "{operator}"); + assert_eq!(result.unread[0].0, a[0].id, "{operator}: only the pattern's path is unread"); + } +} + +#[test] +fn unresolved_pattern_in_mask_art_stays_unread() { + let mask_path = rect_path(0.0, 0.0, 4.0, 4.0).lines().map(|line| format!("%_{line}\n")).collect::<String>(); + let patterned = format!("%_(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{mask_path}%_f\n"); + // A placed file with no preview, and a symbol whose definition the file doesn't have. + let placed = "%_%AI5_BeginPlace\n%_%%FileType: 1\n%_[5 0 0 -5 0 200] 10 20 14 22 4 4 0\n%_(missing.png)`\n%_%%IncludeFile:missing.png\n%_~\n%_%AI5_EndPlace\n"; + let symbol = "%_/SymbolInstance :\n%_(Absent) /SymbolRef ,\n%_;\n"; + for (art_, kind) in [ + (patterned.as_str(), "pattern fills"), + ("%_/Mesh X!\n%_/End X!\n", "gradient meshes it can't read"), + (placed, "placed files"), + (symbol, "symbols"), + ("%_1 2 frobnicate\n", "`frobnicate`"), + ] { + let mask = format!( + "%_/ArtDictionary :\n%_/Mask :\n%_X=\n{art_}%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_1 /Bool (Linked) ,\n%_; (AI9_Mask) ,\n%_;\n" + ); + let masked = format!("{RED}{}f\n{mask}", rect_path(0.0, 0.0, 4.0, 4.0)); + let e = read(stream(&layer(&masked)).as_bytes()).unwrap_err(); + assert!(e.contains(kind), "{e}"); + // In a group, the group is the unread object. + let result = read_ok(&layer(&format!("u\n{masked}U\n"))); + assert_unread(&result, kind); + assert!(result.hidden_unread.is_empty(), "{kind}: {:?}", result.hidden_unread); + // A disabled mask doesn't change how its object looks: what it holds is left out. + let disabled = masked.replace("%_1 /Bool (Linked) ,\n", "%_1 /Bool (Linked) ,\n%_1 /Bool (Disabled) ,\n"); + for body in [disabled.clone(), format!("u\n{disabled}U\n")] { + let result = read_ok(&layer(&body)); + assert!(result.unread.is_empty(), "{kind}: {:?}", result.unread); + assert!(result.hidden_unread.contains(kind), "{kind}: {:?}", result.hidden_unread); + } + } + // Operators a mask's art doesn't know are kept up to 16. + let ops = (0..40).map(|i| format!("%_op{i}\n")).collect::<String>(); + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{ops}%_X+\n%_(Art) ,\n%_1 /Bool (Linked) ,\n%_; (AI9_Mask) ,\n%_;\n"); + let result = read_ok(&layer(&format!("u\n{RED}{}f\n{mask}U\n", rect_path(0.0, 0.0, 4.0, 4.0)))); + assert_eq!(result.unread.len(), 1); + assert_eq!(result.unread[0].1.len(), 16); +} + +#[test] +fn hidden_unread_art_beside_drawn_look_needs_no_page_replacement() { + let hidden_path = rect_path(0.0, 0.0, 4.0, 4.0).lines().map(|line| format!("%_{line}\n")).collect::<String>(); + for (operator, draw, reset) in [("p", "f", "0 0 0 1 k"), ("P", "S", "0 0 0 1 K")] { + let body = format!( + "u\n%_(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] {operator}\n{hidden_path}%_{draw}\n{reset}\n{}{draw}\nU\n", + rect_path(10.0, 0.0, 14.0, 4.0), + ); + let result = read_ok(&layer(&body)); + assert!(result.unread.is_empty(), "{operator}: {:?}", result.unread); + assert!(result.hidden_unread.contains("pattern fills")); + let children = art(&result.doc); + let group_art = children[0].children().expect("group children"); + assert_eq!(group_art.len(), 2); + assert!(matches!(group_art[1].kind, NodeKind::Path { .. })); + } +} + +#[test] +fn unknown_operator_on_hidden_line_does_not_mark_drawn_group_unread() { + let body = format!("u\n%_1 2 frobnicate\n{RED}{}f\nU\n", rect_path(10.0, 0.0, 14.0, 4.0)); + let result = read_ok(&layer(&body)); + assert!(result.unread.is_empty(), "{:?}", result.unread); + assert!(result.hidden_unread.contains("`frobnicate`")); + assert_eq!(art(&result.doc)[0].children().expect("group children").len(), 1); +} + +/// A commented closing delimiter does not hide a visible group's unread content. +#[test] +fn visible_group_closed_on_hidden_line_stays_unread() { + let body = format!("u\n1 2 frobnicate\n{RED}{}f\n%_U\n", rect_path(10.0, 0.0, 14.0, 4.0)); + let result = read_ok(&layer(&body)); + assert_eq!(result.unread.len(), 1); + assert!(result.unread[0].1.contains(&"`frobnicate`".to_string())); + assert!(!result.hidden_unread.contains("`frobnicate`")); +} + +/// `Xw` hides unread objects even when their operators are on ordinary lines. +#[test] +fn xw_hidden_unread_keeps_visible_group_sibling() { + for unread in + ["1 2 frobnicate\n", "(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n0 0 m\n4 0 L\n4 4 L\nf\n", "/SymbolInstance :\n(Absent) /SymbolRef ,\n;\n"] + { + let body = format!("u\n1 Xw\n{unread}0 Xw\n0 0 0 1 k\n{}f\nU\n", rect_path(10.0, 0.0, 14.0, 4.0)); + let result = read_ok(&layer(&body)); + assert!(result.unread.is_empty(), "{unread}: {:?}", result.unread); + assert!(!result.hidden_unread.is_empty(), "{unread}"); + let children = art(&result.doc); + let group_art = children[0].children().expect("group children"); + assert_eq!(group_art.iter().filter(|node| node.visible).count(), 1, "{unread}"); + } + let mut data = placed(true, "[5 0 0 -5 0 200]", "missing.png", None, "0 Xw\n"); + let at = data.windows(15).position(|w| w == b"%AI5_BeginPlace").unwrap(); + data.splice(at..at, *b"1 Xw\n"); + let result = read(&data).unwrap(); + assert!(result.unread.is_empty()); + assert!(result.hidden_unread.contains("placed files")); +} + +#[test] +fn hidden_unread_symbol_does_not_mark_drawn_group_unread() { + let body = format!("u\n%_/SymbolInstance :\n%_(Absent) /SymbolRef ,\n%_;\n{RED}{}f\nU\n", rect_path(10.0, 0.0, 14.0, 4.0)); + let result = read_ok(&layer(&body)); + assert!(result.unread.is_empty(), "{:?}", result.unread); + assert!(result.hidden_unread.contains("symbols")); + assert_eq!(art(&result.doc)[0].children().expect("group children").len(), 1); +} + +#[test] +fn unresolved_pattern_paint_persists_past_plain_group_until_replaced() { + for (operator, draw, reset) in [("p", "f", "0 0 0 1 k"), ("P", "S", "0 0 0 1 K")] { + let body = format!( + "u\n(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] {operator}\n{}{draw}\nU\n{}{draw}\n{reset}\n{}{draw}\n", + rect_path(0.0, 0.0, 4.0, 4.0), + rect_path(10.0, 0.0, 14.0, 4.0), + rect_path(20.0, 0.0, 24.0, 4.0), + ); + let result = read_ok(&layer(&body)); + assert_eq!(result.unread.len(), 2, "{operator}: {:?}", result.unread); + assert_eq!(art(&result.doc).len(), 3); + } +} + +#[test] +fn unresolved_pattern_paint_inside_clip_restores_at_q() { + for (operator, draw, reset) in [("p", "f", "0 0 0 1 k"), ("P", "S", "0 0 0 1 K")] { + let body = format!( + "q\n(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] {operator}\n{}{draw}\nQ\n{}{draw}\n", + rect_path(0.0, 0.0, 4.0, 4.0), + rect_path(10.0, 0.0, 14.0, 4.0), + ); + let result = read_ok(&layer(&body)); + assert_eq!(result.unread.len(), 1, "{operator}: {:?}", result.unread); + assert_eq!(art(&result.doc).len(), 2); + + let body = format!( + "(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] {operator}\nq\n{reset}\n{}{draw}\nQ\n{}{draw}\n", + rect_path(0.0, 0.0, 4.0, 4.0), + rect_path(10.0, 0.0, 14.0, 4.0), + ); + let result = read_ok(&layer(&body)); + assert_eq!(result.unread.len(), 1, "{operator}: {:?}", result.unread); + assert_eq!(result.unread[0].0, art(&result.doc)[1].id); + } +} + #[test] fn sections_it_skips() { let body = "%AI5_Begin_NonPrinting\n%AI14_BeginSymbol\n0 Ae\nu\nfrobnicate\n%AI10_EndSymbol\n%AI3_BeginPattern: (P)\nU\nU\n%AI3_EndPattern\n%AI5_End_NonPrinting--\n\ diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index efbb8a3a11..8744db0eac 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -90,7 +90,7 @@ mod tests { ring(&mut layers, Some(MADE), red, 6.0, square); ring(&mut layers, Some(MADE), red, 2.0, Rect::new(40.0, 40.0, 60.0, 60.0)); let rect = page.artboards[0].rect; - let frame = Frame { page: &page, page_rect: rect, rect, whole: false }; + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; let mut view = PageView::new(&frame); assert_eq!(prune_unseen(&frame, &mut view, &mut layers, false), 1, "only the ring the page doesn't draw"); let widths: Vec<f64> = layers.layers[0].children().unwrap().iter().filter_map(|n| n.appearance.stroke().map(|s| s.width)).collect(); @@ -192,7 +192,7 @@ mod tests { let a = comparison_render(&mut renderer, &page, rect, 0.4, 1); let b = comparison_render(&mut vectorcraft_render::Renderer::new(), &vector, rect, 0.4, 1); assert!(compared(&a, &b, &[], &[]).solid > MAX_SOLID_DIFFERENCE, "the old point sampling falsely refused this page"); - let frame = Frame { page: &page, page_rect: rect, rect, whole: false }; + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; let mut view = PageView::new(&frame); assert!(compare(&frame, &mut view, &vector, false).is_ok()); assert!(compare(&frame, &mut view, &Document::new(1000.0, 500.0), false).is_err(), "missing artwork remains an error"); diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 1dd8b7d2b0..0ed2f354f9 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -26,6 +26,8 @@ pub(super) struct Frame<'a> { /// The page holds all the art that prints (an EPS's page is its art's box, unless it was /// saved as its artboard): the layers print nothing outside it. pub(super) whole: bool, + /// The PDF page areas and their moves into the editing document. + pub(super) pages: Vec<(Rect, Affine)>, } /// The document of the editing copy `data`, with the text (and strokes round it) of `visible`, the @@ -57,7 +59,20 @@ pub(super) fn build_from( trust: bool, unit: f64, ) -> Result<(Document, Vec<String>), String> { - let Structure { mut doc, to_doc, bbox, artboard, template, hidden_unread, slot_names, restyled, placed_elsewhere, warnings } = structure; + let Structure { + mut doc, + to_doc, + bbox, + artboard, + template, + hidden_unread, + unread, + unread_elsewhere, + slot_names, + restyled, + placed_elsewhere, + warnings, + } = structure; // Editing data in the units of the page's user space ([`in_units`]) is compared with the page // scaled down to those units, and the document read from it is scaled up by `unit`. let board = artboard.map(|a| to_doc.transform_rect_bbox(a)); @@ -132,6 +147,15 @@ pub(super) fn build_from( // goes where the layers have that artboard. let pages: Vec<Rect> = visible.artboards.iter().map(|a| a.rect).collect(); let boards = page_boards(&doc.artboards, first, &pages); + let page_moves: Vec<(Rect, Affine)> = pages + .iter() + .enumerate() + .map(|(i, page)| { + let move_to_doc = + boards.and_then(|boards| boards.get(i)).map(|board| Affine::translate(board.rect.origin() - page.origin())).unwrap_or(shift); + (*page, move_to_doc) + }) + .collect(); // The page with most of an object, the first for what is on none. let page_of = |object: &[Arc<Node>]| { extent(object).and_then(|r| { @@ -167,7 +191,7 @@ pub(super) fn build_from( a.rect = rect; } } - frame = Some(Frame { page: visible, page_rect, rect, whole }); + frame = Some(Frame { page: visible, page_rect, rect, whole, pages: page_moves }); } let mut infos = vec![]; collect_slots(&doc.layers, true, &mut infos); @@ -180,6 +204,9 @@ pub(super) fn build_from( if outlined && infos.iter().any(|i| i.shown) { return Err("its type is to come in as outlines, which only its page has".into()); } + // The page's type inside an unread object's box comes in with the page's art that replaces the + // object (see [`replace_unread`]), not in a text object. + let unread_type = take_unread_type(&doc, frame.as_ref(), &unread, &unread_elsewhere, &mut shown); // The page's type that needs no text object of the layers: the layers' own legacy text, or // placed files that show it. let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?; @@ -214,8 +241,22 @@ pub(super) fn build_from( let mut made = vec![]; fill_slots(&mut doc, &mut layers, &mut content.into_iter(), &slot_names, &mut empty, &mut made, &mut vec![]); doc.layers = layers; - // A story in several frames is threaded type: its frames in order (the first holds the story). made.sort(); + let threaded_frames: BTreeSet<NodeId> = + made.chunk_by(|a, b| a.0 == b.0).filter(|thread| thread.len() > 1).flatten().map(|(_, _, id)| *id).collect(); + if !unread.is_empty() { + let Some(frame) = frame.as_ref() else { return Err(unread_error(&unread)) }; + let mut copied = BTreeSet::new(); + let kinds = replace_unread(&mut doc, frame, &unread, &unread_elsewhere, &threaded_frames, &mut copied)?; + // With the text objects filled, the page art chosen can differ from the first try's: the + // page's type set aside for it, and no other, must be in it. + let all_copied = |o: &Vec<Arc<Node>>| !o.is_empty() && o.iter().all(|n| copied.contains(&n.id)); + if !unread_type.iter().all(all_copied) || shown.iter().any(all_copied) { + return Err("the page's type in an unread object's box isn't in its page art".into()); + } + notes.push(format!("{}: they came in as the page's art", kinds.join(", "))); + } + // A story in several frames is threaded type: its frames in order (the first holds the story). for thread in made.chunk_by(|a, b| a.0 == b.0) { if thread.len() > 1 { doc.text_threads.push(thread.iter().map(|(_, _, id)| *id).collect()); @@ -285,6 +326,406 @@ pub(super) fn build_from( Ok((doc, notes)) } +/// A visible page node, with its source order and subtree range. +struct PageArt { + node: Arc<Node>, + bounds: Rect, + page: usize, + end: usize, + stateful_ancestor: bool, +} + +const ART_MARGIN: f64 = 1.0; + +fn inside(art: Rect, bounds: Rect) -> bool { + art.x0 >= bounds.x0 - ART_MARGIN && art.y0 >= bounds.y0 - ART_MARGIN && art.x1 <= bounds.x1 + ART_MARGIN && art.y1 <= bounds.y1 + ART_MARGIN +} + +/// Pick the page holding the most of a box. The first page wins a tie. +fn page_for(bounds: Rect, pages: &[Rect]) -> usize { + let mut best = (0, 0.0); + for (i, page) in pages.iter().enumerate() { + let area = page.intersect(bounds).area().max(0.0); + if area > best.1 { + best = (i, area); + } + } + best.0 +} + +fn collect_live(node: &Node, unread: &BTreeSet<NodeId>, live: &mut Vec<Rect>) { + if !node.visible || unread.contains(&node.id) { + return; + } + if let Some(children) = node.children() { + for child in children { + collect_live(child, unread, live); + } + } else if let Some(bounds) = node.visual_bounds() { + live.push(bounds); + } +} + +fn page_node_has_drawing_state(node: &Node) -> bool { + node.clips() + || matches!(node.kind, NodeKind::Path { clipping: true, .. }) + || node.opacity < 1.0 + || node.blend != super::BlendMode::Normal + || node.isolate + || node.knockout != vectorcraft_doc::Knockout::Neutral + || node.extras().mask.is_some() + || !node.appearance.items.is_empty() + || !node.appearance.effects.is_empty() +} + +fn index_page(node: &Arc<Node>, pages: &[Rect], moves: &[Affine], art: &mut Vec<PageArt>, stateful_ancestor: bool) { + if !node.visible { + return; + } + let start = art.len(); + let mut indexed = false; + if let Some(bounds) = node.visual_bounds() { + let page = page_for(bounds, pages); + if let Some(shift) = moves.get(page) { + art.push(PageArt { node: Arc::clone(node), bounds: shift.transform_rect_bbox(bounds), page, end: start + 1, stateful_ancestor }); + indexed = true; + } + } + if let Some(children) = node.children() { + for child in children { + index_page(child, pages, moves, art, stateful_ancestor || page_node_has_drawing_state(node)); + } + } + let end = art.len(); + if indexed && let Some(entry) = art.get_mut(start) { + entry.end = end; + } +} + +/// Node IDs belong to the importing document, not to the pattern's drawing. +fn same_pattern_art(existing: &vectorcraft_doc::PatternDef, source: &vectorcraft_doc::PatternDef) -> bool { + fn clear_ids(node: &mut Node) { + node.id = NodeId(0); + if let Some(children) = node.children_mut() { + for child in children { + clear_ids(Arc::make_mut(child)); + } + } + if let Some(mask) = &mut node.extras_mut().mask { + clear_ids(Arc::make_mut(&mut mask.art)); + } + } + + let mut a = existing.clone(); + let mut b = source.clone(); + for pattern in [&mut a, &mut b] { + for node in &mut pattern.art { + clear_ids(Arc::make_mut(node)); + } + } + a == b +} + +/// Bring document resources used by page art across before reassigning its node IDs. +fn copy_page_resources(doc: &mut Document, page: &Document, nodes: &[&Node]) -> Result<(), String> { + fn collect(node: &Node, images: &mut BTreeSet<String>, patterns: &mut BTreeSet<String>, swatches: &mut BTreeSet<String>) { + if let NodeKind::Image(im) = &node.kind { + images.insert(im.key.clone()); + } + for item in &node.appearance.items { + match item.paint() { + vectorcraft_color::Paint::Solid { swatch: Some(name), .. } => { + swatches.insert(name.clone()); + } + vectorcraft_color::Paint::Gradient(gradient) => { + if let Some(name) = &gradient.swatch { + swatches.insert(name.clone()); + } + for stop in &gradient.gradient.stops { + if let Some(name) = &stop.swatch { + swatches.insert(name.clone()); + } + } + } + vectorcraft_color::Paint::Pattern { pattern, .. } => { + patterns.insert(pattern.clone()); + } + _ => {} + } + } + if let Some(mask) = &node.extras().mask { + collect(&mask.art, images, patterns, swatches); + } + for child in node.children().into_iter().flatten() { + collect(child, images, patterns, swatches); + } + } + + let (mut images, mut patterns, mut swatches) = (BTreeSet::new(), BTreeSet::new(), BTreeSet::new()); + for node in nodes { + collect(node, &mut images, &mut patterns, &mut swatches); + } + let mut copied = BTreeSet::new(); + while let Some(name) = patterns.pop_first() { + if !copied.insert(name.clone()) { + continue; + } + let Some(source) = page.pattern(&name) else { return Err(format!("page art is missing pattern {name}")) }; + if let Some(existing) = doc.pattern(&name) { + if !same_pattern_art(existing, source) { + return Err(format!("page art conflicts with pattern {name}")); + } + } else { + for node in &source.art { + collect(node, &mut images, &mut patterns, &mut swatches); + } + let mut pattern = source.clone(); + pattern.art = pattern.art.iter().map(|node| Arc::new(reid_page_art(doc, node))).collect(); + doc.patterns.push(pattern); + } + } + for key in images { + let Some(blob) = page.images.get(&key) else { return Err(format!("page art is missing image data for {key}")) }; + if doc.images.get(&key).is_some_and(|existing| existing.bytes != blob.bytes) { + return Err(format!("page art conflicts with image data for {key}")); + } + doc.images.entry(key).or_insert_with(|| blob.clone()); + } + for name in swatches { + let Some(source) = page.swatch(&name) else { return Err(format!("page art is missing swatch {name}")) }; + if let Some(existing) = doc.swatch(&name) { + if existing != source { + return Err(format!("page art conflicts with swatch {name}")); + } + } else { + doc.swatches.push(source.clone()); + } + } + Ok(()) +} + +/// The PDF importer keeps group transparency on a group, or folds it into its only child. +/// If the editing object's state cannot be located in that art, use the PDF page as a whole. +/// Every selected page object must carry the state, on itself or down a chain of only children. +fn page_carries_state(editing: &Node, page: &[&Node]) -> bool { + fn carried(node: &Node, matches: &dyn Fn(&Node) -> bool) -> bool { + matches(node) + || match node.children().map(Vec::as_slice) { + Some([only]) => carried(only, matches), + _ => false, + } + } + let has = |matches: &dyn Fn(&Node) -> bool| !page.is_empty() && page.iter().all(|node| carried(node, matches)); + let opacity = editing.opacity >= 0.999 || has(&|node: &Node| (node.opacity - editing.opacity).abs() < 0.001); + let blend = editing.blend == super::BlendMode::Normal || has(&|node: &Node| node.blend == editing.blend); + let isolate = !editing.isolate || has(&|node: &Node| node.isolate); + let knockout = matches!(editing.knockout, vectorcraft_doc::Knockout::Neutral | vectorcraft_doc::Knockout::Off) + || has(&|node: &Node| node.knockout == editing.knockout); + let appearance = !matches!(editing.kind, NodeKind::Group { .. }) || *editing.appearance == vectorcraft_doc::Appearance::default(); + opacity && blend && isolate && knockout && appearance +} + +/// The error for unread objects with no page art to use: what isn't read, as the reader names it. +fn unread_error(unread: &[(NodeId, Vec<String>)]) -> String { + let kinds: BTreeSet<&str> = unread.iter().flat_map(|(_, kinds)| kinds.iter().map(String::as_str)).collect(); + let (ops, other): (Vec<&str>, Vec<&str>) = kinds.into_iter().partition(|k| k.starts_with('`')); + let mut list: BTreeSet<String> = other.into_iter().map(String::from).collect(); + if !ops.is_empty() { + list.insert(format!("operators VectorCraft doesn't know ({})", ops.join(", "))); + } + let list: Vec<&str> = list.iter().map(String::as_str).collect(); + format!("it has {}, which VectorCraft doesn't read from it yet", ai::join_and(&list)) +} + +/// The page's text objects in `shown` that the page objects replacing `doc`'s unread objects hold +/// (see [`replace_unread`], tried on a copy of `doc` before its text objects are filled), taken out +/// of `shown`. +fn take_unread_type( + doc: &Document, + frame: Option<&Frame<'_>>, + unread: &[(NodeId, Vec<String>)], + elsewhere: &[(NodeId, Rect)], + shown: &mut Vec<Vec<Arc<Node>>>, +) -> Vec<Vec<Arc<Node>>> { + let Some(frame) = frame.filter(|_| !unread.is_empty() && !shown.is_empty()) else { return vec![] }; + let mut copied = BTreeSet::new(); + if replace_unread(&mut doc.clone(), frame, unread, elsewhere, &BTreeSet::new(), &mut copied).is_err() { + return vec![]; + } + let (taken, kept) = std::mem::take(shown).into_iter().partition(|o| !o.is_empty() && o.iter().all(|n| copied.contains(&n.id))); + *shown = kept; + taken +} + +/// Replace each unread top-level object with painted page objects inside its readable bounds. +/// `copied` gets the ids of the page's nodes copied. +fn replace_unread( + doc: &mut Document, + frame: &Frame<'_>, + unread: &[(NodeId, Vec<String>)], + elsewhere: &[(NodeId, Rect)], + threaded_frames: &BTreeSet<NodeId>, + copied: &mut BTreeSet<NodeId>, +) -> Result<Vec<String>, String> { + fn holds_threaded_frame(node: &Node, frames: &BTreeSet<NodeId>) -> bool { + frames.contains(&node.id) || node.children().is_some_and(|children| children.iter().any(|child| holds_threaded_frame(child, frames))) + } + fn subtree(node: &Node, ids: &mut BTreeSet<NodeId>) { + ids.insert(node.id); + for child in node.children().into_iter().flatten() { + subtree(child, ids); + } + } + + let unread_ids: BTreeSet<NodeId> = unread.iter().map(|(id, _)| *id).collect(); + let mut live = Vec::new(); + for layer in &doc.layers { + collect_live(layer, &unread_ids, &mut live); + } + live.sort_by(|a, b| a.x0.total_cmp(&b.x0)); + + let source_pages: Vec<Rect> = frame.pages.iter().map(|(page, _)| *page).collect(); + let moves: Vec<Affine> = frame.pages.iter().map(|(_, shift)| *shift).collect(); + let destination_pages: Vec<Rect> = frame.pages.iter().map(|(page, shift)| shift.transform_rect_bbox(*page)).collect(); + let mut art = Vec::new(); + for layer in &frame.page.layers { + if layer.visible + && let Some(children) = layer.children() + { + for child in children { + index_page(child, &source_pages, &moves, &mut art, false); + } + } + } + let mut by_x: Vec<usize> = (0..art.len()).collect(); + by_x.sort_by(|a, b| art[*a].bounds.x0.total_cmp(&art[*b].bounds.x0)); + let mut claimed = std::collections::BTreeMap::<usize, usize>::new(); + let mut counts = std::collections::BTreeMap::<String, usize>::new(); + for (id, kinds) in unread { + let Some((bounds, name, visible, locked, editing)) = + doc.node(*id).and_then(|n| n.visual_bounds().map(|b| (b, n.name.clone(), n.visible, n.locked, n.clone()))) + else { + return Err("an unread object has no readable bounds".into()); + }; + if !bounds.area().is_finite() || bounds.area() <= 0.0 { + return Err("an unread object has no readable bounds".into()); + } + let mut selected = Vec::new(); + let mut page = 0; + let mut first_rejection = None; + 'candidate: for candidate in std::iter::once(bounds).chain(elsewhere.iter().filter(|(other, _)| *other == *id).map(|(_, b)| *b)) { + let live_start = live.partition_point(|b| b.x0 < candidate.x0 - ART_MARGIN); + let live_end = live.partition_point(|b| b.x0 <= candidate.x1 + ART_MARGIN); + if live[live_start..live_end].iter().any(|art| inside(*art, candidate)) { + first_rejection.get_or_insert("an unread object's bounds also contain live art"); + continue; + } + // Each page has its own copy of art across artboards: one page's art can't stand in for it. + if destination_pages.iter().filter(|page| page.intersect(candidate).area() > 0.0).count() > 1 { + first_rejection.get_or_insert("an unread object lies on more than one artboard"); + continue; + } + let candidate_page = page_for(candidate, &destination_pages); + // An artboard that has no page (a PDF part saved with some of the artboards) has no art + // on the page for the object's part on it. + if let Some(page) = destination_pages.get(candidate_page) + && doc.artboards.iter().map(|a| a.rect.intersect(candidate)).any(|part| part.area() > page.intersect(part).area().max(0.0)) + { + first_rejection.get_or_insert("an unread object lies on an artboard that has no page"); + continue; + } + let start = by_x.partition_point(|i| art[*i].bounds.x0 < candidate.x0 - ART_MARGIN); + let end = by_x.partition_point(|i| art[*i].bounds.x0 <= candidate.x1 + ART_MARGIN); + let mut candidates: Vec<usize> = + by_x[start..end].iter().copied().filter(|i| art[*i].page == candidate_page && inside(art[*i].bounds, candidate)).collect(); + candidates.sort_unstable(); + let mut covered_until = 0; + let mut candidate_selected = Vec::new(); + for i in candidates { + if i < covered_until || matches!(art[i].node.kind, NodeKind::Path { clipping: true, .. }) { + continue; + } + if art[i].stateful_ancestor { + first_rejection.get_or_insert("an unread object's page art depends on a clipping or appearance ancestor"); + continue 'candidate; + } + covered_until = art[i].end; + candidate_selected.push(i); + } + if !candidate_selected.is_empty() + && !page_carries_state(&editing, &candidate_selected.iter().map(|&i| art[i].node.as_ref()).collect::<Vec<_>>()) + { + first_rejection.get_or_insert("an unread object's appearance is not identifiable in the page art"); + continue; + } + if candidate_selected.iter().any(|&i| claimed.range(..art[i].end).next_back().is_some_and(|(_, end)| *end > i)) { + first_rejection.get_or_insert("one page object matches more than one unread object"); + continue; + } + if !candidate_selected.is_empty() { + selected = candidate_selected; + page = candidate_page; + break; + } + } + if selected.is_empty() { + return Err(first_rejection.unwrap_or("an unread object's page art wasn't found in its bounds").into()); + } + if holds_threaded_frame(&editing, threaded_frames) { + return Err("an unread object holds a frame of threaded type".into()); + } + copy_page_resources(doc, frame.page, &selected.iter().map(|&i| art[i].node.as_ref()).collect::<Vec<_>>())?; + let mut found = Vec::new(); + for &i in &selected { + let mut copy = Node::clone(&art[i].node); + if let Some(shift) = moves.get(page) { + copy.transform(*shift, false); + } + found.push(Arc::new(reid_page_art(doc, ©))); + claimed.insert(i, art[i].end); + subtree(&art[i].node, copied); + } + let mut replacement = Node::group(*id, found); + replacement.name = name; + replacement.visible = visible; + replacement.locked = locked; + let Some(target) = doc.node_mut(*id) else { return Err("an unread object is missing from its layer".into()) }; + *target = replacement; + for kind in kinds { + *counts.entry(kind.clone()).or_default() += 1; + } + } + Ok(counts.into_iter().map(|(kind, count)| format!("{kind} ({count})")).collect()) +} + +/// Copy page drawing IDs, including mask art outside the ordinary child tree. +fn reid_page_art(doc: &mut Document, source: &Node) -> Node { + let mut copy = doc.reid(source); + if let Some(mask) = &mut copy.extras_mut().mask { + mask.art = Arc::new(reid_page_art(doc, &mask.art)); + } + if let Some(children) = copy.children_mut() { + for child in children { + let node = reid_page_art_masks(doc, child); + *child = Arc::new(node); + } + } + copy +} + +fn reid_page_art_masks(doc: &mut Document, source: &Node) -> Node { + let mut copy = source.clone(); + if let Some(mask) = &mut copy.extras_mut().mask { + mask.art = Arc::new(reid_page_art(doc, &mask.art)); + } + if let Some(children) = copy.children_mut() { + for child in children { + *child = Arc::new(reid_page_art_masks(doc, child)); + } + } + copy +} + /// What goes into each of `infos`' slots, and whether the type is all made from the file's text /// document. When the text document makes the type of every text object that shows (and the type /// isn't asked for as outlines: `own` has the page's text objects that show outside placed files), @@ -315,18 +756,20 @@ fn slot_content( /// `doc` with the placed files `placed` lists at their other placement (see /// [`ai::Structure::placed_elsewhere`]): each image's transform followed by its move. `None` when -/// none is listed. +/// no listed image survives replacement. fn elsewhere(doc: &Document, placed: &[(NodeId, Affine)]) -> Option<Document> { if placed.is_empty() { return None; } let mut doc = doc.clone(); + let mut moved = false; for (id, shift) in placed { if let Some(NodeKind::Image(im)) = doc.node_mut(*id).map(|n| &mut n.kind) { im.xf *= *shift; + moved = true; } } - Some(doc) + moved.then_some(doc) } /// The page's type that needs no text object of the layers, taken out of `shown` and `hidden` (the @@ -599,3 +1042,304 @@ pub(super) fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Doc } removed } + +#[cfg(test)] +mod candidate_tests { + use super::*; + + use vectorcraft_doc::{ImageBlob, ImageObject}; + + /// A page image with a different proxy keeps its editing layer and original blob. + #[test] + fn page_image_with_different_proxy_keeps_editing_layer() { + let mut doc = Document::new(100.0, 100.0); + let placeholder_id = doc.alloc_id(); + let placeholder = Node::path(placeholder_id, vectorcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 54.0, 54.0)), Default::default()); + doc.insert(Some(doc.layers[0].id), 0, placeholder).unwrap(); + + let mut page = Document::new(100.0, 100.0); + let mut editing_blob = ImageBlob::new("image/png", vec![1, 2, 3]); + editing_blob.proxy = Some(Arc::new(vec![4, 5, 6])); + let page_blob = ImageBlob::new("image/png", vec![1, 2, 3]); + let key = editing_blob.content_key(); + assert_eq!(key, page_blob.content_key()); + doc.images.insert(key.clone(), editing_blob.clone()); + page.images.insert(key.clone(), page_blob); + let image = Node::new( + page.alloc_id(), + NodeKind::Image(Box::new(ImageObject { + key: key.clone(), + width: 4, + height: 4, + xf: Affine::translate(Vec2::new(50.0, 50.0)), + link: None, + placement: Default::default(), + pixels: None, + })), + ); + page.insert(Some(page.layers[0].id), 0, image).unwrap(); + + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; + let kinds = replace_unread( + &mut doc, + &frame, + &[(placeholder_id, vec!["placed files".into()])], + &[(placeholder_id, Rect::new(50.0, 50.0, 54.0, 54.0))], + &BTreeSet::new(), + &mut BTreeSet::new(), + ) + .unwrap(); + assert_eq!(kinds, ["placed files (1)"]); + let replacement = doc.node(placeholder_id).unwrap(); + let [image] = replacement.children().unwrap().as_slice() else { panic!("{replacement:?}") }; + assert!(matches!(image.kind, NodeKind::Image(_))); + assert_eq!(doc.images.get(&key), Some(&editing_blob)); + } + + /// An unread object across two artboards isn't replaced by the art of one page only. + #[test] + fn unread_object_across_two_pages_is_not_replaced() { + let mut doc = Document::new(200.0, 100.0); + let id = doc.alloc_id(); + doc.insert( + Some(doc.layers[0].id), + 0, + Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(90.0, 10.0, 110.0, 20.0)), Default::default()), + ) + .unwrap(); + let mut page = Document::new(200.0, 100.0); + for bounds in [Rect::new(91.0, 11.0, 99.0, 19.0), Rect::new(101.0, 11.0, 109.0, 19.0)] { + let art = Node::path( + page.alloc_id(), + vectorcraft_geom::shapes::rectangle(bounds), + vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + vectorcraft_color::Paint::None, + 0.0, + ), + ); + page.insert(Some(page.layers[0].id), page.layers[0].children().unwrap().len(), art).unwrap(); + } + let (first, second) = (Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(100.0, 0.0, 200.0, 100.0)); + let frame = + Frame { page: &page, page_rect: first, rect: first, whole: false, pages: vec![(first, Affine::IDENTITY), (second, Affine::IDENTITY)] }; + let result = replace_unread(&mut doc, &frame, &[(id, vec!["placed files".into()])], &[], &BTreeSet::new(), &mut BTreeSet::new()); + assert_eq!(result.unwrap_err(), "an unread object lies on more than one artboard"); + } + + /// An unread object reaching an artboard that has no page isn't replaced by the page's part of it. + #[test] + fn unread_object_on_an_artboard_without_a_page_is_not_replaced() { + let mut doc = Document::new(100.0, 100.0); + doc.artboards.push(vectorcraft_doc::Artboard { id: 2, rect: Rect::new(100.0, 0.0, 200.0, 100.0), ..doc.artboards[0].clone() }); + let id = doc.alloc_id(); + doc.insert( + Some(doc.layers[0].id), + 0, + Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(90.0, 10.0, 110.0, 20.0)), Default::default()), + ) + .unwrap(); + let mut page = Document::new(100.0, 100.0); + let art = Node::path( + page.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(91.0, 11.0, 99.0, 19.0)), + vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), vectorcraft_color::Paint::None, 0.0), + ); + page.insert(Some(page.layers[0].id), 0, art).unwrap(); + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; + let result = replace_unread(&mut doc, &frame, &[(id, vec!["placed files".into()])], &[], &BTreeSet::new(), &mut BTreeSet::new()); + assert_eq!(result.unwrap_err(), "an unread object lies on an artboard that has no page"); + + // Half a point onto it is still on it. + let narrow = Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(90.0, 10.0, 100.5, 20.0)), Default::default()); + *doc.node_mut(id).unwrap() = narrow; + let result = replace_unread(&mut doc, &frame, &[(id, vec!["placed files".into()])], &[], &BTreeSet::new(), &mut BTreeSet::new()); + assert_eq!(result.unwrap_err(), "an unread object lies on an artboard that has no page"); + } + + /// A nested placeholder's corner cannot replace its readable sibling. + #[test] + fn nested_placeholder_corner_cannot_replace_readable_sibling() { + let mut doc = Document::new(100.0, 100.0); + let group_id = doc.alloc_id(); + let placeholder = Node::path(doc.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(10.0, 10.0, 20.0, 20.0)), Default::default()); + let placeholder_id = placeholder.id; + let sibling = Node::path(doc.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(70.0, 70.0, 74.0, 74.0)), Default::default()); + let sibling_id = sibling.id; + let group = Node::group(group_id, vec![Arc::new(placeholder), Arc::new(sibling)]); + doc.insert(Some(doc.layers[0].id), 0, group).unwrap(); + + let mut page = Document::new(100.0, 100.0); + let art = Node::path( + page.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(81.0, 81.0, 89.0, 89.0)), + vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), vectorcraft_color::Paint::None, 0.0), + ); + page.insert(Some(page.layers[0].id), 0, art).unwrap(); + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; + let result = replace_unread( + &mut doc, + &frame, + &[(group_id, vec!["placed files".into()])], + &[(placeholder_id, Rect::new(80.0, 80.0, 90.0, 90.0))], + &BTreeSet::new(), + &mut BTreeSet::new(), + ); + assert_eq!(result.unwrap_err(), "an unread object's page art wasn't found in its bounds"); + let group = doc.node(group_id).unwrap(); + assert!(group.children().unwrap().iter().any(|child| child.id == sibling_id)); + } + + /// An alternative box may carry opacity missing from the first box. + #[test] + fn alternative_box_can_carry_opacity_when_first_box_cannot() { + let mut doc = Document::new(100.0, 100.0); + let id = doc.alloc_id(); + let mut editing = Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(10.0, 10.0, 20.0, 20.0)), Default::default()); + editing.opacity = 0.5; + doc.insert(Some(doc.layers[0].id), 0, editing).unwrap(); + + let mut page = Document::new(100.0, 100.0); + for (bounds, opacity) in [(Rect::new(11.0, 11.0, 19.0, 19.0), 1.0), (Rect::new(51.0, 51.0, 59.0, 59.0), 0.5)] { + let mut art = Node::path( + page.alloc_id(), + vectorcraft_geom::shapes::rectangle(bounds), + vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + vectorcraft_color::Paint::None, + 0.0, + ), + ); + art.opacity = opacity; + page.insert(Some(page.layers[0].id), page.layers[0].children().unwrap().len(), art).unwrap(); + } + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; + let kinds = replace_unread( + &mut doc, + &frame, + &[(id, vec!["placed files".into()])], + &[(id, Rect::new(50.0, 50.0, 60.0, 60.0))], + &BTreeSet::new(), + &mut BTreeSet::new(), + ) + .unwrap(); + assert_eq!(kinds, ["placed files (1)"]); + let replacement = doc.node(id).unwrap(); + let [art] = replacement.children().unwrap().as_slice() else { panic!("{replacement:?}") }; + assert_eq!(art.opacity, 0.5); + assert_eq!(art.geometric_bounds(), Some(Rect::new(51.0, 51.0, 59.0, 59.0))); + } + + /// Opacity on one of two page objects in the box is not the unread object's opacity. + #[test] + fn opacity_on_one_of_two_page_objects_is_not_identifiable() { + let mut doc = Document::new(100.0, 100.0); + let id = doc.alloc_id(); + let mut editing = Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(10.0, 10.0, 40.0, 40.0)), Default::default()); + editing.opacity = 0.5; + doc.insert(Some(doc.layers[0].id), 0, editing).unwrap(); + + let mut page = Document::new(100.0, 100.0); + for (bounds, opacity) in [(Rect::new(11.0, 11.0, 19.0, 19.0), 0.5), (Rect::new(21.0, 21.0, 39.0, 39.0), 1.0)] { + let mut art = Node::path( + page.alloc_id(), + vectorcraft_geom::shapes::rectangle(bounds), + vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + vectorcraft_color::Paint::None, + 0.0, + ), + ); + art.opacity = opacity; + page.insert(Some(page.layers[0].id), page.layers[0].children().unwrap().len(), art).unwrap(); + } + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; + let result = replace_unread(&mut doc, &frame, &[(id, vec!["placed files".into()])], &[], &BTreeSet::new(), &mut BTreeSet::new()); + assert_eq!(result.unwrap_err(), "an unread object's appearance is not identifiable in the page art"); + } + + /// A claimed first box lets a second unread object use its own corner box. + #[test] + fn second_unread_object_tries_corner_after_first_box_is_claimed() { + let mut doc = Document::new(100.0, 100.0); + let first = doc.alloc_id(); + let second = doc.alloc_id(); + for (id, bounds) in [(first, Rect::new(10.0, 10.0, 20.0, 20.0)), (second, Rect::new(12.0, 12.0, 22.0, 22.0))] { + let node = Node::path(id, vectorcraft_geom::shapes::rectangle(bounds), Default::default()); + doc.insert(Some(doc.layers[0].id), doc.layers[0].children().unwrap().len(), node).unwrap(); + } + + let mut page = Document::new(100.0, 100.0); + for bounds in [Rect::new(14.0, 14.0, 16.0, 16.0), Rect::new(51.0, 51.0, 59.0, 59.0)] { + let art = Node::path( + page.alloc_id(), + vectorcraft_geom::shapes::rectangle(bounds), + vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + vectorcraft_color::Paint::None, + 0.0, + ), + ); + page.insert(Some(page.layers[0].id), page.layers[0].children().unwrap().len(), art).unwrap(); + } + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; + let unread = [(first, vec!["placed files".into()]), (second, vec!["placed files".into()])]; + let mut one_box_doc = doc.clone(); + let kinds = replace_unread(&mut doc, &frame, &unread, &[(second, Rect::new(50.0, 50.0, 60.0, 60.0))], &BTreeSet::new(), &mut BTreeSet::new()) + .unwrap(); + assert_eq!(kinds, ["placed files (2)"]); + let first_art = doc.node(first).unwrap().children().unwrap()[0].geometric_bounds(); + let second_art = doc.node(second).unwrap().children().unwrap()[0].geometric_bounds(); + assert_eq!(first_art, Some(Rect::new(14.0, 14.0, 16.0, 16.0))); + assert_eq!(second_art, Some(Rect::new(51.0, 51.0, 59.0, 59.0))); + assert_eq!( + replace_unread(&mut one_box_doc, &frame, &unread, &[], &BTreeSet::new(), &mut BTreeSet::new()).unwrap_err(), + "one page object matches more than one unread object" + ); + } + + /// Only the page's type in the page art that replaces an unread object is taken out of the + /// page's type for the text objects: type in the object's other box, which isn't used, stays. + #[test] + fn only_page_type_in_the_chosen_box_is_taken_for_an_unread_object() { + let mut doc = Document::new(100.0, 100.0); + let id = doc.alloc_id(); + doc.insert( + Some(doc.layers[0].id), + 0, + Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(10.0, 10.0, 20.0, 20.0)), Default::default()), + ) + .unwrap(); + let mut page = Document::new(100.0, 100.0); + let mut nodes = vec![]; + for bounds in [Rect::new(12.0, 12.0, 18.0, 18.0), Rect::new(52.0, 52.0, 58.0, 58.0)] { + let art = Node::path( + page.alloc_id(), + vectorcraft_geom::shapes::rectangle(bounds), + vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + vectorcraft_color::Paint::None, + 0.0, + ), + ); + nodes.push(Arc::new(art.clone())); + page.insert(Some(page.layers[0].id), page.layers[0].children().unwrap().len(), art).unwrap(); + } + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; + let unread = [(id, vec!["placed files".into()])]; + let mut shown: Vec<Vec<Arc<Node>>> = nodes.iter().map(|n| vec![Arc::clone(n)]).collect(); + let taken = take_unread_type(&doc, Some(&frame), &unread, &[(id, Rect::new(50.0, 50.0, 60.0, 60.0))], &mut shown); + assert_eq!(taken.iter().flatten().map(|n| n.id).collect::<Vec<_>>(), [nodes[0].id]); + assert_eq!(shown.iter().flatten().map(|n| n.id).collect::<Vec<_>>(), [nodes[1].id]); + let mut copied = BTreeSet::new(); + replace_unread(&mut doc, &frame, &unread, &[], &BTreeSet::new(), &mut copied).unwrap(); + assert!(copied.contains(&nodes[0].id) && !copied.contains(&nodes[1].id)); + } +} diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index e6dc909ace..188a1b6e69 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -24,6 +24,7 @@ pub(super) const LAYERS_UNREAD: &str = "the file's layers weren't read"; pub fn is_loss(note: &str) -> bool { note.ends_with(TEXT_LEFT_OUT) || note.ends_with(TYPE_LEFT_OUT) + || note.ends_with("they came in as the page's art") || note == PAGE_TYPE_LEFT_OUT || note == PAGE_TYPE_UNCHECKED || [ART_LEFT_OUT, LAYERS_UNREAD, crate::import::graphics::TOO_MUCH, crate::import::graphics::FAR_AWAY].iter().any(|n| note.starts_with(n)) diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 29e73bbc92..9ef30473e4 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -53,6 +53,10 @@ fn square(x: u32, y: u32) -> String { format!("0 0 1 0 k\n{x} {y} m\n{} {y} L\n{} {} L\n{x} {} L\nf", x + 4, x + 4, y + 4, y + 4) } +fn square_path(x: u32, y: u32) -> String { + format!("{x} {y} m\n{} {y} L\n{} {} L\n{x} {} L\nf", x + 4, x + 4, y + 4, y + 4) +} + /// An EPS whose page draws `page` and whose private data is `native`. fn eps(page: &str, native: &str) -> Vec<u8> { let stream = ascii85(&zstd(native)); @@ -258,6 +262,667 @@ fn pdf_part(x: f64, y: f64) -> Document { d } +fn pdf_two_squares() -> Document { + let mut page = pdf_part(10.0, 86.0); + let other = pdf_part(50.0, 86.0); + let layer = page.layers[0].id; + let mut square = page.reid(&other.layers[0].children().unwrap()[0]); + square.appearance = vectorcraft_doc::Appearance { + items: vec![vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(vectorcraft_color::Paint::solid( + vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0), + )))], + ..Default::default() + } + .into(); + page.insert(Some(layer), 1, square).unwrap(); + page +} + +fn pdf_three_squares() -> Document { + let mut page = pdf_two_squares(); + let other = pdf_part(70.0, 86.0); + let layer = page.layers[0].id; + let square = page.reid(&other.layers[0].children().unwrap()[0]); + page.insert(Some(layer), 2, square).unwrap(); + page +} + +fn pdf_split_square() -> Document { + let mut page = pdf_part(10.0, 86.0); + let layer = page.layers[0].id; + for (i, color) in [vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0), vectorcraft_color::Color::cmyk(0.0, 1.0, 0.0, 0.0)].into_iter().enumerate() + { + let x = 50.0 + 2.0 * i as f64; + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, 86.0, x + 2.0, 90.0)); + let appearance = vectorcraft_doc::Appearance { + items: vec![vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(vectorcraft_color::Paint::solid(color)))], + ..Default::default() + }; + let node = Node::path(page.alloc_id(), path, appearance); + page.insert(Some(layer), i + 1, node).unwrap(); + } + page +} + +fn os1_group(body: &str) -> String { + format!("u\n{body}\nU\n") +} + +fn replacement_is_cyan(doc: &Document, layer: usize, child: usize) { + let group = &doc.layers[layer].children().unwrap()[child]; + let art = &group.children().unwrap()[0]; + assert!(matches!(art.kind, NodeKind::Path { .. })); + assert!(matches!(art.appearance.items.first(), Some(vectorcraft_doc::AppearanceItem::Fill(fill)) + if fill.paint == vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0)))); +} + +fn replacement_has_two_halves(doc: &Document) { + let group = &doc.layers[1].children().unwrap()[0]; + let art = group.children().unwrap(); + assert_eq!(art.len(), 2); + assert_eq!(art[0].geometric_bounds().unwrap().x0, 50.0); + assert_eq!(art[1].geometric_bounds().unwrap().x0, 52.0); + assert!(matches!(art[0].appearance.items.first(), Some(vectorcraft_doc::AppearanceItem::Fill(fill)) + if fill.paint == vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0)))); + assert!(matches!(art[1].appearance.items.first(), Some(vectorcraft_doc::AppearanceItem::Fill(fill)) + if fill.paint == vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(0.0, 1.0, 0.0, 0.0)))); +} + +#[test] +fn top_level_symbol_uses_page_art_beside_live_path() { + let symbol = format!("%AI14_BeginSymbol\n(Dot) 0 Ae\n{}\n%AI10_EndSymbol\n", square(0, 0)); + let instance = "/SymbolInstance :\n(Dot) /SymbolRef ,\n[1 0 0 1 50 10] /Matrix ,\n;"; + let art = native(&(symbol + &layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &format!("{instance}\n{}", square(70, 10))))); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_three_squares(), vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Live", "Mixed"]); + assert_eq!(kinds(&doc.layers[1]), ["group[1]", "path"]); + replacement_is_cyan(&doc, 1, 0); + assert!(notes.iter().any(|n| n.contains("symbols (1)")), "{notes:?}"); +} + +#[test] +fn group_with_only_symbol_instance_uses_page_art() { + let symbol = format!("%AI14_BeginSymbol\n(Dot) 0 Ae\n{}\n%AI10_EndSymbol\n", square(0, 0)); + let instance = "/SymbolInstance :\n(Dot) /SymbolRef ,\n[1 0 0 1 50 10] /Matrix ,\n;"; + let art = native(&(symbol + &layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &os1_group(instance)))); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_two_squares(), vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Live", "Mixed"]); + assert_eq!(kinds(&doc.layers[1]), ["group[1]"]); + replacement_is_cyan(&doc, 1, 0); + assert!(notes.iter().any(|n| n.contains("symbols (1)")), "{notes:?}"); +} + +#[test] +fn unread_group_uses_page_opacity_once() { + let symbol = format!("%AI14_BeginSymbol\n(Dot) 0 Ae\n{}\n%AI10_EndSymbol\n", square(0, 0)); + let instance = "/SymbolInstance :\n(Dot) /SymbolRef ,\n[1 0 0 1 50 10] /Matrix ,\n;"; + let group = format!("0 Ae\nu\n{instance}\nU\n0 0.5 0 0 0 Xy\n0 0 Xd\n6 () XW"); + let art = native(&(symbol + &layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &group))); + let mut page = pdf_two_squares(); + let id = page.layers[0].children().unwrap()[1].id; + page.node_mut(id).unwrap().opacity = 0.5; + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Live", "Mixed"]); + let replacement = &doc.layers[1].children().unwrap()[0]; + assert_eq!(replacement.opacity, 1.0); + assert_eq!(replacement.children().unwrap()[0].opacity, 0.5); + let rendered = vectorcraft_render::Renderer::new().render_region(&doc, vectorcraft_geom::Rect::new(50.0, 86.0, 54.0, 90.0), 4.0, false); + let pixel = rendered.pixels.as_chunks::<4>().0.get(8 * rendered.width as usize + 8).unwrap(); + assert!((120..=136).contains(&pixel[3]), "the final document draws the group at 50% once: {pixel:?}"); +} + +#[test] +fn unread_group_with_unidentified_transparency_uses_page_document() { + let symbol = format!("%AI14_BeginSymbol\n(Dot) 0 Ae\n{}\n%AI10_EndSymbol\n", square(0, 0)); + let instance = "/SymbolInstance :\n(Dot) /SymbolRef ,\n[1 0 0 1 50 10] /Matrix ,\n;"; + let group = format!("0 Ae\nu\n{instance}\nU\n0 0.5 0 0 0 Xy\n0 0 Xd\n6 () XW"); + let art = native(&(symbol + &layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &group))); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_two_squares(), vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(notes.iter().any(|n| n.contains("appearance is not identifiable")), "{notes:?}"); +} + +#[test] +fn group_with_only_placed_file_without_preview_uses_page_art() { + let placed = "%AI5_BeginPlace\n[1 0 0 1 0 0] 50 10 54 14 (missing) `\n~\n%AI5_EndPlace"; + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &os1_group(placed)))); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_two_squares(), vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Live", "Mixed"]); + assert_eq!(kinds(&doc.layers[1]), ["group[1]"]); + replacement_is_cyan(&doc, 1, 0); + assert!(notes.iter().any(|n| n.contains("placed files (1)")), "{notes:?}"); +} + +#[test] +fn top_level_pattern_uses_page_art_beside_live_path() { + let body = format!("(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}\n{}", square_path(50, 10), square(70, 10)); + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &body))); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_three_squares(), vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Live", "Mixed"]); + assert_eq!(kinds(&doc.layers[1]), ["group[1]", "path"]); + replacement_is_cyan(&doc, 1, 0); + assert!(notes.iter().any(|n| n.contains("pattern fills (1)")), "{notes:?}"); +} + +#[test] +fn pattern_set_in_plain_group_replaces_later_sibling_from_page_art() { + let group = os1_group(&format!("(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}", square_path(50, 10))); + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &format!("{group}\n{}", square_path(70, 10))))); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_three_squares(), vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Live", "Mixed"]); + assert_eq!(kinds(&doc.layers[1]), ["group[1]", "group[1]"]); + replacement_is_cyan(&doc, 1, 0); + assert!(notes.iter().any(|n| n.contains("pattern fills (2)")), "{notes:?}"); +} + +#[test] +fn top_level_placed_file_without_preview_uses_page_art() { + let placed = "%AI5_BeginPlace\n[1 0 0 1 0 0] 50 10 54 14 (missing) `\n~\n%AI5_EndPlace"; + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &format!("{placed}\n{}", square(70, 10))))); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_three_squares(), vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Live", "Mixed"]); + assert_eq!(kinds(&doc.layers[1]), ["group[1]", "path"]); + replacement_is_cyan(&doc, 1, 0); + assert!(notes.iter().any(|n| n.contains("placed files (1)")), "{notes:?}"); +} + +#[test] +fn nested_previewless_placed_file_at_box_corner_falls_back() { + let place = "%AI5_BeginPlace\n[1 0 0 -1 -7970 8070] 8000 8000 8040 8040 4 4 0\n(missing.png)`\n~\n%AI5_EndPlace"; + let art = native(&layer("Placed", true, &os1_group(place))).replace("%AI5_NumLayers", "%AI3_TemplateBox: 100 50 100 50\n%AI5_NumLayers"); + let mut page = Document::new(100.0, 100.0); + let id = page.alloc_id(); + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(30.0, 30.0, 70.0, 70.0)); + let fill = vectorcraft_doc::FillLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::gray(0.5))); + page.insert( + Some(page.layers[0].id), + 0, + Node::path(id, path, vectorcraft_doc::Appearance { items: vec![vectorcraft_doc::AppearanceItem::Fill(fill)], ..Default::default() }), + ) + .unwrap(); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(!read, "a nested placeholder has no group-wide corner alternative: {notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); +} + +#[test] +fn group_with_previewless_placed_file_and_readable_sibling_keeps_sibling() { + let place = "%AI5_BeginPlace\n[1 0 0 -1 -7970 8070] 8000 8000 8040 8040 4 4 0\n(missing.png)`\n~\n%AI5_EndPlace"; + let group = os1_group(&format!("{place}\n{}", square(70, 10))); + let art = native(&layer("Mixed", true, &group)).replace("%AI5_NumLayers", "%AI3_TemplateBox: 100 50 100 50\n%AI5_NumLayers"); + let mut page = pdf_part(70.0, 86.0); + let id = page.alloc_id(); + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(30.0, 30.0, 70.0, 70.0)); + let fill = vectorcraft_doc::FillLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::gray(0.5))); + page.insert( + Some(page.layers[0].id), + 1, + Node::path(id, path, vectorcraft_doc::Appearance { items: vec![vectorcraft_doc::AppearanceItem::Fill(fill)], ..Default::default() }), + ) + .unwrap(); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + if read { + let mixed = doc.layers.iter().find(|layer| layer.name.as_deref() == Some("Mixed")).unwrap(); + assert!( + mixed.children().unwrap().iter().any(|child| { + child.children().is_some_and(|children| children.iter().any(|n| n.geometric_bounds().is_some_and(|b| b.x0 == 70.0))) + }), + "readable sibling was dropped: {notes:?}" + ); + } else { + assert_eq!(names(&doc), ["Layer 1"], "{notes:?}"); + } +} + +#[test] +fn previewless_placed_file_tries_corner_when_first_box_contains_live_art() { + let place = "%AI5_BeginPlace\n[1 0 0 -1 -7970 8070] 8000 8000 8040 8040 4 4 0\n(missing.png)`\n~\n%AI5_EndPlace"; + let live = "0 0 1 0 k\n130 -180 m\n134 -180 L\n134 -184 L\n130 -184 L\nf"; + let art = native(&(layer("Live", true, live) + &layer("Placed", true, place))) + .replace("%AI5_NumLayers", "%AI3_TemplateBox: 100 50 100 50\n%AI5_NumLayers"); + let mut page = Document::new(100.0, 100.0); + let id = page.alloc_id(); + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(30.0, 30.0, 70.0, 70.0)); + let fill = vectorcraft_doc::FillLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::gray(0.5))); + page.insert( + Some(page.layers[0].id), + 0, + Node::path(id, path, vectorcraft_doc::Appearance { items: vec![vectorcraft_doc::AppearanceItem::Fill(fill)], ..Default::default() }), + ) + .unwrap(); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Live", "Placed"]); + assert_eq!(kinds(&doc.layers[0]), ["path"]); + assert_eq!(kinds(&doc.layers[1]), ["group[1]"]); + assert!(notes.iter().any(|note| note.contains("placed files (1)")), "{notes:?}"); +} + +#[test] +fn replaced_page_art_reids_opacity_mask_art() { + let place = "%AI5_BeginPlace\n[1 0 0 1 0 0] 50 10 54 14 (missing) `\n~\n%AI5_EndPlace"; + let art = native(&layer("Placed", true, place)); + let mut page = pdf_part(50.0, 86.0); + let page_node_id = page.layers[0].children().unwrap()[0].id; + let mask_id = page.alloc_id(); + let mask_path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(50.0, 86.0, 54.0, 90.0)); + let mask_fill = vectorcraft_doc::FillLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE)); + let mask_art = Node::path( + mask_id, + mask_path, + vectorcraft_doc::Appearance { items: vec![vectorcraft_doc::AppearanceItem::Fill(mask_fill)], ..Default::default() }, + ); + page.node_mut(page_node_id).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(mask_art, true))); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + let replacement = &doc.layers[0].children().unwrap()[0].children().unwrap()[0]; + let mask = replacement.extras().mask.as_ref().unwrap(); + assert_ne!(mask.art.id, mask_id); + assert_ne!(mask.art.id, replacement.id); + assert!(mask.art.id.0 < doc.peek_next_id()); +} + +#[test] +fn top_level_placed_file_replacement_keeps_page_image_data() { + use vectorcraft_doc::{ImageBlob, ImageObject}; + + let placed = "%AI5_BeginPlace\n[1 0 0 1 0 0] 50 10 54 14 (missing) `\n~\n%AI5_EndPlace"; + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Mixed", true, placed))); + let mut page = pdf_part(10.0, 86.0); + let pixels = image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 255, 255, 255])); + let mut png = Vec::new(); + pixels.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let blob = ImageBlob::new("image/png", png); + let key = blob.content_key(); + let expected = blob.bytes.clone(); + page.images.insert(key.clone(), blob); + let image = Node::new( + page.alloc_id(), + NodeKind::Image(Box::new(ImageObject { + key: key.clone(), + width: 4, + height: 4, + xf: vectorcraft_geom::Affine::translate(vectorcraft_geom::Vec2::new(50.0, 86.0)), + link: None, + placement: Default::default(), + pixels: None, + })), + ); + page.insert(Some(page.layers[0].id), 1, image).unwrap(); + + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Live", "Mixed"]); + let replacement = &doc.layers[1].children().unwrap()[0]; + let [image] = replacement.children().unwrap().as_slice() else { panic!("{replacement:?}") }; + let NodeKind::Image(im) = &image.kind else { panic!("{image:?}") }; + assert!(im.pixels.is_none(), "PDF-imported images use document data"); + assert_eq!(doc.images.get(&im.key).map(|blob| &blob.bytes), Some(&expected)); + assert!(notes.iter().any(|note| note.contains("placed files (1)")), "{notes:?}"); +} + +#[test] +fn top_level_pattern_replacement_keeps_gradient_stop_swatch() { + use vectorcraft_color::gradient::{GradientKind, GradientPaint, GradientStop}; + use vectorcraft_color::{Color, Gradient, Paint, Swatch}; + + let body = format!("(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}", square_path(50, 10)); + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &body))); + let mut page = pdf_two_squares(); + let cyan = Color::cmyk(1.0, 0.0, 0.0, 0.0); + page.swatches.push(Swatch { name: "Linked Cyan".into(), paint: Paint::solid(cyan), global: true, spot: false }); + let mut stop = GradientStop::new(0.0, cyan); + stop.swatch = Some("Linked Cyan".into()); + let gradient = Gradient::new(GradientKind::Linear, vec![stop, GradientStop::new(1.0, cyan)]); + let id = page.layers[0].children().unwrap()[1].id; + let node = page.node_mut(id).unwrap(); + node.appearance = vectorcraft_doc::Appearance { + items: vec![vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Gradient(Box::new(GradientPaint::new(gradient)))))], + ..Default::default() + } + .into(); + + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + let group = &doc.layers[1].children().unwrap()[0]; + let replacement = &group.children().unwrap()[0]; + assert!(matches!(replacement.appearance.fill().map(|f| &f.paint), Some(Paint::Gradient(g)) + if g.gradient.stops[0].swatch.as_deref() == Some("Linked Cyan"))); + assert!(matches!(doc.swatch("Linked Cyan"), Some(s) if s.global && s.paint == Paint::solid(cyan))); +} + +/// Two independently imported copies of the same tile have different node IDs. +fn page_with_named_pattern(native_art: &str, different: bool) -> Document { + use vectorcraft_color::Paint; + + let (editing, _) = crate::ai_alone(&private(&native_art.replace("(Absent)", "(Dots)"))).unwrap(); + let source = editing.pattern("Dots").unwrap(); + let mut page = pdf_two_squares(); + let mut pattern = source.clone(); + pattern.art = source.art.iter().map(|node| std::sync::Arc::new(page.reid(node))).collect(); + if different { + pattern.tile.x1 += 1.0; + } + page.patterns.push(pattern); + let id = page.layers[0].children().unwrap()[1].id; + let node = page.node_mut(id).unwrap(); + node.appearance = vectorcraft_doc::Appearance { + items: vec![vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Pattern { + pattern: "Dots".into(), + xf: vectorcraft_geom::Affine::IDENTITY, + }))], + ..Default::default() + } + .into(); + page +} + +fn named_pattern_replacement_art() -> String { + let dots = "%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_0 0 0 1 k\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n"; + let unread = format!("(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}", square_path(50, 10)); + native(&format!("{dots}{}{}", layer("Live", true, &square(10, 10)), layer("Mixed", true, &unread))) +} + +#[test] +fn same_named_pattern_in_page_art_keeps_editing_layers() { + let art = named_pattern_replacement_art(); + let page = page_with_named_pattern(&art, false); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Live", "Mixed"]); + assert_eq!(doc.patterns.iter().filter(|p| p.name == "Dots").count(), 1); + let replacement = &doc.layers[1].children().unwrap()[0].children().unwrap()[0]; + assert!(matches!(replacement.appearance.fill().map(|f| &f.paint), Some(vectorcraft_color::Paint::Pattern { pattern, .. }) if pattern == "Dots")); +} + +#[test] +fn copied_page_pattern_reids_its_mask_art() { + let source_art = named_pattern_replacement_art(); + let mut page = page_with_named_pattern(&source_art, false); + let mask_id = page.alloc_id(); + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 4.0, 4.0)); + let fill = vectorcraft_doc::FillLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE)); + let mask_art = + Node::path(mask_id, path, vectorcraft_doc::Appearance { items: vec![vectorcraft_doc::AppearanceItem::Fill(fill)], ..Default::default() }); + std::sync::Arc::make_mut(&mut page.patterns[0].art[0]).extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(mask_art, true))); + let art = native(&format!( + "{}{}", + layer("Live", true, &square(10, 10)), + layer("Mixed", true, &format!("(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}", square_path(50, 10))) + )); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + let mask = doc.pattern("Dots").unwrap().art[0].extras().mask.as_ref().unwrap(); + assert_ne!(mask.art.id, mask_id); + assert!(mask.art.id.0 < doc.peek_next_id()); +} + +#[test] +fn different_named_pattern_in_page_art_falls_back() { + let art = named_pattern_replacement_art(); + let page = page_with_named_pattern(&art, true); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(notes.iter().any(|n| n.contains("page art conflicts with pattern Dots")), "{notes:?}"); +} + +#[test] +fn partly_overlapping_page_art_does_not_replace_an_object() { + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &os1_group(&format!("{}\nZZ", square(50, 10)))))); + let mut page = pdf_part(10.0, 86.0); + let other = pdf_part(48.0, 86.0); + let id = page.layers[0].id; + let square = page.reid(&other.layers[0].children().unwrap()[0]); + page.insert(Some(id), 1, square).unwrap(); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(notes.iter().any(|n| n.contains("page art wasn't found")), "{notes:?}"); +} + +/// Page art for the unread square and its neighbor under one PDF group. +fn grouped_page_across_unread_and_neighbor(clipped: bool) -> Document { + let mut page = pdf_two_squares(); + let layer = page.layers[0].id; + let unread = page.remove(page.layers[0].children().unwrap()[1].id).unwrap(); + let other = pdf_part(70.0, 86.0); + let neighbor = page.reid(&other.layers[0].children().unwrap()[0]); + let mut children = Vec::new(); + if clipped { + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(50.0, 86.0, 74.0, 90.0)); + let mut clip = Node::path(page.alloc_id(), path, vectorcraft_doc::Appearance::default()); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + children.push(std::sync::Arc::new(clip)); + } + children.extend([unread, std::sync::Arc::new(neighbor)]); + let mut group = Node::group(page.alloc_id(), children); + group.set_clips(clipped); + page.insert(Some(layer), 1, group).unwrap(); + page +} + +#[test] +fn clipped_pdf_group_across_unread_and_neighbor_falls_back() { + let body = format!("{}\n{}", os1_group(&format!("{}\nZZ", square(50, 10))), square(70, 10)); + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &body))); + let (doc, notes, read) = crate::layered_ai(&private(&art), grouped_page_across_unread_and_neighbor(true), vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(notes.iter().any(|n| n.contains("clipping or appearance ancestor")), "{notes:?}"); +} + +#[test] +fn plain_pdf_group_across_unread_and_neighbor_uses_child() { + let body = format!("{}\n{}", os1_group(&format!("{}\nZZ", square(50, 10))), square(70, 10)); + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &body))); + let (doc, notes, read) = crate::layered_ai(&private(&art), grouped_page_across_unread_and_neighbor(false), vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Live", "Mixed"]); + replacement_is_cyan(&doc, 1, 0); + assert!(notes.iter().any(|n| n.contains("`ZZ` (1)")), "{notes:?}"); +} + +#[test] +fn live_art_inside_unread_bounds_falls_back_instead_of_drawing_twice() { + let body = format!("{}\n{}", os1_group(&format!("{}\nZZ", square(50, 10))), "0 0 1 0 k\n51 11 m\n53 11 L\n53 13 L\n51 13 L\nf"); + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &body))); + let mut page = pdf_two_squares(); + let inner = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(51.0, 87.0, 53.0, 89.0)); + let appearance = (*page.layers[0].children().unwrap()[0].appearance).clone(); + let node = Node::path(page.alloc_id(), inner, appearance); + let layer_id = page.layers[0].id; + page.insert(Some(layer_id), 2, node).unwrap(); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(notes.iter().any(|n| n.contains("bounds also contain live art")), "{notes:?}"); +} + +#[test] +fn live_art_crossing_unread_bounds_by_half_a_point_falls_back() { + let neighbor = "0 0 1 0 k\n53.5 11 m\n54.5 11 L\n54.5 13 L\n53.5 13 L\nf"; + let art = native(&layer("Mixed", true, &format!("{}\n{neighbor}", os1_group(&format!("{}\nZZ", square(50, 10)))))); + let mut page = pdf_part(50.0, 86.0); + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(53.5, 87.0, 54.5, 89.0)); + let appearance = (*page.layers[0].children().unwrap()[0].appearance).clone(); + let node = Node::path(page.alloc_id(), path, appearance); + let layer = page.layers[0].id; + page.insert(Some(layer), 1, node).unwrap(); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(notes.iter().any(|n| n.contains("bounds also contain live art")), "{notes:?}"); +} + +#[test] +fn overlapping_unread_objects_cannot_claim_the_same_page_art() { + let first = os1_group(&format!("{}\nZZ", square(50, 10))); + let second = os1_group(&format!("{}\nZZ", square(52, 10))); + let art = native(&layer("Mixed", true, &format!("{first}\n{second}"))); + let mut page = pdf_part(52.0, 86.0); + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(52.0, 86.0, 54.0, 90.0)); + let node = page.layers[0].children().unwrap()[0].as_ref().clone(); + let layer = page.layers[0].id; + page.remove(node.id).unwrap(); + let replacement = Node::path(page.alloc_id(), path, (*node.appearance).clone()); + page.insert(Some(layer), 0, replacement).unwrap(); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(notes.iter().any(|n| n.contains("more than one unread object")), "{notes:?}"); +} + +#[test] +fn top_level_pattern_without_page_art_falls_back() { + let body = format!("(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}", square_path(50, 10)); + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &body))); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_part(10.0, 86.0), vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(notes.iter().any(|n| n.contains("page art wasn't found")), "{notes:?}"); +} + +#[test] +fn top_level_placed_file_without_page_art_falls_back() { + let placed = "%AI5_BeginPlace\n[1 0 0 1 0 0] 50 10 54 14 (missing) `\n~\n%AI5_EndPlace"; + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Mixed", true, placed))); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_part(10.0, 86.0), vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(notes.iter().any(|n| n.contains("page art wasn't found")), "{notes:?}"); +} + +#[test] +fn unread_object_on_second_artboard_takes_second_page_art() { + let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ + %_/Dictionary :\n%_0 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_/Dictionary :\n%_0 -50 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 -150 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; + let second = "u\n0 0 1 0 k\n50 -100 m\n54 -100 L\n54 -96 L\n50 -96 L\nf\nZZ\nU"; + let art = native(&(boards.to_string() + &layer("Live", true, &square(10, 10)) + &layer("Mixed", true, second))); + let mut page = pdf_part(10.0, 86.0); + let mut board = page.artboards[0].clone(); + (board.id, board.rect) = (2, vectorcraft_geom::Rect::new(120.0, 0.0, 220.0, 100.0)); + page.artboards.push(board); + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(170.0, 46.0, 174.0, 50.0)); + let paint = vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0)); + let appearance = vectorcraft_doc::Appearance { + items: vec![vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(paint))], + ..Default::default() + }; + let node = Node::path(page.alloc_id(), path, appearance); + let layer = page.layers[0].id; + page.insert(Some(layer), 1, node).unwrap(); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Live", "Mixed"]); + replacement_is_cyan(&doc, 1, 0); + let bounds = doc.layers[1].children().unwrap()[0].visual_bounds().unwrap(); + assert_eq!(bounds, vectorcraft_geom::Rect::new(50.0, 196.0, 54.0, 200.0)); +} + +#[test] +fn unknown_operator_between_objects_falls_back() { + let body = format!("{}\nZZ\n{}", square(50, 10), square(70, 10)); + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &body))); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_three_squares(), vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(notes.iter().any(|n| n.contains("`ZZ`")), "{notes:?}"); +} + +#[test] +fn unread_object_without_page_art_names_what_is_unread() { + let art = native(&layer("Mixed", true, &os1_group(&format!("{}\nZZ", square(50, 10))))); + let e = crate::ai_alone(&private(&art)).unwrap_err(); + assert_eq!(e, "it has operators VectorCraft doesn't know (`ZZ`), which VectorCraft doesn't read from it yet"); + let pattern = os1_group(&format!("(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}", square_path(70, 10))); + let art = native(&layer("Mixed", true, &format!("{}\n{pattern}", os1_group(&format!("{}\nZZ", square(50, 10)))))); + let e = crate::ai_alone(&private(&art)).unwrap_err(); + assert_eq!(e, "it has operators VectorCraft doesn't know (`ZZ`) and pattern fills, which VectorCraft doesn't read from it yet"); +} + +#[test] +fn unread_pattern_inside_one_object_uses_page_art_and_keeps_layers() { + let art = native( + &(layer("Live", true, &square(10, 10)) + + &layer( + "Mixed", + true, + &format!("{}\n{}", os1_group(&format!("(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}", square_path(50, 10))), square(70, 10)), + )), + ); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_three_squares(), vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Live", "Mixed"]); + assert_eq!(kinds(&doc.layers[0]), ["path"]); + assert_eq!(kinds(&doc.layers[1]), ["group[1]", "path"]); + replacement_is_cyan(&doc, 1, 0); + assert!(notes.iter().any(|n| n.contains("pattern fills (1)") && n.contains("page's art")), "{notes:?}"); +} + +#[test] +fn unknown_operator_inside_group_uses_page_art() { + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &os1_group(&format!("{}\nZZ", square(50, 10)))))); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_split_square(), vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Live", "Mixed"]); + assert_eq!(kinds(&doc.layers[1]), ["group[2]"]); + replacement_has_two_halves(&doc); + assert!(notes.iter().any(|n| n.contains("`ZZ` (1)")), "{notes:?}"); +} + +#[test] +fn unread_object_on_hidden_layer_stays_left_out() { + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Hidden", false, &os1_group(&format!("{}\nZZ", square(50, 10)))))); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_part(10.0, 86.0), vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Live", "Hidden"]); + assert!(notes.iter().any(|n| n.contains("left out of them")), "{notes:?}"); +} + +#[test] +fn unread_object_without_page_art_falls_back() { + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &os1_group(&format!("{}\nZZ", square(50, 10)))))); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_part(10.0, 86.0), vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(notes.iter().any(|n| n.contains("page art wasn't found")), "{notes:?}"); +} + +#[test] +fn unclosed_unread_group_falls_back() { + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &format!("u\n{}\nZZ", square(50, 10))))); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_two_squares(), vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(notes.iter().any(|n| n.contains("closes something it didn't open")), "{notes:?}"); +} + +#[test] +fn eps_unread_group_uses_printed_page_art() { + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Mixed", true, &os1_group(&format!("{}\nZZ", square(50, 10)))))); + let page = format!( + "{}\n1 0 0 0 setcmykcolor 50 10 moveto 52 10 lineto 52 14 lineto 50 14 lineto closepath fill\n0 1 0 0 setcmykcolor 52 10 moveto 54 10 lineto 54 14 lineto 52 14 lineto closepath fill", + page_square(10, 10) + ); + let result = import(&eps(&page, &art)).unwrap(); + assert_eq!(names(&result.document), ["Live", "Mixed"], "{:?}", result.warnings); + replacement_has_two_halves(&result.document); + assert!(result.warnings.iter().any(|n| n.contains("`ZZ` (1)")), "{:?}", result.warnings); +} + /// The PDF part `d` as read in points from pages of `k` points a unit (their `UserUnit`): its /// pages and art `k` times as large. fn in_points(mut d: Document, k: f64) -> Document { @@ -1992,6 +2657,61 @@ fn threaded_area_type_flows_through_its_frames() { assert_eq!(r.document.text_threads, [ids]); } +/// Replacing a group containing either threaded frame must use the PDF page instead. +#[test] +fn unread_group_holding_threaded_frame_falls_back() { + let frames = [ + format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(50.0, 10.0, 54.0, 14.0)), + format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(70.0, 10.0, 74.0, 14.0)), + ]; + let text = document_of(&frames, &[story("Threaded\\r", &[0, 1], "/0 0", "/1 10.0")]); + for removed in [0, 1] { + let grouped = os1_group(&format!("{}\n{}\nZZ", square(if removed == 0 { 50 } else { 70 }, 10), frame_object(0, removed))); + let other = frame_object(0, 1 - removed); + let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Mixed", true, &format!("{grouped}\n{other}"))), &text); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_three_squares(), vec![], false, true, 1.0); + assert!(!read, "removed frame {removed}: {notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); + assert!(notes.iter().any(|n| n.contains("an unread object holds a frame of threaded type")), "removed frame {removed}: {notes:?}"); + } +} + +/// Replacing an unread group may still discard a single-frame text object. +#[test] +fn unread_group_holding_single_frame_uses_page_art() { + let frame = format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(50.0, 10.0, 54.0, 14.0)); + let text = document_of(&[frame], &[story("Single\\r", &[0], "/0 0", "/1 10.0")]); + let grouped = os1_group(&format!("{}\n{}\nZZ", square(50, 10), frame_object(0, 0))); + let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Mixed", true, &grouped)), &text); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_two_squares(), vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + assert_eq!(names(&doc), ["Back", "Mixed"]); + assert!(doc.text_threads.is_empty()); +} + +/// The page's type inside an unread object's box comes in once, with the page's art that replaces +/// the object, whether every text object's type is made from the text document or not. +#[test] +fn page_type_inside_an_unread_object_comes_in_with_its_page_art() { + let unread = os1_group("0 0 1 0 k\n20 10 m\n50 10 L\n50 30 L\n20 30 L\nf\nZZ"); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show \ + 1 0 0 0 setcmykcolor 20 10 moveto 50 10 lineto 50 30 lineto 20 30 lineto closepath fill \ + 0 0 0 1 setcmykcolor /Helvetica findfont 8 scalefont setfont 22 14 moveto (Ex) show"; + let made = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let unmade = + last_frame_unread(&text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Note\r", 0, (8200.0, 8120.0), (0.0, 0.0), 0.0)])); + for (doc, objects) in [(made, text_object(0)), (unmade, text_object(0) + &text_object(1))] { + let art = native_with_text(&(layer("Words", true, &objects) + &layer("Mixed", true, &unread)), &doc); + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Words", "Mixed"], "{:?}", r.warnings); + let mut texts = all_texts(&r.document); + texts.retain(|t| !t.is_empty()); + assert_eq!(texts, ["Hi there", "Ex"], "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.starts_with("some of the page's type")), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("`ZZ` (1)")), "{:?}", r.warnings); + } +} + #[test] fn shown_type_the_page_draws_in_pieces_comes_whole_from_the_text_document() { // Type on a path the page draws letter by letter: the letters lie on the path, and only the diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index f69921d5d3..00d07dcbe4 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5935,6 +5935,9 @@ breakText Glyphs Глифи Gap 4 Разстояние 4 Dash 5 Тире 5 Gap 5 Разстояние 5 + +@msg {_1}: they came in as the page's art {_1}: те са внесени като изображението от страницата + @msg You must choose a side pattern. Трябва да изберете страничен шаблон. @msg invalid pattern tile choice невалиден избор на плочка за шаблон @msg no pattern named `{choice}` няма шаблон с име `{choice}` diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9048560989..b49ece9ce7 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5968,6 +5968,8 @@ shape Open Otvoren @msg `follow` must be "average", "a" or "b" `follow` mora biti "average", "a" ili "b" @msg the paths have nothing to merge there putanje tu nemaju šta spojiti @msg the path is locked or hidden putanja je zaključana ili skrivena +@msg {_1}: they came in as the page's art {_1}: uvezeni su kao ilustracija stranice + @msg You must choose a side pattern. Morate odabrati bočni uzorak. @msg invalid pattern tile choice nevažeći izbor pločice uzorka @msg no pattern named `{choice}` nema uzorka pod nazivom `{choice}` diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 2eadca7c13..5509d3eaf2 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6039,6 +6039,9 @@ breakText Glyphs Glifs Gap 4 Separació 4 Dash 5 Guió 5 Gap 5 Separació 5 + +@msg {_1}: they came in as the page's art {_1}: han entrat com a art de la pàgina + @msg the JPEG 2000 file can't be read no es pot llegir el fitxer JPEG 2000 @msg the JPEG 2000 file has an unsupported color space or JPX content el fitxer JPEG 2000 té un espai de color o contingut JPX no compatible @msg You must choose a side pattern. Heu de triar un patró lateral. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index d45c83723a..6546f97ec4 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6051,6 +6051,9 @@ breakText Glyphs Glyfy Gap 4 Mezera 4 Dash 5 Čárka 5 Gap 5 Mezera 5 + +@msg {_1}: they came in as the page's art {_1}: byly načteny jako kresba ze stránky + @msg You must choose a side pattern. Musíte zvolit boční vzorek. @msg invalid pattern tile choice neplatná volba dlaždice vzorku @msg no pattern named `{choice}` vzorek s názvem `{choice}` neexistuje diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 74d5e43d6d..6ef8a029ae 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5950,6 +5950,9 @@ breakText Glyphs Glyffer Gap 4 Mellemrum 4 Dash 5 Streg 5 Gap 5 Mellemrum 5 + +@msg {_1}: they came in as the page's art {_1}: de blev importeret som sidens grafik + @msg You must choose a side pattern. Du skal vælge et sidemønster. @msg invalid pattern tile choice ugyldigt valg af mønsterflise @msg no pattern named `{choice}` intet mønster med navnet `{choice}` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index f1e17a4d33..c4d3b973d6 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5636,6 +5636,9 @@ breakText Glyphs Glyphen Gap 4 Lücke 4 Dash 5 Strich 5 Gap 5 Lücke 5 + +@msg {_1}: they came in as the page's art {_1}: sie wurden als Seitengrafik importiert + @msg You must choose a side pattern. Sie müssen ein Seitenmuster auswählen. @msg invalid pattern tile choice ungültige Auswahl einer Musterkachel @msg no pattern named `{choice}` kein Muster mit dem Namen `{choice}` diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 9c046d74f3..89e694f673 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6003,6 +6003,9 @@ breakText Glyphs Γλύφοι Gap 4 Διάκενο 4 Dash 5 Παύλα 5 Gap 5 Διάκενο 5 + +@msg {_1}: they came in as the page's art {_1}: εισήχθησαν ως γραφικά της σελίδας + @msg You must choose a side pattern. Πρέπει να επιλέξετε πλευρικό μοτίβο. @msg invalid pattern tile choice μη έγκυρη επιλογή πλακιδίου μοτίβου @msg no pattern named `{choice}` δεν υπάρχει μοτίβο με όνομα `{choice}` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index eaa3f66d70..f4ada77f1f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5993,6 +5993,9 @@ breakText Glyphs Glifos Gap 4 Hueco 4 Dash 5 Guion 5 Gap 5 Hueco 5 + +@msg {_1}: they came in as the page's art {_1}: se importaron como el arte de la página + @msg You must choose a side pattern. Debe elegir un motivo lateral. @msg invalid pattern tile choice selección de mosaico de motivo no válida @msg no pattern named `{choice}` no hay ningún motivo llamado `{choice}` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4c7a87740..1161c73de2 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6081,6 +6081,9 @@ breakText Glyphs Merkit Gap 4 Väli 4 Dash 5 Viiva 5 Gap 5 Väli 5 + +@msg {_1}: they came in as the page's art {_1}: ne tuotiin sivun piirroksena + @msg You must choose a side pattern. Valitse sivukuvio. @msg invalid pattern tile choice virheellinen kuviolaatan valinta @msg no pattern named `{choice}` kuviota nimeltä `{choice}` ei löydy diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 774b000ba6..e12387e1d9 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6048,6 +6048,9 @@ breakText Glyphs Glyphes Gap 4 Écart 4 Dash 5 Tiret 5 Gap 5 Écart 5 + +@msg {_1}: they came in as the page's art {_1} : ils ont été importés comme le dessin de la page + @msg You must choose a side pattern. Vous devez choisir un motif latéral. @msg invalid pattern tile choice choix de tuile de motif non valide @msg no pattern named `{choice}` aucun motif nommé `{choice}` diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 46bb0c9917..c6fcdcb49f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6037,6 +6037,9 @@ breakText Glyphs Glifák Gap 4 Hézag 4 Dash 5 Vonal 5 Gap 5 Hézag 5 + +@msg {_1}: they came in as the page's art {_1}: az oldal rajzaként lettek importálva + @msg You must choose a side pattern. Válasszon oldalsó mintát. @msg invalid pattern tile choice érvénytelen mintacsempe-választás @msg no pattern named `{choice}` nincs `{choice}` nevű minta diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 8e87dd93a0..9ed018f08c 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5950,6 +5950,9 @@ breakText Glyphs Glif Gap 4 Jarak 4 Dash 5 Garis 5 Gap 5 Jarak 5 + +@msg {_1}: they came in as the page's art {_1}: diimpor sebagai gambar halaman + @msg You must choose a side pattern. Anda harus memilih pola sisi. @msg invalid pattern tile choice pilihan ubin pola tidak valid @msg no pattern named `{choice}` tidak ada pola bernama `{choice}` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 2cf4742605..669a0e3c3a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5670,6 +5670,9 @@ breakText Glyphs Glifi Gap 4 Spazio 4 Dash 5 Tratto 5 Gap 5 Spazio 5 + +@msg {_1}: they came in as the page's art {_1}: sono stati importati come elementi grafici della pagina + @msg You must choose a side pattern. Devi scegliere un motivo laterale. @msg invalid pattern tile choice scelta della tessera motivo non valida @msg no pattern named `{choice}` nessun motivo chiamato `{choice}` diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 8cdb79a678..0a05ba0b90 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5737,6 +5737,9 @@ breakText Glyphs 字形 Gap 4 間隔 4 Dash 5 線分 5 Gap 5 間隔 5 + +@msg {_1}: they came in as the page's art {_1}: ページのアートとして読み込みました + @msg You must choose a side pattern. 側面パターンを選択してください。 @msg invalid pattern tile choice パターンタイルの選択が無効です @msg no pattern named `{choice}` `{choice}` というパターンはありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 22894ea3b1..dcfc8a20f1 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6040,6 +6040,9 @@ breakText Glyphs გლიფები Gap 4 შუალედი 4 Dash 5 ტირე 5 Gap 5 შუალედი 5 + +@msg {_1}: they came in as the page's art {_1}: იმპორტირებულია გვერდის გამოსახულების სახით + @msg You must choose a side pattern. აირჩიეთ გვერდითი ნიმუში. @msg invalid pattern tile choice ნიმუშის ფილა არასწორად არის არჩეული @msg no pattern named `{choice}` ნიმუში სახელით `{choice}` არ არსებობს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 9c9d8dbd32..1b7190a41c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5633,6 +5633,9 @@ breakText Glyphs 글리프 Gap 4 간격 4 Dash 5 대시 5 Gap 5 간격 5 + +@msg {_1}: they came in as the page's art {_1}: 페이지의 아트로 가져왔습니다 + @msg You must choose a side pattern. 측면 패턴을 선택해야 합니다. @msg invalid pattern tile choice 잘못된 패턴 타일 선택 @msg no pattern named `{choice}` `{choice}` 이름의 패턴이 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 4918f150f7..7d137e3e72 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5994,6 +5994,9 @@ breakText Glyphs Glyphs Gap 4 Tussenruimte 4 Dash 5 Streepje 5 Gap 5 Tussenruimte 5 + +@msg {_1}: they came in as the page's art {_1}: ze zijn geïmporteerd als pagina-afbeelding + @msg You must choose a side pattern. Kies een zijpatroon. @msg invalid pattern tile choice ongeldige keuze voor patroontegel @msg no pattern named `{choice}` geen patroon met de naam `{choice}` diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8d9e8ba9da..810f51bdf8 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5906,6 +5906,9 @@ breakText Glyphs Glify Gap 4 Odstęp 4 Dash 5 Kreska 5 Gap 5 Odstęp 5 + +@msg {_1}: they came in as the page's art {_1}: zaimportowano je jako grafikę strony + @msg You must choose a side pattern. Musisz wybrać wzór boczny. @msg invalid pattern tile choice nieprawidłowy wybór kafelka wzoru @msg no pattern named `{choice}` nie ma wzoru o nazwie `{choice}` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index b7aaabd1d6..c5fe48efae 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5970,6 +5970,9 @@ breakText Glyphs Glifos Gap 4 Lacuna 4 Dash 5 Traço 5 Gap 5 Lacuna 5 + +@msg {_1}: they came in as the page's art {_1}: foram importados como arte da página + @msg You must choose a side pattern. Você deve escolher um padrão lateral. @msg invalid pattern tile choice escolha inválida de ladrilho de padrão @msg no pattern named `{choice}` não há padrão chamado `{choice}` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d9d95ae35e..dc410120f6 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6028,6 +6028,9 @@ breakText Glyphs Глифы Gap 4 Зазор 4 Dash 5 Штрих 5 Gap 5 Зазор 5 + +@msg {_1}: they came in as the page's art {_1}: импортированы как графика страницы + @msg You must choose a side pattern. Выберите боковой узор. @msg invalid pattern tile choice недопустимый выбор плитки узора @msg no pattern named `{choice}` узор с именем `{choice}` не найден diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e378d833fc..a9b8a41e75 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6103,6 +6103,9 @@ breakText Glyphs Glyfer Gap 4 Mellanrum 4 Dash 5 Streck 5 Gap 5 Mellanrum 5 + +@msg {_1}: they came in as the page's art {_1}: de importerades som sidans bild + @msg You must choose a side pattern. Du måste välja ett sidomönster. @msg invalid pattern tile choice ogiltigt val av mönsterplatta @msg no pattern named `{choice}` inget mönster med namnet `{choice}` diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 981f2a3ecb..379c377a2c 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6008,6 +6008,9 @@ breakText Glyphs Glifler Gap 4 Boşluk 4 Dash 5 Çizgi 5 Gap 5 Boşluk 5 + +@msg {_1}: they came in as the page's art {_1}: sayfanın çizimi olarak içe aktarıldılar + @msg You must choose a side pattern. Bir yan desen seçmelisiniz. @msg invalid pattern tile choice geçersiz desen döşemesi seçimi @msg no pattern named `{choice}` `{choice}` adlı desen yok diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 4b4bda6bc6..77eeeecc35 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5650,6 +5650,9 @@ breakText Glyphs Гліфи Gap 4 Проміжок 4 Dash 5 Штрих 5 Gap 5 Проміжок 5 + +@msg {_1}: they came in as the page's art {_1}: їх імпортовано як графіку сторінки + @msg You must choose a side pattern. Виберіть бічний візерунок. @msg invalid pattern tile choice недійсний вибір плитки візерунка @msg no pattern named `{choice}` візерунка з назвою `{choice}` немає diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 6b8c543302..a947f674d2 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5653,6 +5653,9 @@ breakText Glyphs Glyph Gap 4 Khoảng hở 4 Dash 5 Nét 5 Gap 5 Khoảng hở 5 + +@msg {_1}: they came in as the page's art {_1}: đã được nhập dưới dạng hình vẽ của trang + @msg You must choose a side pattern. Bạn phải chọn mẫu bên. @msg invalid pattern tile choice lựa chọn ô mẫu không hợp lệ @msg no pattern named `{choice}` không có mẫu tên `{choice}` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index a9d0563da0..3fd35f967f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5893,6 +5893,9 @@ breakText Glyphs 字形 Gap 4 间隔 4 Dash 5 虚线 5 Gap 5 间隔 5 + +@msg {_1}: they came in as the page's art {_1}:已作为页面图稿导入 + @msg You must choose a side pattern. 必须选择侧边图案。 @msg invalid pattern tile choice 图案拼块选项无效 @msg no pattern named `{choice}` 没有名为 `{choice}` 的图案 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index ceec87f9d6..cd01899a4e 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5690,6 +5690,9 @@ breakText Glyphs 字符 Gap 4 間隙 4 Dash 5 虛線 5 Gap 5 間隙 5 + +@msg {_1}: they came in as the page's art {_1}:已作為頁面圖稿匯入 + @msg You must choose a side pattern. 必須選擇側邊圖樣。 @msg invalid pattern tile choice 圖樣拼塊選項無效 @msg no pattern named `{choice}` 沒有名為 `{choice}` 的圖樣 diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index a3858ef8e5..2ca9181e3b 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -84,7 +84,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. ## Format by format diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c5588ef6d8..52c9258162 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1066,6 +1066,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A PDF page whose `UserUnit` (PDF 1.6) is above 1 opens at its size in points, its numbers times the `UserUnit` (one above 75,000 counts as 75,000), and `document.pdfInfo` gives its size and boxes in points too. A `.ai` whose editing data has its artboards in the units of such a page opens from that data at the page's size, with its layers, and when the layers can't be read its pages still take the artboard layout of the data, scaled the same way (part of #1482). When the editing data of a `.ai` or EPS is for a page of another size than the file's, the warning that its layers weren't read gives both sizes in points, and the scale of the editing data's page to the file's page (1:10 for a tenth of its size) when their sides are in proportion (#2034; `crates/eps/src/import/tests_native.rs`). A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). + A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); in PDF 1.3 to 1.5 files and PDF/X files such a page is written in points. Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). A `.ai` saved without PDF compatibility (its PDF part only a placeholder page) is placed and pasted from its editing data, as it opens: File › Place places the art of the layers that show on the first artboard (`file.place`'s `page` places another one), and Paste of it as PDF data (`clipboard.importPdf`) takes every object. `document.open` with `pages` naming every page of such a file opens it the same way (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). From 1e8ac2434cc7104c0be353a7c5df49ce7cbbe1a7 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sun, 1 Nov 2026 04:38:56 +0300 Subject: [PATCH 244/260] Fix #4920: Document Tools exports every open document addon.document.exportAllOpen {folder, format?} writes a copy of every open document to one folder as Save a Copy does, each named after its document with taken names numbered so no file is replaced. Documents keep their paths and modified state, the active one stays active, and a document that can't be written is reported while the others are still written. Object > Plug-ins > Document Tools gets Export All Open Documents as PDF and as SVG, which ask for the folder. --- crates/engine/src/cmd/addons/document.rs | 43 ++++++++++++++++++- .../engine/src/cmd/addons/document/tests.rs | 23 ++++++++++ crates/ui-egui/src/addons/document.rs | 26 ++++++++++- crates/ui-egui/src/addons/document/tests.rs | 41 ++++++++++++++++++ crates/ui-egui/src/menus/run.rs | 1 + docs/mcp.md | 12 ++++++ docs/target-app-parity.md | 5 +++ docs/ui-parity.md | 2 + 8 files changed, 151 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index 38aa8fab3c..faa02efc26 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -1,6 +1,7 @@ //! Document Tools (`addon.document.*`), a built-in add-on: Save a Timestamped Copy writes a copy of //! the document named with the date and time through File › Save a Copy's save; New Symbols from -//! Layers makes a symbol of each layer's art as New Symbol does. Its submenu (Object › Plug-ins › +//! Layers makes a symbol of each layer's art as New Symbol does; Export All Open Documents writes a +//! copy of every open document to one folder as Save a Copy does (#4920). Its submenu (Object › Plug-ins › //! Document Tools) is the UI's. #[cfg(test)] @@ -30,6 +31,15 @@ pub fn specs() -> Vec<CommandSpec> { has_clock, save_timestamped_copy ), + cmd!( + "addon.document.exportAllOpen", + "Export All Open Documents", + ["Object", "Plug-ins", "Document Tools"], + None, + "{folder, format?: vectorcraft|pdf|svg|svgz|ai|eps (default: pdf)} write a copy of every open document, in tab order, to `folder` as File › Save a Copy writes it, each named after its document (<name>.<ext>; -2, -3… added when that name is taken, so no file is replaced): every document keeps its path, title and modified state, and no undo step is made. A document that can't be written is listed in `failed` and the others are still written; the active document stays active → {files: [{title, path, warnings}], failed: [{title, error}], format}", + has_doc, + export_all_open + ), cmd!( "addon.document.symbolsFromLayers", "New Symbols from Layers", @@ -88,6 +98,37 @@ fn save_timestamped_copy(s: &mut Session, p: &Value) -> Result<Value> { fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id })) } +fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "addon.document.exportAllOpen"; + let format = fileio::save_format(Some(str_param(p, "format").unwrap_or("pdf")), None).map_err(|e| bad(C, e))?; + let folder = str_param(p, "folder").map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "give `folder`"))?.to_string(); + let ext = format.extensions.first().copied().ok_or_else(|| bad(C, "the format has no file extension"))?; + let (mut files, mut failed, mut written) = (vec![], vec![], Vec::<String>::new()); + let active = s.active; + for i in 0..s.docs.len() { + // Each document in turn is the one Save a Copy writes; switching tabs this way leaves every + // document's tool and interaction alone, and the active one comes back below. + s.active = Some(i); + let Ok(st) = s.doc() else { continue }; + let title = st.doc.title.clone(); + let stem = fileio::file_stem(st.path.as_deref().unwrap_or(&title)); + // Names the copies already took count as taken, as do files on disk. + let Some(path) = free_name(&folder, &stem, ext, |p| written.iter().any(|w| w == p) || std::path::Path::new(p).exists()) else { + failed.push(json!({ "title": title, "error": "every numbered name for the copy is taken" })); + continue; + }; + match fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id })) { + Ok(r) => { + written.push(path.clone()); + files.push(json!({ "title": title, "path": r.get("path").cloned().unwrap_or(json!(path)), "warnings": r.get("warnings").cloned().unwrap_or(json!([])) })); + } + Err(e) => failed.push(json!({ "title": title, "error": e.to_string() })), + } + } + s.active = active; + Ok(json!({ "files": files, "failed": failed, "format": format.id })) +} + /// `n` with each layer in it, and itself, made a group of the same art and clipping (a symbol holds /// no layers). fn without_layers(n: &Node) -> Node { diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index a67fcd5ae0..aef604eb36 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -194,3 +194,26 @@ fn the_layers_highlighted_in_the_layers_panel_are_the_default() { let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap(); assert_eq!((r["symbols"].clone(), r["skipped"].as_array().unwrap().len()), (json!(["Icons"]), 1)); } + +/// #4920: Export All Open Documents writes an SVG of each open document; a folder that can't be +/// written lists every document in `failed`, and either way the active document stays active. +#[test] +fn export_all_open_documents_writes_each_and_reports_failures() { + let dir = std::env::temp_dir().join(format!("vc-export-all-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "name": "one"})).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100, "name": "two"})).unwrap(); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + let r = s.execute("addon.document.exportAllOpen", &json!({"folder": dir, "format": "svg"})).unwrap(); + assert_eq!(r["files"].as_array().unwrap().len(), 2, "{r}"); + assert!(dir.join("one.svg").exists() && dir.join("two.svg").exists()); + assert_eq!(s.active_index(), Some(0)); + assert!(s.documents().iter().all(|d| d.path.is_none()), "the documents stay unsaved"); + let missing = dir.join("missing").join("deeper"); + let r = s.execute("addon.document.exportAllOpen", &json!({"folder": missing, "format": "svg"})).unwrap(); + assert_eq!((r["files"].as_array().unwrap().len(), r["failed"].as_array().unwrap().len()), (0, 2), "{r}"); + assert_eq!(s.active_index(), Some(0)); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/addons/document.rs b/crates/ui-egui/src/addons/document.rs index 47ea442f46..4d439c7233 100644 --- a/crates/ui-egui/src/addons/document.rs +++ b/crates/ui-egui/src/addons/document.rs @@ -1,7 +1,8 @@ //! Document Tools in the interface: its submenu (Object › Plug-ins › Document Tools), which runs //! Save a Timestamped Copy, New Symbols from Layers and Convert Layers to Symbols (the same, with //! each layer's art replaced by an instance). Save a Timestamped Copy of a document never saved -//! asks for the folder to put it in ([`save_copy`]). +//! asks for the folder to put it in ([`save_copy`]). Export All Open Documents as PDF or SVG asks +//! for the folder the copies go in ([`export_all`], #4920). use serde_json::{Value, json}; @@ -10,6 +11,8 @@ use crate::menus::Item; /// Save a Timestamped Copy. pub const SAVE_COPY: &str = "addon.document.saveTimestampedCopy"; +/// Export All Open Documents. +pub const EXPORT_ALL: &str = "addon.document.exportAllOpen"; /// New Symbols from Layers (Convert Layers to Symbols: with their art replaced by instances). const SYMBOLS: &str = "addon.document.symbolsFromLayers"; @@ -17,6 +20,8 @@ const SYMBOLS: &str = "addon.document.symbolsFromLayers"; pub fn menu() -> Vec<Item> { vec![ Item::Cmd("Save a Timestamped Copy", SAVE_COPY, json!({})), + Item::Cmd("Export All Open Documents as PDF", EXPORT_ALL, json!({ "format": "pdf" })), + Item::Cmd("Export All Open Documents as SVG", EXPORT_ALL, json!({ "format": "svg" })), Item::Sep, Item::Cmd("New Symbols from Layers", SYMBOLS, json!({})), Item::Cmd("Convert Layers to Symbols", SYMBOLS, json!({ "replace": true })), @@ -35,5 +40,24 @@ pub(crate) fn save_copy(app: &mut VectorcraftApp, p: &Value) -> Result<Value, St Ok(r) } +/// Export All Open Documents with params `p`: without a `folder`, the copies go in the folder +/// picked. The status bar says how many were written and names the first that failed. +pub(crate) fn export_all(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { + let mut p = if p.is_object() { p.clone() } else { json!({}) }; + if p.get("folder").is_none() { + p["folder"] = json!(crate::picks::folder(app).ok_or("cancelled")?); + } + let r = app.session.execute(EXPORT_ALL, &p).map_err(|e| e.to_string())?; + let written = r["files"].as_array().map_or(0, Vec::len); + let failed = r["failed"].as_array().cloned().unwrap_or_default(); + let mut status = crate::i18n::msg_n(written as u64, "Exported {n} document", "Exported {n} documents", &[]); + if let Some(f) = failed.first() { + let (title, error) = (f["title"].as_str().unwrap_or_default(), f["error"].as_str().unwrap_or_default()); + status = format!("{status}; {title} wasn't written: {error}"); + } + app.status(status); + Ok(r) +} + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/addons/document/tests.rs b/crates/ui-egui/src/addons/document/tests.rs index 5221c84147..4a2f96bd20 100644 --- a/crates/ui-egui/src/addons/document/tests.rs +++ b/crates/ui-egui/src/addons/document/tests.rs @@ -82,3 +82,44 @@ fn new_symbols_from_layers_and_convert_layers_to_symbols() { .all(|l| matches!(l.children().unwrap()[..], [ref one] if matches!(one.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. }))) ); } + +/// #4920: Export All Open Documents as PDF asks for a folder and writes one PDF per open document, +/// named after each, without replacing a file there, and leaves every document as it was. +#[test] +fn export_all_open_documents_writes_each_to_the_folder_picked() { + let dir = folder("export-all"); + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + app.run("document.save", json!({"path": dir.join("card.vectorcraft")})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100, "name": "card"})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let untitled = app.session.doc().unwrap().doc.title.clone(); + let out = dir.join("out"); + std::fs::create_dir_all(&out).unwrap(); + std::fs::write(out.join(format!("{untitled}.pdf")), b"keep").unwrap(); + let picked = out.to_string_lossy().into_owned(); + app.services.pick_folder = Some(Box::new(move || Some(picked.clone()))); + let active = app.session.active_index(); + click(&mut app, "Export All Open Documents as PDF"); + let mut names = files(&out); + names.sort(); + let mut want = vec!["card.pdf".to_string(), "card-2.pdf".into(), format!("{untitled}.pdf"), format!("{untitled}-2.pdf")]; + want.sort(); + assert_eq!(names, want, "one per document, the taken names numbered"); + assert_eq!(std::fs::read(out.join(format!("{untitled}.pdf"))).unwrap(), b"keep", "no file is replaced"); + assert!(std::fs::read(out.join("card.pdf")).unwrap().starts_with(b"%PDF")); + assert_eq!(app.session.active_index(), active, "the active document stays active"); + assert!( + app.session.documents().iter().all(|d| d.path.as_ref().is_none_or(|p| p.ends_with("card.vectorcraft"))), + "no document takes a copy's path" + ); + assert!(app.ui.status.starts_with("Exported 3 documents"), "{}", app.ui.status); + // Cancelled: nothing written. + app.services.pick_folder = Some(Box::new(|| None)); + assert_eq!(app.run(super::EXPORT_ALL, json!({})).unwrap_err(), "cancelled"); + assert_eq!(files(&out).len(), 4); + // The engine command refuses a missing folder and an unknown format. + assert!(app.session.execute(super::EXPORT_ALL, &json!({})).is_err()); + assert!(app.session.execute(super::EXPORT_ALL, &json!({"folder": out, "format": "doc"})).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 5da061cbe0..e7f80ecd81 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -531,6 +531,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result< crate::addons::pathtools::shared_edge::COMMAND => crate::addons::pathtools::shared_edge::open(app), crate::addons::arrange::ZOOM => crate::addons::arrange::zoom(app), crate::addons::document::SAVE_COPY => crate::addons::document::save_copy(app, p), + crate::addons::document::EXPORT_ALL => crate::addons::document::export_all(app, p), "tool.setOption" => app.session.set_tool_option_cmd(p), "effect.dialog" => crate::dialogs::open_effect_dialog(app, p), "ui.recolorDialog" => crate::dialogs::recolor::open(app, p), diff --git a/docs/mcp.md b/docs/mcp.md index b1ca3a3477..ddd23ecfae 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6401,6 +6401,18 @@ command is off where there is no clock (the web). → `{path, format, bytes, war {"name":"run_command","arguments":{"command":"addon.document.saveTimestampedCopy","params":{"folder":"/Users/me/Versions","format":"pdf"}}} ``` +`addon.document.exportAllOpen {folder, format?}` writes a copy of every open document, in tab order, to `folder`, +each named after its document (`<name>.<ext>`, with `-2`, `-3`… added when that name is taken there or by another +copy, so no file is replaced). `format` is a save format (`pdf` by default; `svg`, `svgz`, `vectorcraft`, `ai`, +`eps`). Each copy is written as `file.saveCopy` writes it, inside the automation roots in force: every document keeps +its path, title and modified state, no undo step is made, and the active document stays active. A document that +can't be written is listed in `failed` and the others are still written (#4920). The desktop app's Export All Open +Documents as PDF and as SVG ask for the folder. → `{files: [{title, path, warnings}], failed: [{title, error}], format}` + +```json +{"name":"run_command","arguments":{"command":"addon.document.exportAllOpen","params":{"folder":"/Users/me/Out","format":"svg"}}} +``` + `addon.document.symbolsFromLayers {layers?, replace?}` makes one symbol of each top-level layer's art, as `symbol.new` makes one (registration in the centre), named after the layer with a number added when a symbol has that name, as one undo step. `layers` lists layer ids (top-level layers only; anything else is refused); by default it takes the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 52c9258162..c592788dfe 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1448,10 +1448,15 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov Symbols area (#4938), from the public symbol documentation ([create and place symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html), [edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html)). Symbol Options has Symbol Type (Dynamic Symbol / Static Symbol; the dialog's default is Dynamic, `symbol.new`'s `type` defaults to static so scripts behave as before). An instance of a dynamic symbol keeps its own fill, stroke, opacity and blend for any object of the symbol's art, named by a child-index path (`symbol.instance.setAppearance`), and stays an instance: the canvas, SVG, PDF, EPS, legacy `.ai`, EMF/WMF and DXF writers, effects and Expand draw the art with those changes. Redefining the symbol reshapes every instance and keeps each change whose object the new art still has; Break Link bakes the changes into the art; Edit Symbol expands the symbol's own art; Reset (`symbol.instance.reset`: the Properties panel's Quick Actions and the Symbols panel menu) and making the symbol static drop them. The type is stored on the symbol and the changes on the instance in the native format, both left out when unset, so documents without them save byte for byte as before. Remaining: Direct Selection of an object inside a dynamic instance on the canvas (with the Fill/Stroke controls then setting its change), and reading and writing the type and changes in `.ai` files. Evidence: `crates/engine/src/tests/dynamic_symbols.rs`, `crates/doc/src/symbol_overrides.rs` tests. Score unchanged at 87% (estimated); hours 5–9 → 4–8. +## Document Tools add-on: Export All Open Documents (2026-11-01) + +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Document Tools › Export All Open Documents as PDF (or as SVG) asks for a folder and writes a copy of every open document there, each named after its document with `-2`, `-3`… added when a name is taken, so no file is replaced (`addon.document.exportAllOpen {folder, format?}`, #4920). Each copy is written as Save a Copy writes it: the documents keep their paths, titles and modified state, and the active one stays active. A document that can't be written is named in the status bar and the others are still written. Tests: `addons::document::tests::export_all_open_documents_writes_each_to_the_folder_picked` (ui-egui), `cmd::addons::document::tests::export_all_open_documents_writes_each_and_reports_failures` (engine). + ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): Export All Open Documents as PDF or SVG (#4920); evidence added; scores unchanged. | | 2026-11-01 | minor | Path Precision Tools add-on (a VectorCraft addition): Expand Dashes into Paths (#4922); evidence added; scores unchanged. | | 2026-11-01 | minor | Type core: the Glyphs panel highlights the character selected with the Type tool and scrolls it into view (#4908); evidence added; scores unchanged. | | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Randomize Opacity (#4925); evidence added; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 221211281d..f9e9ce12e2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -337,6 +337,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `<name>_YYYY-MM-DD_HH-MM.<ext>` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | +| Document Tools add-on (VectorCraft addition): Export All Open Documents as PDF / as SVG (#4920) | done | asks for a folder, writes a copy of every open document named after it (taken names numbered, nothing replaced), documents and active tab unchanged; failures named in the status bar | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › New Symbols from Layers makes a symbol of each layer's art named after the layer (the highlighted layers when two or more are, else all); Convert Layers to Symbols also replaces each layer's art with an instance in place; empty layers skipped, one undo step | done | #4927; `addon.document.symbolsFromLayers`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its seven tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | @@ -392,6 +393,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): Export All Open Documents as PDF or SVG (#4920); scores and estimates unchanged | | 2026-11-01 | minor | Path Precision Tools add-on (a VectorCraft addition): Expand Dashes into Paths (#4922); scores and estimates unchanged | | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Randomize Opacity (#4925); scores and estimates unchanged | | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Sort Objects (#4917); scores and estimates unchanged | From 2d95cd667b4e08d75ae7e18b5edad0214d12e7e8 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 09:21:14 +0700 Subject: [PATCH 245/260] Document Tools: catalog rows for Export All Open Documents, and its failure message as one translatable message --- crates/ui-egui/src/addons/document.rs | 13 ++++++++----- crates/ui-egui/src/i18n/bg.tsv | 5 +++++ crates/ui-egui/src/i18n/bs.tsv | 5 +++++ crates/ui-egui/src/i18n/ca.tsv | 5 +++++ crates/ui-egui/src/i18n/cs.tsv | 5 +++++ crates/ui-egui/src/i18n/da.tsv | 5 +++++ crates/ui-egui/src/i18n/de.tsv | 5 +++++ crates/ui-egui/src/i18n/el.tsv | 5 +++++ crates/ui-egui/src/i18n/es.tsv | 5 +++++ crates/ui-egui/src/i18n/fi.tsv | 5 +++++ crates/ui-egui/src/i18n/fr.tsv | 5 +++++ crates/ui-egui/src/i18n/hu.tsv | 5 +++++ crates/ui-egui/src/i18n/id.tsv | 5 +++++ crates/ui-egui/src/i18n/it.tsv | 5 +++++ crates/ui-egui/src/i18n/ja.tsv | 5 +++++ crates/ui-egui/src/i18n/ka.tsv | 5 +++++ crates/ui-egui/src/i18n/ko.tsv | 5 +++++ crates/ui-egui/src/i18n/nl.tsv | 5 +++++ crates/ui-egui/src/i18n/pl.tsv | 5 +++++ crates/ui-egui/src/i18n/pt-br.tsv | 5 +++++ crates/ui-egui/src/i18n/ru.tsv | 5 +++++ crates/ui-egui/src/i18n/sv.tsv | 5 +++++ crates/ui-egui/src/i18n/tr.tsv | 5 +++++ crates/ui-egui/src/i18n/uk.tsv | 5 +++++ crates/ui-egui/src/i18n/vi.tsv | 5 +++++ crates/ui-egui/src/i18n/zh-hans.tsv | 5 +++++ crates/ui-egui/src/i18n/zh-hant.tsv | 5 +++++ 27 files changed, 138 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/addons/document.rs b/crates/ui-egui/src/addons/document.rs index 4d439c7233..14723e417f 100644 --- a/crates/ui-egui/src/addons/document.rs +++ b/crates/ui-egui/src/addons/document.rs @@ -50,11 +50,14 @@ pub(crate) fn export_all(app: &mut VectorcraftApp, p: &Value) -> Result<Value, S let r = app.session.execute(EXPORT_ALL, &p).map_err(|e| e.to_string())?; let written = r["files"].as_array().map_or(0, Vec::len); let failed = r["failed"].as_array().cloned().unwrap_or_default(); - let mut status = crate::i18n::msg_n(written as u64, "Exported {n} document", "Exported {n} documents", &[]); - if let Some(f) = failed.first() { - let (title, error) = (f["title"].as_str().unwrap_or_default(), f["error"].as_str().unwrap_or_default()); - status = format!("{status}; {title} wasn't written: {error}"); - } + let status = match failed.first() { + Some(f) => { + let args = [("title", f["title"].as_str().unwrap_or_default()), ("error", f["error"].as_str().unwrap_or_default())]; + let (one, other) = ("Exported {n} document; {title} wasn't written: {error}", "Exported {n} documents; {title} wasn't written: {error}"); + crate::i18n::msg_n(written as u64, one, other, &args) + } + None => crate::i18n::msg_n(written as u64, "Exported {n} document", "Exported {n} documents", &[]), + }; app.status(status); Ok(r) } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 00d07dcbe4..801ed44b5c 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5993,6 +5993,11 @@ breakText Glyphs Глифи Odia Ория Urdu Урду VectorCraft {release} and later (version {n}) VectorCraft {release} и по-нови (версия {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Експортиране на всички отворени документи като PDF + Export All Open Documents as SVG Експортиране на всички отворени документи като SVG +@msgplural Exported {n} document|Exported {n} documents Експортиран е {n} документ|Експортирани са {n} документа +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Експортиран е {n} документ; {title} не беше записан: {error}|Експортирани са {n} документа; {title} не беше записан: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Тип на символа: Dynamic Symbol Динамичен символ diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index b49ece9ce7..d2e67c11da 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6025,6 +6025,11 @@ shape Open Otvoren Odia Odija Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} i novije (verzija {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Izvezi sve otvorene dokumente kao PDF + Export All Open Documents as SVG Izvezi sve otvorene dokumente kao SVG +@msgplural Exported {n} document|Exported {n} documents Izvezen je {n} dokument|Izvezena su {n} dokumenta|Izvezeno je {n} dokumenata +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Izvezen je {n} dokument; {title} nije zapisan: {error}|Izvezena su {n} dokumenta; {title} nije zapisan: {error}|Izvezeno je {n} dokumenata; {title} nije zapisan: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Vrsta simbola: Dynamic Symbol Dinamički simbol diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 5509d3eaf2..ffb752f8a9 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6099,6 +6099,11 @@ breakText Glyphs Glifs Odia Oriya Urdu Urdú VectorCraft {release} and later (version {n}) VectorCraft {release} i posteriors (versió {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Exporta tots els documents oberts com a PDF + Export All Open Documents as SVG Exporta tots els documents oberts com a SVG +@msgplural Exported {n} document|Exported {n} documents S’ha exportat {n} document|S’han exportat {n} documents +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} S’ha exportat {n} document; no s’ha escrit {title}: {error}|S’han exportat {n} documents; no s’ha escrit {title}: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Tipus de símbol: Dynamic Symbol Símbol dinàmic diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 6546f97ec4..97ab1c407a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6109,6 +6109,11 @@ breakText Glyphs Glyfy Odia Urijština Urdu Urdština VectorCraft {release} and later (version {n}) VectorCraft {release} a novější (verze {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Exportovat všechny otevřené dokumenty jako PDF + Export All Open Documents as SVG Exportovat všechny otevřené dokumenty jako SVG +@msgplural Exported {n} document|Exported {n} documents Exportován {n} dokument|Exportovány {n} dokumenty|Exportováno {n} dokumentů +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Exportován {n} dokument; {title} nebyl zapsán: {error}|Exportovány {n} dokumenty; {title} nebyl zapsán: {error}|Exportováno {n} dokumentů; {title} nebyl zapsán: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Typ symbolu: Dynamic Symbol Dynamický symbol diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 6ef8a029ae..1d1741662b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6008,6 +6008,11 @@ breakText Glyphs Glyffer Odia Oriya Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} og nyere (version {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Eksportér alle åbne dokumenter som PDF + Export All Open Documents as SVG Eksportér alle åbne dokumenter som SVG +@msgplural Exported {n} document|Exported {n} documents Eksporterede {n} dokument|Eksporterede {n} dokumenter +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Eksporterede {n} dokument; {title} blev ikke skrevet: {error}|Eksporterede {n} dokumenter; {title} blev ikke skrevet: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Symboltype: Dynamic Symbol Dynamisk symbol diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c4d3b973d6..8045420136 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5694,6 +5694,11 @@ breakText Glyphs Glyphen Odia Oriya Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} und neuer (Version {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Alle geöffneten Dokumente als PDF exportieren + Export All Open Documents as SVG Alle geöffneten Dokumente als SVG exportieren +@msgplural Exported {n} document|Exported {n} documents {n} Dokument exportiert|{n} Dokumente exportiert +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} {n} Dokument exportiert; {title} wurde nicht geschrieben: {error}|{n} Dokumente exportiert; {title} wurde nicht geschrieben: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Symboltyp: Dynamic Symbol Dynamisches Symbol diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 89e694f673..ce061787a2 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6061,6 +6061,11 @@ breakText Glyphs Γλύφοι Odia Όντια Urdu Ούρντου VectorCraft {release} and later (version {n}) VectorCraft {release} και νεότερες (έκδοση {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Εξαγωγή όλων των ανοιχτών εγγράφων ως PDF + Export All Open Documents as SVG Εξαγωγή όλων των ανοιχτών εγγράφων ως SVG +@msgplural Exported {n} document|Exported {n} documents Εξήχθη {n} έγγραφο|Εξήχθησαν {n} έγγραφα +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Εξήχθη {n} έγγραφο; το {title} δεν γράφτηκε: {error}|Εξήχθησαν {n} έγγραφα; το {title} δεν γράφτηκε: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Τύπος συμβόλου: Dynamic Symbol Δυναμικό σύμβολο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f4ada77f1f..3f389ff274 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6051,6 +6051,11 @@ breakText Glyphs Glifos Odia Oriya Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} y posteriores (versión {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Exportar todos los documentos abiertos como PDF + Export All Open Documents as SVG Exportar todos los documentos abiertos como SVG +@msgplural Exported {n} document|Exported {n} documents Se exportó {n} documento|Se exportaron {n} documentos +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Se exportó {n} documento; no se escribió {title}: {error}|Se exportaron {n} documentos; no se escribió {title}: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Tipo de símbolo: Dynamic Symbol Símbolo dinámico diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1161c73de2..d3cf99cd8b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6139,6 +6139,11 @@ breakText Glyphs Merkit Odia Orija Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} ja uudemmat (versio {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Vie kaikki avoimet asiakirjat PDF-muodossa + Export All Open Documents as SVG Vie kaikki avoimet asiakirjat SVG-muodossa +@msgplural Exported {n} document|Exported {n} documents Vietiin {n} asiakirja|Vietiin {n} asiakirjaa +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Vietiin {n} asiakirja; {title} jäi kirjoittamatta: {error}|Vietiin {n} asiakirjaa; {title} jäi kirjoittamatta: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Symbolin tyyppi: Dynamic Symbol Dynaaminen symboli diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e12387e1d9..e82972fbc6 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6106,6 +6106,11 @@ breakText Glyphs Glyphes Odia Odia Urdu Ourdou VectorCraft {release} and later (version {n}) VectorCraft {release} et ultérieures (version {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Exporter tous les documents ouverts en PDF + Export All Open Documents as SVG Exporter tous les documents ouverts en SVG +@msgplural Exported {n} document|Exported {n} documents {n} document exporté|{n} documents exportés +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} {n} document exporté; {title} n’a pas été écrit : {error}|{n} documents exportés; {title} n’a pas été écrit : {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Type de symbole : Dynamic Symbol Symbole dynamique diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c6fcdcb49f..1f7317fad8 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6095,6 +6095,11 @@ breakText Glyphs Glifák Odia Odia Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} és újabb (verzió: {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Az összes megnyitott dokumentum exportálása PDF-ként + Export All Open Documents as SVG Az összes megnyitott dokumentum exportálása SVG-ként +@msgplural Exported {n} document|Exported {n} documents Exportált dokumentumok: {n} +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Exportált dokumentumok: {n}; {title} nem lett kiírva: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Szimbólum típusa: Dynamic Symbol Dinamikus szimbólum diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 9ed018f08c..b90aadc98d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6008,6 +6008,11 @@ breakText Glyphs Glif Odia Oriya Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} dan yang lebih baru (versi {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Ekspor Semua Dokumen Terbuka sebagai PDF + Export All Open Documents as SVG Ekspor Semua Dokumen Terbuka sebagai SVG +@msgplural Exported {n} document|Exported {n} documents Berhasil mengekspor {n} dokumen +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Berhasil mengekspor {n} dokumen; {title} tidak ditulis: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Jenis simbol: Dynamic Symbol Simbol dinamis diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 669a0e3c3a..9a9709b8df 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5728,6 +5728,11 @@ breakText Glyphs Glifi Odia Odia Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} e successive (versione {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Esporta tutti i documenti aperti come PDF + Export All Open Documents as SVG Esporta tutti i documenti aperti come SVG +@msgplural Exported {n} document|Exported {n} documents Esportato {n} documento|Esportati {n} documenti +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Esportato {n} documento; {title} non è stato scritto: {error}|Esportati {n} documenti; {title} non è stato scritto: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Tipo di simbolo: Dynamic Symbol Simbolo dinamico diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 0a05ba0b90..b901b93366 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5795,6 +5795,11 @@ breakText Glyphs 字形 Odia オディア語 Urdu ウルドゥー語 VectorCraft {release} and later (version {n}) VectorCraft {release} 以降 (バージョン {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF 開いているすべてのドキュメントを PDF として書き出し + Export All Open Documents as SVG 開いているすべてのドキュメントを SVG として書き出し +@msgplural Exported {n} document|Exported {n} documents {n} 個のドキュメントを書き出しました +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} {n} 個のドキュメントを書き出しました; {title} は書き出されませんでした: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: シンボルの種類: Dynamic Symbol ダイナミックシンボル diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index dcfc8a20f1..be58e0b36d 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6098,6 +6098,11 @@ breakText Glyphs გლიფები Odia ორია Urdu ურდუ VectorCraft {release} and later (version {n}) VectorCraft {release} და უფრო ახალი (ვერსია {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF ყველა ღია დოკუმენტის ექსპორტი PDF-ად + Export All Open Documents as SVG ყველა ღია დოკუმენტის ექსპორტი SVG-ად +@msgplural Exported {n} document|Exported {n} documents ექსპორტირებულია დოკუმენტი ({n}) +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} ექსპორტირებულია დოკუმენტი ({n}); {title} არ ჩაიწერა: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: სიმბოლოს ტიპი: Dynamic Symbol დინამიკური სიმბოლო diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 1b7190a41c..b979e26136 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5691,6 +5691,11 @@ breakText Glyphs 글리프 Odia 오리야어 Urdu 우르두어 VectorCraft {release} and later (version {n}) VectorCraft {release} 이상 (버전 {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF 열린 모든 문서를 PDF로 내보내기 + Export All Open Documents as SVG 열린 모든 문서를 SVG로 내보내기 +@msgplural Exported {n} document|Exported {n} documents 문서 {n}개를 내보냈습니다 +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} 문서 {n}개를 내보냈습니다; {title}을(를) 쓰지 못했습니다: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: 심볼 유형: Dynamic Symbol 동적 심볼 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 7d137e3e72..60b73cb0fd 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6052,6 +6052,11 @@ breakText Glyphs Glyphs Odia Odia Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} en nieuwer (versie {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Alle geopende documenten exporteren als PDF + Export All Open Documents as SVG Alle geopende documenten exporteren als SVG +@msgplural Exported {n} document|Exported {n} documents {n} document geëxporteerd|{n} documenten geëxporteerd +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} {n} document geëxporteerd; {title} is niet geschreven: {error}|{n} documenten geëxporteerd; {title} is niet geschreven: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Symbooltype: Dynamic Symbol Dynamisch symbool diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 810f51bdf8..e32cb1fa11 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5964,6 +5964,11 @@ breakText Glyphs Glify Odia Orija Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} i nowsze (wersja {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Eksportuj wszystkie otwarte dokumenty jako PDF + Export All Open Documents as SVG Eksportuj wszystkie otwarte dokumenty jako SVG +@msgplural Exported {n} document|Exported {n} documents Wyeksportowano {n} dokument|Wyeksportowano {n} dokumenty|Wyeksportowano {n} dokumentów +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Wyeksportowano {n} dokument; nie zapisano {title}: {error}|Wyeksportowano {n} dokumenty; nie zapisano {title}: {error}|Wyeksportowano {n} dokumentów; nie zapisano {title}: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Typ symbolu: Dynamic Symbol Symbol dynamiczny diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index c5fe48efae..af74d69dd8 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6028,6 +6028,11 @@ breakText Glyphs Glifos Odia Oriá Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} e posteriores (versão {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Exportar todos os documentos abertos como PDF + Export All Open Documents as SVG Exportar todos os documentos abertos como SVG +@msgplural Exported {n} document|Exported {n} documents {n} documento exportado|{n} documentos exportados +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} {n} documento exportado; {title} não foi gravado: {error}|{n} documentos exportados; {title} não foi gravado: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Tipo de símbolo: Dynamic Symbol Símbolo dinâmico diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index dc410120f6..c497b2ad2b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6086,6 +6086,11 @@ breakText Glyphs Глифы Odia Ория Urdu Урду VectorCraft {release} and later (version {n}) VectorCraft {release} и новее (версия {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Экспортировать все открытые документы в PDF + Export All Open Documents as SVG Экспортировать все открытые документы в SVG +@msgplural Exported {n} document|Exported {n} documents Экспортирован {n} документ|Экспортировано {n} документа|Экспортировано {n} документов +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Экспортирован {n} документ; {title} не записан: {error}|Экспортировано {n} документа; {title} не записан: {error}|Экспортировано {n} документов; {title} не записан: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Тип символа: Dynamic Symbol Динамический символ diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index a9b8a41e75..4b8742d00a 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6161,6 +6161,11 @@ breakText Glyphs Glyfer Odia Oriya Urdu Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} och senare (version {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Exportera alla öppna dokument som PDF + Export All Open Documents as SVG Exportera alla öppna dokument som SVG +@msgplural Exported {n} document|Exported {n} documents Exporterade {n} dokument|Exporterade {n} dokument +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Exporterade {n} dokument; {title} skrevs inte: {error}|Exporterade {n} dokument; {title} skrevs inte: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Symboltyp: Dynamic Symbol Dynamisk symbol diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 379c377a2c..5aeae9118b 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6066,6 +6066,11 @@ breakText Glyphs Glifler Odia Oriya dili Urdu Urduca VectorCraft {release} and later (version {n}) VectorCraft {release} ve sonrası (sürüm {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Tüm Açık Belgeleri PDF Olarak Dışa Aktar + Export All Open Documents as SVG Tüm Açık Belgeleri SVG Olarak Dışa Aktar +@msgplural Exported {n} document|Exported {n} documents {n} belge dışa aktarıldı +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} {n} belge dışa aktarıldı; {title} yazılamadı: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Sembol Türü: Dynamic Symbol Dinamik Sembol diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 77eeeecc35..53fe1f4623 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5708,6 +5708,11 @@ breakText Glyphs Гліфи Odia Одія Urdu Урду VectorCraft {release} and later (version {n}) VectorCraft {release} і новіші (версія {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Експортувати всі відкриті документи як PDF + Export All Open Documents as SVG Експортувати всі відкриті документи як SVG +@msgplural Exported {n} document|Exported {n} documents Експортовано {n} документ|Експортовано {n} документи|Експортовано {n} документів +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Експортовано {n} документ; {title} не записано: {error}|Експортовано {n} документи; {title} не записано: {error}|Експортовано {n} документів; {title} не записано: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Тип символу: Dynamic Symbol Динамічний символ diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index a947f674d2..ea692ca644 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5711,6 +5711,11 @@ breakText Glyphs Glyph Odia Tiếng Odia Urdu Tiếng Urdu VectorCraft {release} and later (version {n}) VectorCraft {release} trở lên (phiên bản {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF Xuất tất cả tài liệu đang mở dưới dạng PDF + Export All Open Documents as SVG Xuất tất cả tài liệu đang mở dưới dạng SVG +@msgplural Exported {n} document|Exported {n} documents Đã xuất {n} tài liệu +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Đã xuất {n} tài liệu; không ghi được {title}: {error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Kiểu ký hiệu: Dynamic Symbol Ký hiệu động diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 3fd35f967f..431eb33552 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5951,6 +5951,11 @@ breakText Glyphs 字形 Odia 奥里亚语 Urdu 乌尔都语 VectorCraft {release} and later (version {n}) VectorCraft {release} 及更高版本 (版本 {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF 将所有打开的文档导出为 PDF + Export All Open Documents as SVG 将所有打开的文档导出为 SVG +@msgplural Exported {n} document|Exported {n} documents 已导出 {n} 个文档 +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} 已导出 {n} 个文档; 未写入 {title}:{error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: 符号类型: Dynamic Symbol 动态符号 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index cd01899a4e..c55958717b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5748,6 +5748,11 @@ breakText Glyphs 字符 Odia 歐利亞文 Urdu 烏都文 VectorCraft {release} and later (version {n}) VectorCraft {release} 及更新版本 (版本 {n}) +# Document Tools add-on: Export All Open Documents (#4920). + Export All Open Documents as PDF 將所有開啟的文件匯出為 PDF + Export All Open Documents as SVG 將所有開啟的文件匯出為 SVG +@msgplural Exported {n} document|Exported {n} documents 已匯出 {n} 份文件 +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} 已匯出 {n} 份文件; 未寫入 {title}:{error} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: 符號類型: Dynamic Symbol 動態符號 From 9b9f0918f0131017f8505df7dd0a9cd8193505af Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 09:54:36 +0700 Subject: [PATCH 246/260] Fix #4687: the Artboards panel reorders artboards by dragging a row --- crates/ui-egui/src/panels/artboards.rs | 20 ++++++++- crates/ui-egui/src/panels/artboards/tests.rs | 44 ++++++++++++++++++++ docs/ui-parity.md | 4 +- 3 files changed, 66 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index 695f63fd62..77023bacb1 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -1,6 +1,6 @@ //! Artboards panel: numbered list with inline rename (double-click the name, or the panel menu's //! Rename; while several artboards are selected, the name typed goes to all of them, numbered), -//! move up / down, new +//! move up / down (or drag a row above or below another), new //! (Alt-click: Artboard Options for the new artboard first), delete; a row dragged onto New //! Artboard duplicates its artboard (as Duplicate Artboards does, with //! its art when the Artboard tool's Move/Copy Artwork with Artboard is on). The highlighted row is the active artboard, the one the status bar's navigator shows and @@ -405,6 +405,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let all = picked(app, abs.len()); let editing: Option<usize> = pstate(ui.ctx(), "ab-edit"); let mut row_clicked = false; + // A row dropped on another row: (from, to), the index it lands at. + let mut dropped = None; let list_rect = widgets::list_box(ui, |ui| { ui.set_min_height(110.0); ui.spacing_mut().item_spacing.y = 0.0; @@ -512,10 +514,26 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } else if resp.double_clicked() { start_rename(ui.ctx(), app, i); } + // Another row dragged over this one lands above or below it by the pointer's half, + // a line showing where. + if let Some(from) = resp.dnd_hover_payload::<RowDrag>().map(|d| d.0).filter(|from| *from != i) { + let after = ui.input(|inp| inp.pointer.interact_pos()).is_some_and(|p| p.y > r.center().y); + let y = if after { r.bottom() } else { r.top() }; + ui.painter().line_segment([pos2(r.left(), y), pos2(r.right(), y)], egui::Stroke::new(2.0, t.accent)); + if resp.dnd_release_payload::<RowDrag>().is_some() { + let to = i + usize::from(after); + dropped = Some((from, if from < to { to - 1 } else { to })); + } + } } }); scrolled.inner_rect }); + if let Some((from, to)) = dropped.filter(|(from, to)| from != to) + && app.run("artboard.reorder", json!({"index": from, "to": to})).is_ok() + { + select(app, to); + } // Keyboard: the panel takes it with a click on a row and gives it up when the pointer is // pressed outside the list or the panel is not drawn (`ab-keys`: the frame it last had it in). let pressed_outside = ui.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !list_rect.contains(p))); diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index 15bab000bc..edae3a32e2 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -994,6 +994,50 @@ fn dragging_a_row_onto_new_artboard_duplicates_it() { assert_eq!(app.view().unwrap().artboard, 1); } +/// #4687: a row dragged above or below another row reorders the artboards there (a line shows +/// where it lands), in one undo step, and the moved artboard becomes the active one. +#[test] +fn dragging_a_row_onto_another_row_reorders_the_artboards() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); + let ctx = egui::Context::default(); + let screen = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(240.0, 400.0))); + let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: screen, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.shapes + }; + let shapes = frame(&mut app, vec![]); + let name_at = |label: &str| { + shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text() == label => Some(t.pos + vec2(4.0, 4.0)), + _ => None, + }) + .unwrap() + }; + let (first, last) = (name_at("Artboard 1"), name_at("Artboard 3")); + let names = |app: &VectorcraftApp| app.session.active().unwrap().doc.artboards.iter().map(|a| a.name.clone()).collect::<Vec<_>>(); + let button = |at, pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + // Artboard 1 dragged onto the lower half of Artboard 3's row lands below it. + let below = last + vec2(0.0, 8.0); + frame(&mut app, vec![egui::Event::PointerMoved(first), button(first, true)]); + frame(&mut app, vec![egui::Event::PointerMoved(first + vec2(0.0, 12.0))]); + let held = frame(&mut app, vec![egui::Event::PointerMoved(below)]); + let accent = Tokens::get(&ctx).accent; + assert!( + held.iter().any(|c| matches!(&c.shape, egui::Shape::LineSegment { stroke, .. } if stroke.color == accent)), + "a line shows where it lands" + ); + frame(&mut app, vec![button(below, false)]); + assert_eq!(names(&app), ["Artboard 2", "Artboard 3", "Artboard 1"]); + assert_eq!(app.view().unwrap().artboard, 2, "the moved artboard is active"); + // One undo step puts it back. + app.session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(names(&app), ["Artboard 1", "Artboard 2", "Artboard 3"]); +} + /// A click in a row's lock column locks its artboard and shows the lock next to the name, a /// second click unlocks it, and each click is one undo step. Delete Artboard leaves a locked /// artboard. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f9e9ce12e2..3c618c46bb 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Path Precision Tools add-on: Expand Dashes into Paths, #4922) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Artboards panel: drag a row to reorder the artboards, #4687) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -228,6 +228,7 @@ tools, never checked side by side) isn't captured row by row. | Escape while typing ends the edit, keeps the type selected and switches to the Selection tool | done | #1802 (#1686, #1656) | | Selection tool: selected area type and type on a path show an in port and an out port (empty, an arrow where threaded, the red "+" of overflow); a click on either loads the text cursor; a click on a closed path, on empty canvas or a drag threads the text there, after the clicked frame from its out port, before it from its in port; Escape or another tool drops it; a double-click on a threaded port breaks the thread there | partial | #2572 (`text.thread.add`, `before` for the in port); the out port sits on the frame's right side above the bottom-right corner handle and the in port on its left side below the top-left one, so the handles can still be grabbed; a double-click on a threaded port breaks the thread (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)); the loaded cursor borrows the I-beam | | Shift-click selects several artboards (Artboard tool, Artboards panel); they move, Alt-copy and delete together | done | `artboard.move`/`artboard.delete` `indices` (#1139); panel menu, trash and Properties share selected-set deletion; all-selected retains artboard 1 and a single board cannot be deleted, with pointer-event and Undo/Redo coverage | +| Artboards panel: drag a row above or below another to reorder the artboards (as Move Up / Move Down do) | done | #4687; a line shows where the row lands, `artboard.reorder` in one undo step, the moved artboard becomes active; public forum answers describe the drag | | Artboards panel › Delete Empty Artboards | done | `artboard.deleteEmpty`; one undo step, guides go too, locked artboards stay, and artboard 1 when every artboard is empty and none is locked; an artboard is empty when no object (hidden, locked and template art included; guides not) has visual bounds that meet or touch it, a group counting by its members and a clip group or clipping layer by its members inside the clip (our reading of "no artwork"; the pages give no finer rule); [spec](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html) | | Artboard Delete/Backspace delete selected boards while protecting artwork, the last board and active drags | done | Headless shortcut regressions in `tests/distortkeys.rs` cover retaining the original first board when all are selected, single-board protection, artwork, saved state and Undo/Redo; the navigator follows the tool’s surviving board through repeated deletion and history changes. | | Artboard navigator synchronizes the active tool selection before deletion | done | Actual status-bar Next → Delete/Backspace and Next → Properties Delete regressions in `chrome.rs` cover surviving board records, preserved artwork and Undo/Redo; other tools keep object selection and history. **Tab-switch follow-up:** document-tab changes align the Artboard tool with the displayed board. Actual A → B → A tab clicks followed by Properties Delete and controls for same-tab multiselection, Move/Scale Artwork options and other tools passed, along with historical full CI on `a0671777`. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area). **Clean-tab close:** with the Artboard tool active, closing a clean active tab restores the surviving document's displayed board before Properties Delete. | @@ -393,6 +394,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Artboards panel: a row dragged above or below another reorders the artboards (#4687); scores and estimates unchanged | | 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): Export All Open Documents as PDF or SVG (#4920); scores and estimates unchanged | | 2026-11-01 | minor | Path Precision Tools add-on (a VectorCraft addition): Expand Dashes into Paths (#4922); scores and estimates unchanged | | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Randomize Opacity (#4925); scores and estimates unchanged | From 469c7a421e8f59534677fdc052ef3cb656d56eed Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Sat, 31 Oct 2026 23:43:01 -0400 Subject: [PATCH 247/260] ci: grant packages write permission to release workflow --- .github/workflows/release.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d1677e538c..07b3c6b7fe 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -63,6 +63,7 @@ jobs: needs: git-sources permissions: contents: write + packages: write # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: From 70651f585ef63da1c0352121a2df8184a44e5b4c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 19:28:19 -0700 Subject: [PATCH 248/260] .ai import: template layers and ruler guides open as they were set The editing data's layer options set a template layer from the flag four places after the colour index. The colour index of nine-operand options, and the colour index and dimming percentage of eleven and twelve operand options, are read from their own places (they were read one place later). A straight (N) * guide path directly on a layer that runs across the whole canvas, or from edge to edge of one artboard, opens as a ruler guide on that layer (an artboard guide of that artboard); other guide paths stay guide paths. Guides scale with the document when its editing data is in the units of a UserUnit page, and an EPS that keeps only its first artboard keeps only that artboard's guides. Fixes #779 --- crates/engine/tests/import_fuzz.rs | 55 +++++++++ crates/eps/src/import/ai/read.rs | 13 ++- crates/eps/src/import/ai/read/art.rs | 22 +++- crates/eps/src/import/ai/read/containers.rs | 2 +- crates/eps/src/import/ai/read/document.rs | 79 ++++++++++++- crates/eps/src/import/ai/read/ops.rs | 12 +- crates/eps/src/import/ai/read/types.rs | 1 + crates/eps/src/import/ai/tests.rs | 118 +++++++++++++++++++- crates/eps/src/import/native/build.rs | 14 ++- crates/eps/src/import/tests_native.rs | 40 +++++++ docs/file-format-parity.md | 2 +- docs/target-app-parity.md | 1 + 12 files changed, 343 insertions(+), 16 deletions(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index e7a89d97c5..b93b28b53b 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3011,6 +3011,22 @@ proptest! { } } +/// An operand of a layer's options (`Lb`): a flag, a colour index or component, a percentage, or +/// anything else. +fn arb_layer_operand() -> impl Strategy<Value = String> { + prop_oneof![Just("0".to_string()), Just("1".to_string()), (-2i32..300).prop_map(|v| v.to_string()), arb_num()] +} + +/// A coordinate of a guide path: the ends of the canvas around the template box's centre (100 50), +/// the edges of the artboards, near them, or anything else. +fn arb_guide_coord() -> impl Strategy<Value = String> { + prop_oneof![ + prop::sample::select(vec!["-8091.5", "8291.5", "-8141.5", "8241.5", "0", "50", "100", "200", "-8091.505", "8291.5001", "1e308"]) + .prop_map(str::to_string), + arb_num(), + ] +} + /// The operators, operands and section comments of hostile editing data. fn arb_ai_token() -> impl Strategy<Value = String> { prop_oneof![ @@ -3037,6 +3053,9 @@ fn arb_ai_token() -> impl Strategy<Value = String> { "b", "W", "(b) *", + "(N) *", + "(S) *", + "-8091.5 50 m 8291.5 50 L (N) *", "u", "U", "*u", @@ -3297,6 +3316,42 @@ proptest! { survive("hostile editing data in an EPS of its art's box", || vectorcraft_engine::cmd::fileio::load("x.eps", &boxed).ok().map(|l| l.doc))?; } + /// Layer options (`Lb`) of any number of operands with any values, and guide paths (`(N) *`, + /// `(S) *`) of any points, among them ones across the whole canvas or from edge to edge of + /// artboards that overlap or are the same, on layers and sublayers. + #[test] + fn ai_layer_options_and_ruler_guides_never_panic( + options in prop::collection::vec(arb_layer_operand(), 0..17), + guides in prop::collection::vec((prop::collection::vec((arb_guide_coord(), arb_guide_coord()), 0..5), any::<bool>(), any::<bool>()), 0..12), + boards in prop::collection::vec(prop::sample::select(vec![[0.0, 100.0, 200.0, 0.0], [0.0, 100.0, 100.0, 0.0], [50.0, 100.0, 200.0, 0.0]]), 0..4), + ) { + use vectorcraft_testkit::ai; + let board = |b: &[f64; 4]| { + format!( + "%_/Dictionary :\n%_{} {} /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} {} /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n", + b[0], b[1], b[2], b[3] + ) + }; + let array: String = boards.iter().map(board).collect(); + let document = format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n{array}%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"); + let paths: Vec<String> = guides + .iter() + .map(|(points, ruler, sub)| { + let ops: String = points.iter().enumerate().map(|(i, (x, y))| format!("{x} {y} {}\n", if i == 0 { "m" } else { "L" })).collect(); + let path = format!("{ops}({}) *\n", if *ruler { "N" } else { "S" }); + if *sub { format!("%AI5_BeginLayer\n{} Lb\n(Sub) Ln\n{path}LB\n%AI5_EndLayer--\n", options.join(" ")) } else { path } + }) + .collect(); + let body = format!("{document}%AI5_BeginLayer\n{} Lb\n(L) Ln\n{}\nLB\n%AI5_EndLayer--\n", options.join(" "), paths.concat()); + let data = ai::editing_data(200.0, 100.0, &body).replacen("%%EndComments", "%AI3_TemplateBox: 100 50 100 50\n%%EndComments", 1); + survive("layer options and ruler guides", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + survive("layer options and ruler guides in units of 10 points", || { + Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(2000.0, 1000.0), vec![], false, false, 10.0).0) + })?; + let eps = ai::eps(data.as_bytes(), ai::page_ps()); + survive("layer options and ruler guides in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + } + /// The testkit's sample damaged, as it is and compressed, in EPS, `.ai` and PDF files. #[test] fn ai_mutated_sample_never_panics(cut in 0usize..4_000, edits in prop::collection::vec((0usize..4_000, any::<u8>()), 0..12)) { diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 8e7753dd77..cb381d6fde 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -1,9 +1,12 @@ //! The reader: runs the editing data's operators into a document. //! //! - Art space has y up; the first artboard's top left corner is the document's origin. -//! - Layers: `%AI5_BeginLayer`, `visible preview unlocked printing dimmed … colorIndex r g b … -//! dimPercent … Lb` (ten operands in the legacy format, without the one before the colour -//! index), `(name) Ln`, its art, `LB`. +//! - Layers: `%AI5_BeginLayer`, `visible preview unlocked printing dimmed … colorIndex r g b +//! template dimPercent … Lb` (ten operands in the legacy format, without the one before the +//! colour index; see `Reader::layer_attrs`), `(name) Ln`, its art, `LB`. +//! - Ruler guides: a straight `(N) *` guide path, directly on a layer, that runs across the whole +//! canvas (16,383 points around the template box's centre) or from edge to edge of one artboard +//! is a ruler guide on that layer ([`Document::guides`]); other guide paths stay paths. //! - Groups `u` … `U`, compound paths `*u` … `*U`, clipping groups `q` … `Q` (the path painted //! with `W` clips); a group's transparency and name follow its end. //! - Paths: `m`, `l`/`L`, `c`/`C`, `v`/`V`, `y`/`Y`, painted by `N n F f S s B b` (lower case @@ -206,6 +209,9 @@ struct Reader<'a> { clip_fills: HashSet<NodeId>, /// Groups closed as an object's drawn look (`9 () XW`). looks: HashSet<NodeId>, + /// Straight `(N) *` guide paths painted directly on a layer, by id: their two points in art + /// space. [`Reader::finish`] makes the ruler guides among them guides of their layer. + ruler_guides: HashMap<NodeId, (Point, Point)>, /// Legacy compound member groups, even when followed by the generic `9 () XW` marker. compound_groups: HashSet<NodeId>, /// Groups of a text object and its look (see [`Self::style_marker`]), which aren't a look. @@ -308,6 +314,7 @@ impl<'a> Reader<'a> { blend_budget: BLEND_BUDGET, clip_fills: HashSet::new(), looks: HashSet::new(), + ruler_guides: HashMap::new(), compound_groups: HashSet::new(), text_looks: HashSet::new(), group_ended: false, diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 3f60ebe11e..a32ea81daa 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -1,11 +1,12 @@ use super::containers::close; use super::document::TEXT_SLOT; use super::types::{ - FLIP, IMAGE_TOO_LARGE, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, Place, + FLIP, Frame, IMAGE_TOO_LARGE, Kind, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, MAX_SIDE, NON_NATIVE_ART, + NON_NATIVE_ART_UNREAD, Place, }; use super::{ Affine, Appearance, AppearanceItem, Arc, BezPath, CANVAS_CENTRE, FillLayer, ImageBlob, ImageObject, Inks, Instance, LinkInfo, Node, NodeId, - NodeKind, Obj, OpacityMask, Paint, PathData, Point, Reader, Rect, StrokeLayer, V, ps, + NodeKind, Obj, OpacityMask, Paint, PathData, PathEl, Point, Reader, Rect, StrokeLayer, V, ps, }; impl<'a> Reader<'a> { @@ -162,6 +163,10 @@ impl<'a> Reader<'a> { if op.chars().next().is_some_and(|c| c.is_ascii_lowercase()) { close(&mut bp); } + let line = match bp.elements() { + [PathEl::MoveTo(a), PathEl::LineTo(b)] => Some((*a, *b)), + _ => None, + }; let to_doc = self.space(); let path = PathData::from_bezpath(&(to_doc * bp)); let gs = self.gs.clone(); @@ -191,6 +196,19 @@ impl<'a> Reader<'a> { } let kind = NodeKind::Path { path, rule: gs.rule, live: None, clipping: clip, guide }; let mut node = self.new_node(kind, &gs); + // A ruler guide is written as a straight `(N) *` guide path on its layer. + if guide + && op == "N" + && !hidden + && !gs.hidden + && !clip + && self.pattern.is_none() + && matches!(self.frames.last(), Some(Frame { kind: Kind::Layer(_), .. })) + && let Some((a, b)) = line + && [a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite()) + { + self.ruler_guides.insert(node.id, (a, b)); + } node.appearance = Appearance { items, ..Appearance::default() }.into(); node.opacity = gs.opacity; node.blend = gs.blend; diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 39f398a2e2..929f5a0cc9 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -222,7 +222,7 @@ impl<'a> Reader<'a> { let color = a.color.unwrap_or(LayerColor::Preset(0)); let mut layer = Node::new( self.doc.alloc_id(), - NodeKind::Layer { color, template: false, printable: a.printable, children, clip, preview: a.preview, dim_images: a.dim }, + NodeKind::Layer { color, template: a.template, printable: a.printable, children, clip, preview: a.preview, dim_images: a.dim }, ); layer.name = Some(a.name.clone()); layer.visible = a.visible; diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index eeaf108543..7e63b31da5 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1,8 +1,11 @@ use super::art::{element_name, elements, join_and, sane}; use super::containers::drop_commented_copies; use super::types::{FLIP, Kind, MAX_DEPTH}; -use super::{Affine, Artboard, ColorMode, Document, NodeKind, Obj, OpacityMask, Paint, Point, Reader, Rect, Structure, Swatch, Unit, V, obj}; -use vectorcraft_doc::{ImageBlob, PatternDef}; +use super::{ + Affine, Arc, Artboard, CANVAS_CENTRE, ColorMode, Document, Node, NodeId, NodeKind, Obj, OpacityMask, Paint, Point, Reader, Rect, Structure, + Swatch, Unit, V, obj, +}; +use vectorcraft_doc::{Guide, ImageBlob, PatternDef}; /// `%AI5_RulerUnits` → [`Unit`] (Illustrator 7 spec table 3; centimeters is 4; pixels is 6 in later files). fn ruler_unit(v: u8) -> Option<Unit> { @@ -395,6 +398,7 @@ impl<'a> Reader<'a> { } else { self.artboards.clone() }; + let board_rects: Vec<Rect> = boards.iter().map(|(_, r)| *r).collect(); doc.artboards = boards .into_iter() .enumerate() @@ -424,6 +428,22 @@ impl<'a> Reader<'a> { color: None, }]; } + if !self.ruler_guides.is_empty() { + let ids: Vec<u32> = doc.artboards.iter().map(|a| a.id).collect(); + let (candidates, centre) = (std::mem::take(&mut self.ruler_guides), self.template_center); + let pick = |id: NodeId| -> Option<Guide> { + let (a, b) = candidates.get(&id)?; + let (vertical, board) = ruler_guide(*a, *b, centre, &board_rects)?; + let p = to_doc * *a; + let artboard = match board { + Some(i) => Some(*ids.get(i)?), + None => None, + }; + let pos = if vertical { p.x } else { p.y }; + pos.is_finite().then_some(Guide { vertical, pos, artboard, layer: None }) + }; + take_ruler_guides(&mut doc.layers, &pick, &mut doc.guides, 0); + } if self.color_model.unwrap_or(self.cmyk_colors > self.rgb_colors) { doc.color_mode = ColorMode::Cmyk; let (swatches, groups) = vectorcraft_color::default_swatches(ColorMode::Cmyk.model()); @@ -474,6 +494,61 @@ impl<'a> Reader<'a> { } /// The dictionary of entry `key` in `o` or the dictionaries it holds. +/// How far (points) a ruler guide's ends may lie from the canvas's or an artboard's edges. +const GUIDE_TOLERANCE: f64 = 0.01; + +/// Whether the straight guide path from `a` to `b` (art space) is a ruler guide → whether it is +/// vertical, and the index in `boards` of the artboard it belongs to (`None`: a canvas guide). A +/// canvas guide runs across the whole canvas, 16,383 points centred on the template box's +/// centre `centre`; an artboard guide runs from edge to edge of one artboard of `boards`, inside it. +fn ruler_guide(a: Point, b: Point, centre: Option<(f64, f64)>, boards: &[Rect]) -> Option<(bool, Option<usize>)> { + let near = |u: f64, v: f64| (u - v).abs() <= GUIDE_TOLERANCE; + let vertical = match (near(a.x, b.x), near(a.y, b.y)) { + (true, false) => true, + (false, true) => false, + _ => return None, + }; + let (along, across) = if vertical { ((a.y.min(b.y), a.y.max(b.y)), a.x) } else { ((a.x.min(b.x), a.x.max(b.x)), a.y) }; + if let Some((cx, cy)) = centre { + let c = if vertical { cy } else { cx }; + if near(along.0, c - CANVAS_CENTRE) && near(along.1, c + CANVAS_CENTRE) { + return Some((vertical, None)); + } + } + let mut on = boards.iter().enumerate().filter(|(_, r)| { + let (ends, sides) = + if vertical { ((r.min_y(), r.max_y()), (r.min_x(), r.max_x())) } else { ((r.min_x(), r.max_x()), (r.min_y(), r.max_y())) }; + near(along.0, ends.0) && near(along.1, ends.1) && (sides.0..=sides.1).contains(&across) + }); + match (on.next(), on.next()) { + (Some((i, _)), None) => Some((vertical, Some(i))), + _ => None, + } +} + +/// Moves the children of the layers and sublayers of `nodes` that `pick` makes a guide of into +/// `guides`, each on its layer. +fn take_ruler_guides(nodes: &mut [Arc<Node>], pick: &dyn Fn(NodeId) -> Option<Guide>, guides: &mut Vec<Guide>, depth: usize) { + if depth > MAX_DEPTH { + return; + } + for n in nodes { + if !matches!(n.kind, NodeKind::Layer { .. }) { + continue; + } + let id = n.id; + let Some(kids) = Arc::make_mut(n).children_mut() else { continue }; + kids.retain(|k| match pick(k.id) { + Some(g) => { + guides.push(Guide { layer: Some(id), ..g }); + false + } + None => true, + }); + take_ruler_guides(kids, pick, guides, depth + 1); + } +} + fn find_entry<'o>(o: &'o Obj, key: &str, depth: usize) -> Option<&'o Obj> { if depth > 8 { return None; diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 8eff92907b..9461ecb0cb 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -308,8 +308,11 @@ impl<'a> Reader<'a> { Ok(()) } - /// `… Lb`: a layer's options. The legacy format's has ten operands, its colour index one place - /// earlier (`visible preview unlocked printing dimmed masks colorIndex r g b`). + /// `… Lb`: a layer's options, `visible preview unlocked printing dimmed`, then the colour index + /// and its RGB. The colour index is at 5 with fewer than ten operands, 6 with ten to twelve + /// (`masks` before it) and 7 with thirteen or more (one more flag before it). Four places after + /// the colour index comes the template flag (eleven operands or more), then the dimming + /// percentage (twelve or more, else 50). A fourteenth operand changes nothing here. fn layer_attrs(&mut self, vals: &[V]) { let n = Self::nums(vals); let Some(Frame { kind: Kind::Layer(a), .. }) = self.frames.last_mut() else { return }; @@ -318,9 +321,10 @@ impl<'a> Reader<'a> { a.preview = flag(1, true); a.locked = !flag(2, true); a.printable = flag(3, true); - let dim_pct = n.get(12).copied().filter(|v| v.is_finite()).unwrap_or(50.0).clamp(0.0, 100.0); + let at = 5 + usize::from(n.len() >= 10) + usize::from(n.len() >= 13); + a.template = flag(at + 4, false); + let dim_pct = n.get(at + 5).copied().filter(|v| v.is_finite()).unwrap_or(50.0).clamp(0.0, 100.0); a.dim = flag(4, false).then_some(dim_pct.round() as u8); - let at = if n.len() <= 10 { 6 } else { 7 }; let index = n.get(at).copied().unwrap_or(0.0); let rgb = |i: usize| n.get(at + i).map_or(0, |v| v.clamp(0.0, 255.0) as u8); a.color = Some(if (0.0..vectorcraft_doc::LAYER_COLORS.len() as f64).contains(&index) && index.fract() == 0.0 { diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index a2792e84c1..b73177a37f 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -123,6 +123,7 @@ pub(super) struct LayerAttrs { pub(super) preview: bool, pub(super) locked: bool, pub(super) printable: bool, + pub(super) template: bool, pub(super) dim: Option<u8>, pub(super) color: Option<LayerColor>, } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 21227eef65..f20a07d492 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use kurbo::{Point, Rect}; use vectorcraft_color::gradient::GradientKind; use vectorcraft_color::{BlendMode, Color, Paint}; -use vectorcraft_doc::{AppearanceItem, ColorMode, Document, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind, Unit}; +use vectorcraft_doc::{AppearanceItem, ColorMode, Document, Guide, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind, Unit}; use super::*; @@ -2133,6 +2133,122 @@ fn stroked_path_guides_from_the_star_operator() { assert!(matches!(n.appearance.items[0], AppearanceItem::Stroke(_))); } +/// [`stream`] with a template box centred on (306.5, 395.5): the canvas runs 8,191.5 points each +/// way from there. +fn canvas_stream(body: &str) -> String { + stream(body).replacen("%%EndComments", "%AI3_TemplateBox: 306.5 395.5 306.5 395.5\n%%EndComments", 1) +} + +/// The straight guide path from (`x0`, `y0`) to (`x1`, `y1`), `(op) *`. +fn guide_line(x0: f64, y0: f64, x1: f64, y1: f64, op: &str) -> String { + format!("{x0} {y0} m\n{x1} {y1} L\n({op}) *\n") +} + +/// #779: a straight `(N) *` guide path across the whole canvas, directly on a layer or sublayer, is +/// a ruler guide on that layer, at its place in the document; it leaves no path behind. +#[test] +fn canvas_wide_guide_paths_are_ruler_guides_of_their_layer() { + let body = format!( + "{}{}{RED}{}f\n%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(Sub) Ln\n{}LB\n%AI5_EndLayer--\n", + guide_line(-7885.0, 40.0, 8498.0, 40.0, "N"), + guide_line(25.0, 8587.0, 25.0, -7796.0, "N"), + rect_path(0.0, 0.0, 10.0, 10.0), + guide_line(-7885.0, 90.0, 8498.0, 90.0, "N"), + ); + let doc = read(canvas_stream(&layer(&body)).as_bytes()).unwrap().doc; + let top = &doc.layers[0]; + let kids = top.children().unwrap(); + assert_eq!(kids.len(), 2, "the square and the sublayer"); + assert!(matches!(kids[0].kind, NodeKind::Path { guide: false, .. })); + let sub = &kids[1]; + assert!(sub.children().unwrap().is_empty()); + let want = [ + Guide { vertical: false, pos: 60.0, artboard: None, layer: Some(top.id) }, + Guide { vertical: true, pos: 25.0, artboard: None, layer: Some(top.id) }, + Guide { vertical: false, pos: 10.0, artboard: None, layer: Some(sub.id) }, + ]; + assert_eq!(doc.guides, want); +} + +/// #779: a straight `(N) *` guide path from edge to edge of one artboard is a ruler guide of that +/// artboard. +#[test] +fn artboard_wide_guide_paths_are_ruler_guides_of_their_artboard() { + // The crop marks' artboard, 0 0 200 100. + let doc = read(canvas_stream(&layer(&guide_line(0.0, 30.0, 200.0, 30.0, "N"))).as_bytes()).unwrap().doc; + assert_eq!(doc.guides, [Guide { vertical: false, pos: 70.0, artboard: Some(1), layer: Some(doc.layers[0].id) }]); + assert!(art(&doc).is_empty()); + // The second of two artboards: art space x 400 to 600, y -150 to 0. + let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ + %_/Dictionary :\n%_0 200 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_300 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_/Dictionary :\n%_400 0 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_600 -150 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; + let doc = read_ok(&format!("{boards}{}", layer(&guide_line(500.0, 0.0, 500.0, -150.0, "N")))).doc; + assert_eq!(doc.artboards[1].id, 2); + assert_eq!(doc.guides, [Guide { vertical: true, pos: 500.0, artboard: Some(2), layer: Some(doc.layers[0].id) }]); +} + +/// Guide paths that aren't ruler guides stay guide paths: `(S) *` ones (guides made from objects), +/// even across the whole canvas or an artboard, short ones, slanted ones, and ones in a group. +#[test] +fn other_guide_paths_stay_guide_paths() { + let cases = [ + guide_line(-7885.0, 40.0, 8498.0, 40.0, "S"), + guide_line(20.0, 40.0, 80.0, 40.0, "S"), + guide_line(20.0, 40.0, 80.0, 40.0, "N"), + guide_line(0.0, 30.0, 200.0, 30.0, "S"), + guide_line(-7885.0, -7796.0, 8498.0, 8587.0, "N"), + format!("u\n{}U\n", guide_line(-7885.0, 40.0, 8498.0, 40.0, "N")), + format!("1 Xw\n{}0 Xw\n", guide_line(-7885.0, 40.0, 8498.0, 40.0, "N")), + "-7885 40 m\n306 40 L\n8498 40 L\n(N) *\n".to_string(), + ]; + for body in cases { + let doc = read(canvas_stream(&layer(&body)).as_bytes()).unwrap().doc; + assert!(doc.guides.is_empty(), "{body}"); + assert_eq!(art(&doc).len(), 1, "{body}"); + } +} + +/// The layer whose `Lb` has `ops` as its options (the first one in the file). +fn layer_with(ops: &str) -> Node { + let doc = read_ok(&format!("%AI5_BeginLayer\n{ops} Lb\n(L) Ln\nLB\n%AI5_EndLayer--\n")).doc; + Node::clone(&doc.layers[0]) +} + +/// #779: the template flag four places after the colour index makes a template layer; locking, +/// printing and dimming keep their own flags. In thirteen and fourteen operands the flag before +/// the colour index and the last one change nothing. +#[test] +fn the_template_flag_of_a_layer() { + let l = layer_with("1 1 0 0 1 0 0 4 255 79 255 1 50 0"); + let NodeKind::Layer { template, printable, dim_images, color, .. } = l.kind else { panic!() }; + assert!(template && !printable && l.locked); + assert_eq!((dim_images, color), (Some(50), LayerColor::Preset(4))); + for ops in ["1 1 1 1 1 0 1 5 1 2 3 1 30 0", "1 1 1 1 1 0 0 5 1 2 3 1 30 1", "1 1 1 1 1 0 1 5 1 2 3 1 30"] { + let l = layer_with(ops); + let NodeKind::Layer { template, printable, dim_images, color, .. } = l.kind else { panic!() }; + assert!(template && printable && !l.locked, "{ops}"); + assert_eq!((dim_images, color), (Some(30), LayerColor::Preset(5)), "{ops}"); + } + let l = layer_with("1 1 1 1 0 0 1 0 79 128 255 0 50 0"); + assert!(matches!(l.kind, NodeKind::Layer { template: false, .. })); +} + +/// The colour index is one place earlier in eleven and twelve operands, as in ten, and the twelfth +/// is the dimming percentage; with nine it is one place earlier still. +#[test] +fn layer_options_of_nine_to_twelve_operands() { + let options = |l: Node| match l.kind { + NodeKind::Layer { template, dim_images, color, .. } => (template, dim_images, color), + _ => panic!(), + }; + assert_eq!(options(layer_with("1 1 1 1 1 0 3 1 2 3 1")), (true, Some(50), LayerColor::Preset(3))); + assert_eq!(options(layer_with("1 1 1 1 1 0 3 1 2 3 0 25")), (false, Some(25), LayerColor::Preset(3))); + assert_eq!(options(layer_with("1 1 1 1 1 0 -1 10 20 30 1 25")), (true, Some(25), LayerColor::Custom([10, 20, 30]))); + assert_eq!(options(layer_with("1 1 1 1 0 0 3 1 2 3")), (false, None, LayerColor::Preset(3))); + assert_eq!(options(layer_with("1 1 1 1 0 2 1 2 3")), (false, None, LayerColor::Preset(2))); +} + /// A blend's record as the editing data writes it after `(Adobe Path Blends) 1 0 n XP`: `DCBA`, /// version 1, then (as far as the reader reads it) the number of keys at word 10 and a record of /// six words per key starting with its id. Hand-written; the other words are zero. diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 0ed2f354f9..88524ef58d 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -190,6 +190,7 @@ pub(super) fn build_from( if let Some(a) = doc.artboards.first_mut() { a.rect = rect; } + drop_guides_off_boards(&mut doc); } frame = Some(Frame { page: visible, page_rect, rect, whole, pages: page_moves }); } @@ -933,8 +934,14 @@ fn page_boards<'a>(boards: &'a [vectorcraft_doc::Artboard], first: usize, pages: ((first > 0 || pages.len() == boards.len()) && shown.iter().zip(pages).all(same)).then_some(shown) } -/// Draw `doc`'s layers and artboards `k` times as large, from the origin, with their strokes, -/// effects and pattern tiles. +/// Drops the guides of artboards `doc` no longer has: an artboard guide goes with its artboard. +fn drop_guides_off_boards(doc: &mut Document) { + let kept: Vec<u32> = doc.artboards.iter().map(|a| a.id).collect(); + doc.guides.retain(|g| g.artboard.is_none_or(|id| kept.contains(&id))); +} + +/// Draw `doc`'s layers, artboards and guides `k` times as large, from the origin, with their +/// strokes, effects and pattern tiles. fn scale_document(doc: &mut Document, k: f64) { let a = Affine::scale(k); let scaling = Scaling { strokes: true, effects: Some(vectorcraft_effects::scale_effect), patterns: true, ..Default::default() }; @@ -944,6 +951,9 @@ fn scale_document(doc: &mut Document, k: f64) { for board in &mut doc.artboards { board.rect = a.transform_rect_bbox(board.rect); } + for guide in &mut doc.guides { + guide.pos *= k; + } } /// Marks (in a node's name, until [`prune_unseen`] has looked) the text objects made from the file's diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 9ef30473e4..6ba17640d7 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -1135,6 +1135,46 @@ fn editing_data_in_the_units_of_a_user_unit_page_comes_in_at_the_pages_size() { assert!(near(first(&d, 0), [100.0, 860.0, 140.0, 900.0]), "{:?}", first(&d, 0)); } +/// #779: a `.ai`'s ruler guides come in as guides of their layers, at the page's size when the +/// editing data is in the units of a `UserUnit` page. +#[test] +fn an_ai_files_ruler_guides_come_in_on_their_layers() { + // Across the canvas (16,383 points around the template box's centre, 50 50) at y 40, and + // across the artboard at x 20. + let guides = "-8141.5 40 m\n8241.5 40 L\n(N) *\n20 0 m\n20 100 L\n(N) *\n"; + let art = native(&layer("Jig", true, &format!("{}\n{guides}", square(10, 10)))); + let art = art.replacen("%AI5_NumLayers", "%AI3_TemplateBox: 50 50 50 50\n%AI5_NumLayers", 1); + for k in [1.0, 10.0] { + let page = in_points(pdf_part(10.0, 86.0), k); + let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, k); + assert!(read, "{w:?}"); + let jig = d.layers[0].id; + let want = [ + vectorcraft_doc::Guide { vertical: false, pos: 60.0 * k, artboard: None, layer: Some(jig) }, + vectorcraft_doc::Guide { vertical: true, pos: 20.0 * k, artboard: Some(d.artboards[0].id), layer: Some(jig) }, + ]; + assert_eq!(d.guides, want); + assert_eq!(d.layers[0].children().map_or(0, |c| c.len()), 1, "the square alone"); + } +} + +/// An EPS whose page is its art's box keeps only its first artboard, and the guides of that one: +/// the ruler guides of the artboards left out go with them. +#[test] +fn an_eps_of_its_art_box_keeps_the_guides_of_its_first_artboard() { + let point = |x: u32, y: u32, n: u8| format!("%_{x} {y} /RealPointRelToROrigin\n%_ (PositionPoint{n}) ,\n"); + let board = |x0: u32, x1: u32| format!("%_/Dictionary :\n{}{}%_; ,\n", point(x0, 50, 1), point(x1, 0, 2)); + let array = format!("%_/Array :\n{}{}%_; (ArtboardArray) ,\n", board(0, 50), board(50, 100)); + let boards = format!("%_/Document :\n%_/Dictionary :\n{array}%_; /NotRecorded ,\n%_;\n"); + let guides = "25 0 m\n25 50 L\n(N) *\n75 0 m\n75 50 L\n(N) *\n"; + let art = native(&format!("{boards}{}", layer("Art", true, &format!("{}\n{guides}", square(10, 10))))); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert_eq!(r.document.artboards.len(), 1); + let (board, layer) = (r.document.artboards[0].id, r.document.layers[0].id); + assert_eq!(r.document.guides, [vectorcraft_doc::Guide { vertical: true, pos: 25.0, artboard: Some(board), layer: Some(layer) }]); +} + /// A PDF part read from a `UserUnit` page cropped to the art: the art's box, not the artboard, is /// the page in the editing data's units, so the layers are read at the page's size, with their /// artboard. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 2ca9181e3b..10ad24c792 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -92,7 +92,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri |---|---|---|---|---| | VectorCraft `.vectorcraft` / `.vctemplate` | — | yes | yes | lossless JSON, versioned, save down to v1; property-tested round trips (`format/tests/prop_format.rs`); documents with a lot of path data are written as compact JSON, about a fifth of the size (#1492); a save falls back to a plain fsync and to writing elsewhere and copying in when the folder refuses the usual steps (#1625, #1649, part of #1620; not confirmed on a real network share); the size limits on embedded data also apply to files read from memory (#1783), and saving over a private file on Unix leaves no readable temporary copy beside it (#1778); a dynamic symbol's type (`dynamic` on the symbol) and an instance's appearance changes to its art (`symbol_overrides`, each path at most 64 deep, counted against the object budget) are written only when set, so documents without them save as before (#4938) | | Illustrator template `.ait` | open, save | yes | PDF-compatible only, from Save as Template (`.vctemplate` stays its default) | New from Template opens a saved `.ait` untitled with its layers and art (`tests_pdfedit.rs`) | -| Illustrator `.ai` | open, save | yes (PDF-compatible + editing-data structure, File Info) | PDF-compatible, or legacy version 7 (layers and groups) | see above; no real-file corpus | +| Illustrator `.ai` | open, save | yes (PDF-compatible + editing-data structure with template layers and ruler guides, File Info) | PDF-compatible, or legacy version 7 (layers and groups) | see above; no real-file corpus | | PDF | open, place, save | yes (layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160) | | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CID-keyed CJK type not read; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c592788dfe..4712f97499 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1069,6 +1069,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); in PDF 1.3 to 1.5 files and PDF/X files such a page is written in points. Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). + `.ai` and EPS editing-data import keeps template layers, and opens canvas and artboard ruler guides as ruler guides on their layers; guide objects stay editable guide paths (#779; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A `.ai` saved without PDF compatibility (its PDF part only a placeholder page) is placed and pasted from its editing data, as it opens: File › Place places the art of the layers that show on the first artboard (`file.place`'s `page` places another one), and Paste of it as PDF data (`clipboard.importPdf`) takes every object. `document.open` with `pages` naming every page of such a file opens it the same way (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part; CCITT Group 3 and planar files with extra channels are not read); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). - The Open and Place dialogs list PostScript `.ps` files and `.epsf` files. A `.ps` file opens and places through the EPS reader (its first page), also when its header is only `%!`, as the `ps` format, which exports don't write (Print to PostScript does); an `.epsf` file opens and places as EPS. Copied in a file manager, these files paste as EPS, and `clipboard.importEps` also reads PostScript whose header is only `%!` (`crates/engine/src/cmd/fileio/tests_epsimport.rs`). From c0279473623f98d021e2f524d751c4063ac009c4 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 1 Nov 2026 11:08:47 +0700 Subject: [PATCH 249/260] .ai import: Objects on Path groups open live with their path, Pivot and Rotate Squashed from #5059 onto main. --- .../engine/src/cmd/fileio/tests_aiimport.rs | 27 +++ crates/engine/tests/import_fuzz.rs | 95 ++++++++++ crates/eps/src/import/ai/read.rs | 6 + crates/eps/src/import/ai/read/document.rs | 9 +- crates/eps/src/import/ai/read/on_path.rs | 176 ++++++++++++++++++ crates/eps/src/import/ai/tests.rs | 142 ++++++++++++++ crates/testkit/src/ai.rs | 38 +++- docs/file-format-parity.md | 2 +- docs/target-app-parity.md | 1 + 9 files changed, 491 insertions(+), 5 deletions(-) create mode 100644 crates/eps/src/import/ai/read/on_path.rs diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 6f603b2006..29e0b06801 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -410,6 +410,33 @@ fn an_ai_file_with_a_variable_library_says_its_variables_werent_read() { assert!(notes(&r).is_empty(), "{r}"); } +/// An Objects on Path group in a `.ai` file opens as one: its record names the group's children by +/// their ids in the opened document. +#[test] +fn an_ai_file_opens_its_objects_on_path_group_live() { + let ids = ["9b1c0e7a-0000-4000-8000-000000000001", "9b1c0e7a-0000-4000-8000-000000000002", "9b1c0e7a-0000-4000-8000-000000000003"]; + let options = ai::on_path_options(2, 4, std::f64::consts::FRAC_PI_2, ""); + let record = ai::on_path_record("Adobe Align On Path", &ids, &options); // brand-ok: the record's name in the files + let group = format!( + "0 Ae\nu\n/ConstraintGroup :\n128 /GroupType ,\n;\n0 0 1 0 0 0 1 XA\n10 50 m\n190 50 L\nS\n{}0 1 1 0 1 0 0 Xa\n{}f\n{}{}f\n{}U\n", + ai::on_path_member(ids[0], None, 0.0), + ai::rect(5.0, 45.0, 15.0, 55.0), + ai::on_path_member(ids[1], Some(0), 0.0), + ai::rect(185.0, 45.0, 195.0, 55.0), + ai::on_path_member(ids[2], Some(1), 0.0), + ); + let data = ai::editing_data(200.0, 100.0, &format!("{record}{}", ai::layer("Art", &group))); + let mut s = Session::new(); + let r = open(&mut s, "on-path.ai", &ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 5 45 10 10 re f 185 45 10 10 re f"), json!({})).unwrap(); + assert_eq!(r["format"], json!("ai"), "{r}"); + let doc = &s.doc().unwrap().doc; + let g = &doc.layers[0].children().unwrap()[0]; + let rec = g.extras().objects_on_path.as_deref().expect("an Objects on Path group"); + let kids: Vec<NodeId> = g.children().unwrap().iter().map(|c| c.id).collect(); + assert!(kids.contains(&rec.path) && rec.members.iter().all(|m| kids.contains(&m.id)), "{rec:?} {kids:?}"); + assert_eq!((rec.members.len(), rec.pivot, rec.rotate.round()), (2, 4, 90.0)); +} + /// A page showing only a placeholder line, as a `.ai` saved without PDF compatibility has. const PLACEHOLDER: &str = "BT /F1 12 Tf 10 50 Td (Saved without its PDF part) Tj ET"; diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index b93b28b53b..e09c91e86b 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -2980,6 +2980,101 @@ proptest! { let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); survive("mutated .ai variable library", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; } + + /// A `.ai` whose Objects on Path record and group are damaged or hostile. + #[test] + fn ai_objects_on_path_never_panics(cut in 0usize..4_000, edits in prop::collection::vec((0usize..4_000, prop::sample::select(vec!['0', '1', '9', '-', '.', 'e', ' ', '\n', '(', ')', '/', ':', ';', ',', '%', '_', 'u', 'U'])), 0..12)) { + let text = mutate_text(&on_path_data(&ON_PATH_IDS, &ON_PATH_IDS, 4, "4", "0.5", "", ["0", "1", "2"], true, 0), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + // Trusted, so that the layers read are built whatever the empty page shows. + survive("mutated .ai Objects on Path", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?; + } + + /// Objects on Path records of any shape: ids in any order, repeated or missing, any number of + /// objects, pivots and angles out of range or not finite, spacings, order tags that disagree, + /// groups nested or cut short, and versioned content left open. + #[test] + fn ai_objects_on_path_records_never_panic( + listed in prop::collection::vec(prop::sample::select(ON_PATH_IDS.to_vec()), 0..7), + drawn in prop::collection::vec(prop::sample::select(ON_PATH_IDS.to_vec()), 0..7), + members in 0usize..7, + pivot in prop::sample::select(vec!["0", "4", "8", "9", "-1", "2.5", "1e400"]), + rotation in prop::sample::select(vec!["0", "0.5235987755982988", "-3.2", "1e400", "-1e400", "1e300"]), + spacing in prop::sample::select(vec!["", "%_56.5 /Real (Spacing) ,\n", "%_0 /Bool (IsEquiSpaced) ,\n", "%_1 /Bool (Flip) ,\n"]), + tags in prop::array::uniform3(prop::sample::select(vec!["0", "1", "2", "-1", "7", "(x)", "1e400"])), + versioned in any::<bool>(), + nest in 0usize..3, + cut in 0usize..2_000, + ) { + let data = on_path_data(&listed, &drawn, members, pivot, rotation, spacing, tags, versioned, nest); + let cut_at = data.len().saturating_sub(cut); + let cut_at = (0..=cut_at).rev().find(|i| data.is_char_boundary(*i)).unwrap_or(0); + for data in [data.as_str(), &data[..cut_at]] { + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(data)].concat(); + survive("hostile Objects on Path", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?; + } + } +} + +/// The data [`ai_objects_on_path_never_panics`] damages, as it is, opens with its Objects on Path group. +#[test] +fn the_objects_on_path_fuzz_data_opens_live() { + let text = on_path_data(&ON_PATH_IDS, &ON_PATH_IDS, 4, "4", "0.5", "", ["0", "1", "2"], true, 0); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + // Trusted: the empty page it is read beside isn't compared with its art. + let (doc, warnings, _) = vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0); + let g = doc.layers.first().and_then(|l| l.children()).and_then(|c| c.first()).unwrap_or_else(|| panic!("{warnings:?}")); + assert!(g.extras().objects_on_path.is_some(), "{g:?}"); +} + +/// The ids of the objects of an Objects on Path group in the fuzz cases. +const ON_PATH_IDS: [&str; 5] = ["f-0001", "f-0002", "f-0003", "f-0004", "f-0005"]; + +/// Editing data with an Objects on Path record naming `listed` for `members` objects (Pivot +/// `pivot`, Rotation `rotation`, then the entries `more`) and a group of a path and squares whose +/// dictionaries give the ids `drawn` (the first the path's, the others with the order tags `tags` +/// in turn), inside `nest` more groups, in versioned content with a copy after it when `versioned` +/// is set. +#[allow(clippy::too_many_arguments)] +fn on_path_data( + listed: &[&str], + drawn: &[&str], + members: usize, + pivot: &str, + rotation: &str, + more: &str, + tags: [&str; 3], + versioned: bool, + nest: usize, +) -> String { + use vectorcraft_testkit::ai; + let options = ai::on_path_options(members, 0, 0.0, more) + .replace("%_0 /Int (PivotPosition)", &format!("%_{pivot} /Int (PivotPosition)")) + .replace("%_0 /Real (Rotation)", &format!("%_{rotation} /Real (Rotation)")); + let record = ai::on_path_record("Adobe Align On Path", listed, &options); // brand-ok: the record's name in the files + let mut group = String::from("0 Ae\nu\n/ConstraintGroup :\n128 /GroupType ,\n;\n0 0 1 0 0 0 1 XA\n20 20 m\n100 80 L\n180 20 L\nS\n"); + for (i, id) in drawn.iter().enumerate() { + if i == 0 { + group += &ai::on_path_member(id, None, 0.0); + } else { + let x = 10.0 + 30.0 * i as f64; + let tag = tags.get(i - 1).map_or_else(|| (i - 1).to_string(), |t| t.to_string()); + group += &format!( + "0 1 1 0 1 0 0 Xa\n{}f\n%_/ArtDictionary :\n%_{tag} /Int (ConstraintArtOrderId) ,\n%_({id}) /String (Persistent ID) ,\n%_({rotation}) /String (BBAccumRotation) ,\n%_;\n%_\n", + ai::rect(x, 40.0, x + 10.0, 46.0) + ); + } + } + group += "U\n"; + for _ in 0..nest { + group = format!("0 Ae\nu\n{group}U\n"); + } + let art = if versioned { + format!("%AI17_Begin_Content_if_version_gt:24 14\n{group}%AI17_Alternate_Content\n{group}%AI17_End_Versioned_Content\n") + } else { + group + }; + ai::editing_data(200.0, 100.0, &format!("{record}{}", ai::layer("L", &art))) } /// A `.ai` in PostScript form as other apps write it: the procsets that define its operators named, diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index cb381d6fde..4791274bd7 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -18,6 +18,8 @@ //! app wrote) the bounding box. //! - Variables: the variable library, XML nodes of the `/Document` dictionary, isn't read; a note //! gives how many variables and data sets it has ([`VariableLibrary`]). +//! - Objects on Path: a group whose objects' dictionaries carry ids, and a record of the +//! `/Document` dictionary naming them, read by [`on_path`]. //! - Images: `%AI5_BeginRaster`, the colour space `XN`, `[matrix] bounds w h bits type alpha …` //! and the samples after `XI`. 8-bit CMYK samples keep their ink amounts in a CMYK TIFF, and //! an alpha channel that hides part of such an image becomes its opacity mask; other samples @@ -73,6 +75,7 @@ mod art; mod containers; mod directives; mod document; +mod on_path; mod ops; mod types; @@ -148,6 +151,8 @@ struct Reader<'a> { artboards: Vec<(String, Rect)>, /// The variables and data sets of the `/Document` dictionary's variable library. variables: VariableLibrary, + /// The Objects on Path records of the `/Document` dictionary and the ids of the objects. + on_path: on_path::OnPath, gradients: HashMap<String, Gradient>, gradient_def: Option<GradientDef>, instance: Option<Instance>, @@ -280,6 +285,7 @@ impl<'a> Reader<'a> { cropmarks: None, artboards: Vec::new(), variables: VariableLibrary::default(), + on_path: on_path::OnPath::default(), gradients: HashMap::new(), gradient_def: None, instance: None, diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 7e63b31da5..892a8893cc 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -224,6 +224,7 @@ impl<'a> Reader<'a> { /// An object's dictionary: its name (`AIArtName`, or the XML id `AI10_ArtUID`), and the /// opacity mask it may carry. pub(super) fn art_dictionary(&mut self, o: &Obj) { + self.constraint_art(o); // A blend's key object or spine. if let Some(kind) = o.text("ShapeBlendPathType") && let Some(id) = self.last_object().map(|n| n.id) @@ -278,10 +279,11 @@ impl<'a> Reader<'a> { } } - /// The `/Document` dictionary: the artboards, and how many variables and data sets its variable - /// library has. + /// The `/Document` dictionary: the artboards, how many variables and data sets its variable + /// library has, and its Objects on Path records. pub(super) fn document(&mut self, o: &Obj) { variable_library(o, 0, &mut self.variables); + self.constraint_data(o); let Some(list) = find_entry(o, "ArtboardArray", 0) else { return }; for (i, ab) in list.items().enumerate().take(1000) { let (p1, p2) = (ab.nums("PositionPoint1"), ab.nums("PositionPoint2")); @@ -392,6 +394,7 @@ impl<'a> Reader<'a> { let to_doc = self.ensure_space(); let artboard = self.first_board(); drop_commented_copies(&mut self.doc.layers, &self.hidden_ids); + super::on_path::apply(&mut self.doc, &self.on_path); let mut doc = std::mem::replace(&mut self.doc, Document::new(1.0, 1.0)); let boards: Vec<(String, Rect)> = if self.artboards.is_empty() { artboard.or_else(|| self.bbox_board()).map(|r| vec![("Artboard 1".to_string(), r)]).unwrap_or_default() @@ -549,7 +552,7 @@ fn take_ruler_guides(nodes: &mut [Arc<Node>], pick: &dyn Fn(NodeId) -> Option<Gu } } -fn find_entry<'o>(o: &'o Obj, key: &str, depth: usize) -> Option<&'o Obj> { +pub(super) fn find_entry<'o>(o: &'o Obj, key: &str, depth: usize) -> Option<&'o Obj> { if depth > 8 { return None; } diff --git a/crates/eps/src/import/ai/read/on_path.rs b/crates/eps/src/import/ai/read/on_path.rs new file mode 100644 index 0000000000..909d611315 --- /dev/null +++ b/crates/eps/src/import/ai/read/on_path.rs @@ -0,0 +1,176 @@ +//! Objects on Path groups: a `u` … `U` group whose children's dictionaries carry a `Persistent ID` +//! (the path's with `KeyPath` 1, each object's with its `ConstraintArtOrderId` and the angle of its +//! frame, `BBAccumRotation`: radians, counterclockwise in art space), and a dictionary of the +//! `/Document` dictionary's `Constraint Data` array naming them: `Constraint Name`, `Constraint +//! Verison` 1, `Constraint IDs` (the path's id, then the objects' in their order along the path) +//! and `Constraint Dict` with the options (`PivotPosition` 0 to 8, `Rotation` in radians, +//! `IsEquiSpaced`, `StartRangeFraction`, `ObjectsOrder`, `ConstraintArtData`). The group opens +//! with its [`ObjectsOnPath`] record and its art where it is drawn. A record with options the +//! record can't hold (a `Spacing`, uneven spacing, a start other than 0, keys this reader doesn't +//! know), or one that doesn't match one group exactly, leaves the group a plain group. + +use std::collections::{HashMap, HashSet}; + +use vectorcraft_doc::objects_on_path::{Member, ObjectsOnPath, attachable_path}; + +use super::{Affine, Document, NodeId, NodeKind, Obj, Reader, V}; + +/// The constraint name of an Objects on Path record. +const NAME: &str = "Adobe Align On Path"; // brand-ok: the record's name in the files +/// Most records read from one file. +const MAX_RECORDS: usize = 1000; +/// Most objects one record names. +const MAX_IDS: usize = 10_000; +/// Most objects whose ids are kept. +const MAX_TAGGED: usize = 100_000; +/// The keys of `Constraint Dict` this reader reads; any other one leaves the group plain. +const KNOWN: [&str; 6] = ["StartRangeFraction", "ConstraintArtData", "ObjectsOrder", "PivotPosition", "IsEquiSpaced", "Rotation"]; + +/// An Objects on Path record of the `/Document` dictionary. +#[derive(Debug)] +pub(super) struct Record { + /// The path's id, then the objects' in their order along the path. + ids: Vec<String>, + pivot: u8, + /// Degrees, counterclockwise. + rotate: f64, +} + +/// What an object's dictionary says of its part in an Objects on Path group. +#[derive(Clone, Copy, Debug, Default)] +struct Tag { + key_path: bool, + order: Option<f64>, + /// `BBAccumRotation`: radians, counterclockwise in art space. + angle: Option<f64>, +} + +/// The records and object ids read, for [`apply`]. +#[derive(Debug, Default)] +pub(super) struct OnPath { + records: Vec<Record>, + /// The objects with each `Persistent ID`. + ids: HashMap<String, Vec<NodeId>>, + tags: HashMap<NodeId, Tag>, +} + +/// The first number of entry `key`. +fn num(o: &Obj, key: &str) -> Option<f64> { + o.nums(key).first().copied() +} + +/// An Objects on Path record from a dictionary of the `Constraint Data` array: `None` for another +/// constraint, another version, or options the record can't hold. +fn record(o: &Obj) -> Option<Record> { + if o.text("Constraint Name").as_deref() != Some(NAME) || num(o, "Constraint Verison") != Some(1.0) { + return None; + } + let list = o.obj("Constraint IDs")?; + if list.entries.len() > MAX_IDS || !list.content.is_empty() { + return None; + } + let ids = list.entries.iter().map(|(_, v)| v.iter().find(|v| matches!(v, V::Str(_))).and_then(V::text)).collect::<Option<Vec<String>>>()?; + let members = ids.len().checked_sub(1).filter(|n| *n > 0)?; + let options = o.obj("Constraint Dict")?; + if options.entries.iter().any(|(k, _)| !k.as_deref().is_some_and(|k| KNOWN.contains(&k))) || !options.content.is_empty() { + return None; + } + if num(options, "IsEquiSpaced") != Some(1.0) + || !matches!(options.get("StartRangeFraction").map(|_| num(options, "StartRangeFraction")), None | Some(Some(0.0))) + { + return None; + } + let pivot = num(options, "PivotPosition").filter(|p| p.fract() == 0.0 && (0.0..=8.0).contains(p))? as u8; + let rotate = num(options, "Rotation").map(f64::to_degrees).filter(|r| r.is_finite())?; + let order = options.obj("ObjectsOrder")?; + let order: Vec<f64> = order.entries.iter().flat_map(|(_, v)| v.iter().filter_map(V::num)).collect(); + if order.len() != members || order.iter().enumerate().any(|(i, n)| *n != i as f64) { + return None; + } + let data = options.obj("ConstraintArtData")?; + if data.entries.len() != members || data.items().count() != members || data.items().any(|d| !d.entries.is_empty() || !d.content.is_empty()) { + return None; + } + Some(Record { ids, pivot, rotate }) +} + +impl Reader<'_> { + /// The Objects on Path records of a `Constraint Data` array in the `/Document` dictionary `o`. + pub(super) fn constraint_data(&mut self, o: &Obj) { + let Some(list) = super::document::find_entry(o, "Constraint Data", 0) else { return }; + for d in list.items().take(MAX_RECORDS) { + if self.on_path.records.len() >= MAX_RECORDS { + return; + } + if let Some(r) = record(d) { + self.on_path.records.push(r); + } + } + } + + /// The `Persistent ID` an object's dictionary `o` gives the last object, with its part in an + /// Objects on Path group. + pub(super) fn constraint_art(&mut self, o: &Obj) { + let Some(uuid) = o.text("Persistent ID") else { return }; + let Some(id) = self.last_object().filter(|n| !matches!(n.kind, NodeKind::Layer { .. })).map(|n| n.id) else { return }; + if self.on_path.tags.len() >= MAX_TAGGED { + return; + } + let angle = o.text("BBAccumRotation").and_then(|s| s.trim().parse::<f64>().ok()).filter(|a| a.is_finite()); + let tag = Tag { key_path: num(o, "KeyPath") == Some(1.0), order: num(o, "ConstraintArtOrderId"), angle }; + self.on_path.tags.insert(id, tag); + self.on_path.ids.entry(uuid).or_default().push(id); + } +} + +/// Give each group that a record of `found` names exactly its [`ObjectsOnPath`] record. +pub(super) fn apply(doc: &mut Document, found: &OnPath) { + if found.records.is_empty() { + return; + } + // Where every object with an id is, found in one walk of the tree (setting a record doesn't + // move anything). + let at = doc.index_paths(found.tags.keys().copied()); + for r in &found.records { + // A record that doesn't match leaves the group as it was read. + let _ = apply_one(doc, found, &at, r); + } +} + +fn apply_one(doc: &mut Document, found: &OnPath, at: &HashMap<NodeId, Vec<usize>>, r: &Record) -> Option<()> { + // The one object still in the document with the id `uuid` (a commented copy may have gone). + let resolve = |uuid: &str| -> Option<(NodeId, &Vec<usize>)> { + let mut live = found.ids.get(uuid)?.iter().filter_map(|id| at.get(id).map(|p| (*id, p))); + let one = live.next()?; + live.next().is_none().then_some(one) + }; + let (first, rest) = r.ids.split_first()?; + let (path, path_at) = resolve(first)?; + if !found.tags.get(&path)?.key_path { + return None; + } + let (_, group_at) = path_at.split_last()?; + let mut seen = HashSet::from([path]); + let mut members = Vec::with_capacity(rest.len()); + for (i, uuid) in rest.iter().enumerate() { + let (id, place) = resolve(uuid)?; + let tag = found.tags.get(&id)?; + if !seen.insert(id) || place.split_last().map(|(_, up)| up) != Some(group_at) || tag.key_path || tag.order != Some(i as f64) { + return None; + } + // The frame the object is drawn in: turned by its angle (the document's y points down) + // about the center of its bounds. + let angle = -tag.angle?; + let center = doc.node_at(place)?.geometric_bounds()?.center(); + members.push(Member { id, frame: Affine::rotate_about(angle, center), angle }); + } + let g = doc.node_at(group_at)?; + let NodeKind::Group { children, clip: false } = &g.kind else { return None }; + if g.extras().objects_on_path.is_some() || children.len() != seen.len() || children.iter().any(|c| !seen.contains(&c.id)) { + return None; + } + attachable_path(children.iter().find(|c| c.id == path)?)?; + let on_path = ObjectsOnPath { path, members, pivot: r.pivot, rotate: r.rotate }; + doc.node_mut_at(group_at)?.extras_mut().objects_on_path = Some(Box::new(on_path)); + Some(()) +} diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index f20a07d492..be27b9f5c8 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -2478,3 +2478,145 @@ fn crop_marks_after_the_layers_are_not_art() { assert_eq!(art(&r.doc).len(), 1); assert_eq!(r.doc.layers.len(), 1); } + +/// The name of an Objects on Path record. +const ALIGN_ON_PATH: &str = "Adobe Align On Path"; // brand-ok: the record's name in the files +/// The ids of an Objects on Path group's path and its four objects. +const ON_PATH_IDS: [&str; 5] = [ + "0a6d1e52-0000-4000-8000-000000000001", + "0a6d1e52-0000-4000-8000-000000000002", + "0a6d1e52-0000-4000-8000-000000000003", + "0a6d1e52-0000-4000-8000-000000000004", + "0a6d1e52-0000-4000-8000-000000000005", +]; +const OPEN_PATH: &str = "20 20 m\n100 80 L\n180 20 L\nS\n"; +const CLOSED_PATH: &str = + "40 50 m\n40 66.57 66.86 80 100 80 c\n133.14 80 160 66.57 160 50 c\n160 33.43 133.14 20 100 20 c\n66.86 20 40 33.43 40 50 c\ns\n"; + +/// An Objects on Path group: the stroked `path` with the id `ids[0]`, then a 10 × 6 red square for +/// each other id, 50 pt apart from x 20, whose frame is turned `angle` radians. +fn on_path_group(path: &str, ids: &[&str], angle: f64) -> String { + use vectorcraft_testkit::ai::on_path_member; + let (first, rest) = ids.split_first().unwrap(); + let mut group = format!("0 Ae\nu\n/ConstraintGroup :\n128 /GroupType ,\n;\n0 0 1 0 0 0 1 XA\n2 w\n{path}{}", on_path_member(first, None, 0.0)); + for (i, id) in rest.iter().enumerate() { + let x = 20.0 + 50.0 * i as f64; + group += &format!("{RED}{}f\n{}", rect_path(x, 40.0, x + 10.0, 46.0), on_path_member(id, Some(i), angle)); + } + group + "U\n" +} + +/// The group the layer of `body` holds first, and its Objects on Path record. +fn on_path(body: &str) -> (Arc<Node>, Option<vectorcraft_doc::objects_on_path::ObjectsOnPath>) { + let doc = read_ok(body).doc; + let g = art(&doc).first().cloned().unwrap(); + let rec = g.extras().objects_on_path.as_deref().cloned(); + (g, rec) +} + +/// An Objects on Path group opens as one, with its path, its objects in their order along the path, +/// Pivot and Rotate, and its art where the file draws it; the same art without the record opens as a +/// plain group. +#[test] +fn an_objects_on_path_group_opens_with_its_path_objects_and_options() { + use vectorcraft_testkit::ai::{on_path_options, on_path_record}; + let group = on_path_group(OPEN_PATH, &ON_PATH_IDS, 0.5); + let record = on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &on_path_options(4, 0, std::f64::consts::FRAC_PI_6, "")); + let (g, rec) = on_path(&format!("{record}{}", layer(&group))); + let rec = rec.expect("an Objects on Path group"); + let kids = g.children().unwrap(); + assert_eq!(kids.len(), 5); + let NodeKind::Path { path, .. } = &kids.iter().find(|c| c.id == rec.path).unwrap().kind else { panic!("the path") }; + assert!(path.subpaths.first().is_some_and(|s| !s.closed), "the open path"); + let child = |id| kids.iter().find(|c| c.id == id).unwrap(); + let xs: Vec<f64> = rec.members.iter().map(|m| child(m.id).geometric_bounds().unwrap().x0).collect(); + assert_eq!(xs, [20.0, 70.0, 120.0, 170.0], "the objects in the file's order"); + for m in &rec.members { + let center = child(m.id).geometric_bounds().unwrap().center(); + assert_eq!((m.angle, m.frame), (-0.5, kurbo::Affine::rotate_about(-0.5, center)), "the frame turned counterclockwise"); + } + assert!((rec.rotate - 30.0).abs() < 1e-9, "{}", rec.rotate); + assert_eq!(rec.pivot, 0); + let (plain, none) = on_path(&layer(&group)); + assert!(none.is_none()); + let kinds = |g: &Node| g.children().unwrap().iter().map(|c| c.kind.clone()).collect::<Vec<_>>(); + assert_eq!(kinds(&g), kinds(&plain), "the art stays where it is drawn"); +} + +/// A group on a closed path opens as an Objects on Path group too. +#[test] +fn an_objects_on_path_group_on_a_closed_path_opens_live() { + use vectorcraft_testkit::ai::{on_path_options, on_path_record}; + let record = on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &on_path_options(4, 4, 0.0, "")); + let (g, rec) = on_path(&format!("{record}{}", layer(&on_path_group(CLOSED_PATH, &ON_PATH_IDS, 0.0)))); + let rec = rec.expect("an Objects on Path group"); + let NodeKind::Path { path, .. } = &g.children().unwrap().iter().find(|c| c.id == rec.path).unwrap().kind else { panic!("the path") }; + assert!(path.subpaths.first().is_some_and(|s| s.closed), "the closed path"); + assert_eq!((rec.members.len(), rec.pivot, rec.rotate), (4, 4, 0.0)); +} + +/// A record the group can't be read from, or with options an Objects on Path group doesn't hold, +/// leaves the group a plain group with its art. +#[test] +fn an_objects_on_path_record_that_doesnt_fit_leaves_a_plain_group() { + use vectorcraft_testkit::ai::{on_path_options, on_path_record}; + let [p, a, b, c, d] = ON_PATH_IDS; + let options = |more: &str| on_path_options(4, 4, 0.0, more); + let good = options(""); + let group = on_path_group(OPEN_PATH, &ON_PATH_IDS, 0.0); + assert!(on_path(&format!("{}{}", on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &good), layer(&group))).1.is_some()); + let cases: Vec<(&str, String, String)> = vec![ + ("the path's id is missing", on_path_record(ALIGN_ON_PATH, &["0a6d1e52-ffff", a, b, c, d], &good), group.clone()), + ("an object's id is missing", on_path_record(ALIGN_ON_PATH, &[p, a, b, c], &good), group.clone()), + ("an id twice", on_path_record(ALIGN_ON_PATH, &[p, a, b, b, d], &good), group.clone()), + ("objects out of order", on_path_record(ALIGN_ON_PATH, &[p, b, a, c, d], &good), group.clone()), + ("a spacing", on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &options("%_56.5 /Real (Spacing) ,\n")), group.clone()), + ("an option this reader doesn't know", on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &options("%_1 /Bool (Flip) ,\n")), group.clone()), + ( + "uneven spacing", + on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &good.replace("1 /Bool (IsEquiSpaced)", "0 /Bool (IsEquiSpaced)")), + group.clone(), + ), + ( + "a later start", + on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &good.replace("0 /Real (StartRangeFraction)", "0.25 /Real (StartRangeFraction)")), + group.clone(), + ), + ("a pivot past 8", on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &on_path_options(4, 9, 0.0, "")), group.clone()), + ("another constraint", on_path_record("Some Other Constraint", &ON_PATH_IDS, &good), group.clone()), + ( + "another version", + on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &good).replace("%_1 /Int (Constraint Verison)", "%_2 /Int (Constraint Verison)"), + group.clone(), + ), + ("an object without its angle", on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &good), group.replace("%_(0) /String (BBAccumRotation) ,\n", "")), + ( + "another child in the group", + on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &good), + group.replace("U\n", &format!("{}f\nU\n", rect_path(0.0, 0.0, 5.0, 5.0))), + ), + ("a path without its key", on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &good), group.replace("%_1 /Bool (KeyPath) ,\n", "")), + ]; + for (why, record, group) in cases { + let (g, rec) = on_path(&format!("{record}{}", layer(&group))); + assert!(rec.is_none(), "{why}"); + assert!(matches!(g.kind, NodeKind::Group { clip: false, .. }), "{why}"); + assert!(g.children().unwrap().len() >= 5, "{why}: the art is kept"); + } +} + +/// The copy of the drawn group that follows it as versioned content is skipped: the group opens once, +/// live. +#[test] +fn an_objects_on_path_group_in_versioned_content_opens_once() { + use vectorcraft_testkit::ai::{on_path_options, on_path_record}; + let record = on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &on_path_options(4, 4, 0.0, "")); + let group = on_path_group(OPEN_PATH, &ON_PATH_IDS, 0.0); + let copy = group.replace("/ConstraintGroup :\n128 /GroupType ,\n;\n", ""); + let versioned = format!("%AI17_Begin_Content_if_version_gt:24 14\n{group}%AI17_Alternate_Content\n{copy}%AI17_End_Versioned_Content\n"); + let doc = read_ok(&format!("{record}{}", layer(&versioned))).doc; + let kids = art(&doc); + assert_eq!(kids.len(), 1); + assert_eq!(kids[0].children().unwrap().len(), 5); + assert!(kids[0].extras().objects_on_path.is_some()); +} diff --git a/crates/testkit/src/ai.rs b/crates/testkit/src/ai.rs index c7bbcbff1a..d94423ef6c 100644 --- a/crates/testkit/src/ai.rs +++ b/crates/testkit/src/ai.rs @@ -1,6 +1,7 @@ //! Hand-written Illustrator editing data (the format `vectorcraft_eps`'s reader documents) and the //! EPS, `.ai` and PDF files that carry it, for import tests. Nothing here comes from files another -//! app wrote, except the key names that [`pdf`] uses and the XML node keys of [`variable_library`]. +//! app wrote, except the key names that [`pdf`] uses, the XML node keys of [`variable_library`] and +//! the keys of [`on_path_record`] and [`on_path_member`]. /// Editing data of a `width` × `height` page: header comments (the art's bounding box and the crop /// marks are the page), `body` (setup and layers), the trailer. @@ -77,6 +78,41 @@ pub fn variable_library(variables: &[&str], data_sets: &[&str]) -> String { ) } +/// The document data with an Objects on Path record: a `/Document` dictionary whose `Constraint +/// Data` array holds a record named `name` (version 1) for the objects with the ids `ids` (the +/// path's first), with the options `options` ([`on_path_options`]). +pub fn on_path_record(name: &str, ids: &[&str], options: &str) -> String { + let ids: String = ids.iter().map(|id| format!("%_({id}) /UnicodeString ,\n")).collect(); + format!( + "%AI9_BeginDocumentData\n%_/Document :\n%_/Dictionary :\n%_/Array :\n%_/Dictionary :\n%_1 /Int (Constraint Verison) ,\n\ + %_({name}) /UnicodeString (Constraint Name) ,\n%_/Array :\n{ids}%_; (Constraint IDs) ,\n%_/Dictionary :\n{options}%_; (Constraint Dict) ,\n\ + %_; ,\n%_; (Constraint Data) ,\n%_; /Recorded ,\n%_;\n%AI9_EndDocumentData\n" + ) +} + +/// The options of an Objects on Path record for `members` objects: Pivot `pivot` (0 to 8), +/// Rotate `rotation` (radians), spaced evenly from the start of the path, then `more` entries. +pub fn on_path_options(members: usize, pivot: u8, rotation: f64, more: &str) -> String { + let data = "%_/Dictionary :\n%_; ,\n".repeat(members); + let order: String = (0..members).map(|i| format!("%_{i} /Int ,\n")).collect(); + format!( + "%_0 /Real (StartRangeFraction) ,\n%_/Array :\n{data}%_; (ConstraintArtData) ,\n%_/Array :\n{order}%_; (ObjectsOrder) ,\n\ + %_{pivot} /Int (PivotPosition) ,\n%_1 /Bool (IsEquiSpaced) ,\n%_{rotation} /Real (Rotation) ,\n{more}" + ) +} + +/// The dictionary of an object of an Objects on Path group, with the id `id`: the path's +/// (`order` `None`), or the object's at `order` along the path whose frame is turned `angle` +/// radians counterclockwise. +pub fn on_path_member(id: &str, order: Option<usize>, angle: f64) -> String { + match order { + None => format!("%_/ArtDictionary :\n%_({id}) /String (Persistent ID) ,\n%_1 /Bool (KeyPath) ,\n%_;\n%_\n"), + Some(i) => format!( + "%_/ArtDictionary :\n%_{i} /Int (ConstraintArtOrderId) ,\n%_({id}) /String (Persistent ID) ,\n%_({angle}) /String (BBAccumRotation) ,\n%_;\n%_\n" + ), + } +} + /// A document of 200 × 100 pt with a bit of everything the reader reads. A layer `Art` that shows: /// a group `Pair` (a red square `Red` and a hidden one), a compound path `Ring`, a clipping group /// `Window` (a grey square seen through a smaller one), what [`page_ps`] and [`page_pdf`] draw. A diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 10ad24c792..de7e1cfce0 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -84,7 +84,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. ## Format by format diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4712f97499..7fd540e93a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1063,6 +1063,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In a `.ai` opened from its editing data, a text object on a layer that shows and doesn't print stays on that layer, made from the file's text document, even where the page doesn't draw it (`crates/eps/src/import/tests_native.rs`). Such a `.ai` opens without the PDF part's warnings that text was kept as outlines when no outlined glyphs come in, and a warning counts the text objects that hold the page's type next to glyphs the page has only as outlines, which don't come in (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). Where the art of a `.ai` or EPS opened from its editing data differs a little from the file's page, the warning gives the share of the page that differs away from type. When that share is 0.2% or less, the warning names the type and gives the share of the page that differs where the type is; when all the type is made from the text document, the type's share has a warning of its own beside the art's (`crates/eps/src/import/tests_native.rs`). PDF text opens with every glyph where the file draws it (#722): the font's kerning or none, whichever the file followed, word and character spacing, `TJ` adjustments and horizontal scaling kept per character as tracking, text rise as baseline shift within its line, vertical glyphs narrower than an em centred on their column (`/W2`, `/W`, `/DW`), justified text boxes with word spacing back as justified area type (`tests_text_placement`, fixtures written from ISO 32000-1 §9). A `.ai` or PDF whose editing data holds a variable library opens with a warning that its variables and data sets weren't read, with how many of each it has, whether its layers are read or it comes in as its PDF part (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). + A `.ai` opened from its editing data opens its Objects on Path groups live, with their path, their objects in order along it, Pivot and Rotate, and their art where the file draws it; a group whose spacing has been dragged, or with options an Objects on Path group doesn't hold, opens as a plain group (`crates/eps/src/import/ai/tests.rs`). A PDF page whose `UserUnit` (PDF 1.6) is above 1 opens at its size in points, its numbers times the `UserUnit` (one above 75,000 counts as 75,000), and `document.pdfInfo` gives its size and boxes in points too. A `.ai` whose editing data has its artboards in the units of such a page opens from that data at the page's size, with its layers, and when the layers can't be read its pages still take the artboard layout of the data, scaled the same way (part of #1482). When the editing data of a `.ai` or EPS is for a page of another size than the file's, the warning that its layers weren't read gives both sizes in points, and the scale of the editing data's page to the file's page (1:10 for a tenth of its size) when their sides are in proportion (#2034; `crates/eps/src/import/tests_native.rs`). A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). From af133b1ee4eedd181ffe9c02bfc65fbc428928a7 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 20:15:31 -0700 Subject: [PATCH 250/260] .ai import: envelopes open as live envelopes An envelope in a .ai's editing data opened as its distorted art, with its mesh and contents dropped. It now opens as a live envelope of its contents: a warp with its style, bend, distortions and orientation, a mesh with its points and handles, or a top object with its outline, with Envelope Options, Fidelity and Edit Contents. The envelope replaces its drawn art only when VectorCraft draws it like that art, with a budget so that live envelopes don't make the file open from its PDF part. When the layers still differ too much from the page, the drawn art is put back. An envelope that can't be read, or that draws differently, keeps its drawn art with a note. Envelopes of type keep their drawn art and hidden type as before. --- crates/engine/tests/import_fuzz.rs | 40 ++ crates/eps/src/import/ai.rs | 2 + crates/eps/src/import/ai/envelope.rs | 361 +++++++++++++++ crates/eps/src/import/ai/read.rs | 21 +- crates/eps/src/import/ai/read/containers.rs | 100 +++- crates/eps/src/import/ai/read/document.rs | 14 +- crates/eps/src/import/ai/read/ops.rs | 2 + crates/eps/src/import/ai/read/types.rs | 15 + crates/eps/src/import/ai/style.rs | 6 + crates/eps/src/import/ai/tests.rs | 482 ++++++++++++++++++++ crates/eps/src/import/native.rs | 2 +- crates/eps/src/import/native/build.rs | 47 +- crates/eps/src/import/native/compare.rs | 10 +- crates/eps/src/import/tests_native.rs | 34 ++ docs/target-app-parity.md | 1 + 15 files changed, 1124 insertions(+), 13 deletions(-) create mode 100644 crates/eps/src/import/ai/envelope.rs diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index e09c91e86b..19c6ef93af 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -2954,6 +2954,40 @@ proptest! { survive("mutated EPS editing data", || vectorcraft_eps::import(&bytes).ok().map(|r| r.document))?; } + /// A `.ai` whose envelopes are damaged or hostile: any kind, warp style, options word, + /// Fidelity and grid size, corners out of range or repeated, the contents block cut short. + #[test] + fn ai_envelope_never_panics( + kind in prop::sample::select(vec![0i64, 1, 2, 3, 4, -1, 1 << 40]), + style in prop::sample::select(vec![0i64, 1, 8, 15, 16, -3, i64::MAX]), + word in prop::sample::select(vec![0i64, 1, 131073, 65536, 0x2_0007, 1 << 18, -1, i64::MAX]), + fidelity in prop::sample::select(vec!["50", "0", "100", "101", "-1", "1e308", "nan"]), + size in prop::sample::select(vec!["[1 1]", "[3 2]", "[0 0]", "[51 1]", "[100000 100000]", "[-1 2]", "[1e308 1]"]), + corner in prop::sample::select(vec!["10 10", "1e308 -1e308", "nan 0", "10 10 10 10", "0"]), + edit in 0i64..2, + cut in 0usize..2_000, + edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec!['0', '9', '-', ' ', '\n', '(', ')', '/', ':', ';', ',', '[', ']', '%', '_', 'X', 'u', 'U'])), 0..8), + ) { + use vectorcraft_testkit::ai; + let n = |x: &str, y: &str| format!("%_[0.5 1 {x} {y} {x} {y} 1 {x} {y} 1] /N X#\n"); + let mesh = format!( + "%_/Mesh X!\n%_2 /Version X#\n%_/Cartesian /Type X#\n%_{size} /Size X#\n%_/Data X#\n%_[0 0] /P X#\n{}{}{}%_[{corner}] /N X#\n%_/E X#\n%_[0 0] /P X#\n%_/E X#\n%_/End X!\n", + n("10", "10"), + n("10", "90"), + n("90", "90") + ); + let content = "%_u\n%_1 0 0 1 0 0 Xa\n%_10 10 m\n%_10 90 L\n%_90 90 L\n%_90 10 L\n%_f\n%_U\n"; + let keys = format!( + "%_{word} /Int (AIDeformOptionsKey) ,\n%_{fidelity} /Int (AIDeformFidelityKey) ,\n%_{edit} /Bool (AIDeformEditModeKey) ,\n%_{style} /Int (DeformStyle) ,\n%_0.5 /Real (DeformValue) ,\n%_1 /Bool (Rotate) ,\n" + ); + let art = format!( + "%_u\n{mesh}%_U\n%_/ArtDictionary :\n{keys}%_X=\n{content}%_X+\n%_ (AIDeformArtKey) ,\n%_{kind} /Int (AIDeformStyle) ,\n%_;\n%_\nu\n1 0 0 1 0 0 Xa\n12 12 m\n12 88 L\n88 88 L\nf\nU\n(Adobe Deform Plugin) 1 0 0 XP\n0 0 1 1 0 0 Xa\n0 0 m\n5 5 L\nf\n" + ); + let data = mutate_text(&ai::editing_data(100.0, 100.0, &ai::layer("L", &art)), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat(); + survive("hostile .ai envelope", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + /// A `.ai` whose editing data is damaged or hostile. #[test] fn ai_editing_data_never_panics(cut in 0usize..3_000, edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', ':', ';', '[', ']', '%', 'q', 'Q', 'W', 'u', 'U', 'L', 'k', 'x'])), 0..12), damage in prop::collection::vec((0usize..4_000, any::<u8>()), 0..4)) { @@ -3328,6 +3362,12 @@ fn arb_ai_token() -> impl Strategy<Value = String> { "[1 1] /P X#", "(Adobe Path Blends) 1 0 92 XP", "(Adobe Path Blends) 1 0 999999 XP", + "(Adobe Deform Plugin) 1 0 0 XP", + "%_/ArtDictionary :\n%_131073 /Int (AIDeformOptionsKey) ,\n%_X=\n", + "%_X+\n%_ (AIDeformArtKey) ,\n%_2 /Int (AIDeformStyle) ,\n%_;\n", + "%_1 /Int (AIDeformStyle) ,\n%_9 /Int (DeformStyle) ,\n%_1e308 /Real (DeformValue) ,\n%_;\n", + "%_1 /Bool (AIDeformEditModeKey) ,", + "[1e308 1e308] /Size X#", "\n%44434241010000000000000000000000\n", "\n%0200000041000000000000000000000000000000\n", "\n%4G\n", diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 50fcec2416..c32bf22177 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -18,6 +18,7 @@ //! did before (the printed page, or the PDF), with a warning saying why. mod blend; +mod envelope; mod frames; mod lex; mod mesh; @@ -32,6 +33,7 @@ use std::io::Read as _; use super::lex::find; use crate::ps; +pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN; pub(crate) use frames::text_frames; pub use read::{IMAGE_TOO_LARGE, PaletteSwatches, Structure, artboards, palette, read, variables}; pub(crate) use read::{join_and, slot_frame, slot_of}; diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs new file mode 100644 index 0000000000..33fae9eab3 --- /dev/null +++ b/crates/eps/src/import/ai/envelope.rs @@ -0,0 +1,361 @@ +//! Envelopes from the editing data (`(Adobe Deform Plugin) 1 0 0 XP`), read as live envelopes. +//! +//! What an envelope is and does is Illustrator's public documentation: Make with Warp, Make with +//! Mesh (rows and columns) and Make with Top Object +//! (<https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-objects-with-envelopes.html>), +//! Edit Contents +//! (<https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/edit-the-contents-of-envelopes.html>), +//! Envelope Options +//! (<https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/envelope-panel-options.html>) +//! and the warp styles with their bend and distortions +//! (<https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html>). +//! +//! An envelope is written in three parts. On `%_` lines, a group holding the mesh that shapes it, +//! then its `/ArtDictionary`: Envelope Options as a bit word (`AIDeformOptionsKey`), Fidelity +//! (`AIDeformFidelityKey`), Edit Contents (`AIDeformEditModeKey`), a warp's style (`DeformStyle`, +//! numbered as Effect › Warp lists them), bend and distortions (`DeformValue`, `DeformHoriz`, +//! `DeformVert`, fractions) and orientation (`Rotate`), the contents (`X=` … `X+`, then +//! `(AIDeformArtKey)`) and the kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object). Then the +//! distorted art on plain lines, and the plugin's `XP`. While the contents are edited, the group +//! holds the contents and the dictionary the mesh. A top object's outline is the edge of its +//! one-patch mesh. An envelope whose parts don't read, or that doesn't come out as drawn, keeps its +//! drawn art. + +use std::collections::BTreeMap; +use std::sync::Arc; + +use kurbo::{BezPath, Point, Rect, Vec2}; +use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, default_fidelity}; +use vectorcraft_doc::{Document, ImageBlob, LayerColor, Node, NodeId, NodeKind, PatternDef}; +use vectorcraft_geom::PathData; + +use super::obj::Obj; +use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, compare_scale, differ, differ_in_colour}; + +/// The plugin that writes envelopes. +pub(super) const PLUGIN: &str = "Adobe Deform Plugin"; // brand-ok: the plugin name the files use +/// The note for an envelope that keeps its drawn art. +pub(crate) const DRAWN: &str = "an envelope VectorCraft couldn't read as a live envelope comes in as its drawn art"; +/// The most envelopes waiting for their drawn art at once. +pub(super) const MAX_PENDING: usize = 64; +/// The most envelopes one import draws to check; more keep their drawn art. +pub(super) const MAX_CHECKED: usize = 256; +/// The most rows or columns of a mesh read (Make with Mesh's own limit). +const MAX_GRID: u32 = 50; +/// The bits of the options word that are read: Distort Appearance, Distort Pattern Fills, Distort +/// Linear Gradients, Anti-Alias (set: off) and Preserve Shape Using (set: Clipping Mask). +const KNOWN_BITS: i64 = 0b111 | 1 << 16 | 1 << 17; +/// More of the inked pixels than this differing, each with all its neighbours, and the envelope +/// doesn't come out as drawn. +const MAX_SOLID: f64 = 0.03; +/// More of the inked pixels than this differing at all, and the envelope doesn't come out as drawn. +const MAX_ANY: f64 = 0.1; + +/// The whole number of entry `key`: `None` when it is missing, `Some(None)` when it isn't one. +fn whole(o: &Obj, key: &str) -> Option<Option<i64>> { + o.get(key)?; + let n = o.nums(key); + Some(match n.as_slice() { + [v] if v.is_finite() && v.fract() == 0.0 && v.abs() < 1e12 => Some(*v as i64), + _ => None, + }) +} + +/// A switch (`0` or `1`), off when missing. +fn switch(o: &Obj, key: &str) -> Option<bool> { + match whole(o, key) { + None | Some(Some(0)) => Some(false), + Some(Some(1)) => Some(true), + _ => None, + } +} + +/// Envelope Options and Fidelity. +pub(super) fn options(o: &Obj) -> Option<(EnvelopeOptions, f64)> { + let word = whole(o, "AIDeformOptionsKey")??; + if word < 0 || word & !KNOWN_BITS != 0 { + return None; + } + let fidelity = match whole(o, "AIDeformFidelityKey") { + None => default_fidelity(), + Some(Some(f)) if (0..=100).contains(&f) => f as f64, + Some(_) => return None, + }; + let bit = |n: u32| word & (1 << n) != 0; + let options = EnvelopeOptions { + anti_alias: !bit(16), + preserve_shape: if bit(17) { PreserveShape::ClippingMask } else { PreserveShape::Transparency }, + distort_appearance: bit(0), + distort_pattern_fills: bit(1), + distort_linear_gradients: bit(2), + }; + Some((options, fidelity)) +} + +/// A warp: its style, bend, distortions and orientation. +fn warp(o: &Obj) -> Option<EnvelopeKind> { + let style = whole(o, "DeformStyle")??; + let id = super::style::warp_style(style)?; + let percent = |key: &str| -> Option<f64> { + if o.get(key).is_none() { + return Some(0.0); + } + match o.nums(key).as_slice() { + [v] if v.is_finite() && (-1.0..=1.0).contains(v) => Some(v * 100.0), + _ => None, + } + }; + o.get("DeformValue")?; + let vertical = switch(o, "Rotate")?; + Some(EnvelopeKind::Warp { + style: id.into(), + bend: percent("DeformValue")?, + h: percent("DeformHoriz")?, + v: percent("DeformVert")?, + horizontal: !vertical, + }) +} + +/// The gradient mesh `n` is, or the one its plain groups hold alone. +fn only_mesh(n: &Node) -> Option<&GradientMesh> { + match &n.kind { + NodeKind::Mesh(m) => Some(m), + NodeKind::Group { children, clip: false } => match children.as_slice() { + [c] => only_mesh(c), + _ => None, + }, + _ => None, + } +} + +/// A grid point and its handles. +type GridPoint = (Point, [Vec2; 4]); + +/// The points of mesh `m` as a `rows`×`cols` grid with its first row at the top and its first +/// column at the left (y down), as an envelope's mesh lays them out; `None` for a grid out of range +/// or with points that aren't finite. +fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec<GridPoint>)> { + let (mut rows, mut cols) = (m.rows, m.cols); + if rows == 0 || cols == 0 || rows > MAX_GRID || cols > MAX_GRID { + return None; + } + let len = (rows as usize + 1) * (cols as usize + 1); + if m.points.len() != len { + return None; + } + let finite = |v: Vec2| v.x.is_finite() && v.y.is_finite(); + if !m.points.iter().all(|q| finite(q.p.to_vec2()) && q.handles.iter().all(|h| finite(*h))) { + return None; + } + let mut pts: Vec<GridPoint> = m.points.iter().map(|q| (q.p, q.handles)).collect(); + let at = |pts: &[GridPoint], cols: u32, r: u32, c: u32| pts.get((r * (cols + 1) + c) as usize).map_or(Point::ZERO, |q| q.0); + let remap = |h: [Vec2; 4], slots: [usize; 4]| slots.map(|s| h.get(s).copied().unwrap_or(Vec2::ZERO)); + // Columns that run down the page: the grid goes the other way round. + let along = at(&pts, cols, 0, cols) - at(&pts, cols, 0, 0); + if along.y.abs() > along.x.abs() { + let mut t = Vec::with_capacity(len); + for r in 0..=cols { + for c in 0..=rows { + let (p, h) = pts.get((c * (cols + 1) + r) as usize).copied()?; + // The new next column is the old next row. + let mut slots = [0; 4]; + (slots[H_RIGHT], slots[H_LEFT], slots[H_DOWN], slots[H_UP]) = (H_DOWN, H_UP, H_RIGHT, H_LEFT); + t.push((p, remap(h, slots))); + } + } + (rows, cols) = (cols, rows); + pts = t; + } + if (at(&pts, cols, 0, cols) - at(&pts, cols, 0, 0)).x < 0.0 { + for row in pts.chunks_mut(cols as usize + 1) { + row.reverse(); + for (_, h) in row.iter_mut() { + h.swap(H_RIGHT, H_LEFT); + } + } + } + if (at(&pts, cols, rows, 0) - at(&pts, cols, 0, 0)).y < 0.0 { + let mut flipped: Vec<GridPoint> = pts.chunks(cols as usize + 1).rev().flatten().copied().collect(); + for (_, h) in &mut flipped { + h.swap(H_DOWN, H_UP); + } + pts = flipped; + } + Some((rows, cols, pts)) +} + +/// The outline of an upright grid: its edge, clockwise from the top left corner. +fn outline(rows: u32, cols: u32, pts: &[GridPoint]) -> Option<PathData> { + let at = |r: u32, c: u32| pts.get((r * (cols + 1) + c) as usize).copied(); + // Each edge: from a point by one of its handles to the next point by one of its handles. + type Edge = ((u32, u32), usize, (u32, u32), usize); + let mut ring: Vec<Edge> = vec![]; + ring.extend((0..cols).map(|c| ((0, c), H_RIGHT, (0, c + 1), H_LEFT))); + ring.extend((0..rows).map(|r| ((r, cols), H_DOWN, (r + 1, cols), H_UP))); + ring.extend((1..=cols).rev().map(|c| ((rows, c), H_LEFT, (rows, c - 1), H_RIGHT))); + ring.extend((1..=rows).rev().map(|r| ((r, 0), H_UP, (r - 1, 0), H_DOWN))); + let mut bp = BezPath::new(); + bp.move_to(at(0, 0)?.0); + for ((ar, ac), out, (br, bc), into) in ring { + let ((a, ha), (b, hb)) = (at(ar, ac)?, at(br, bc)?); + bp.curve_to(a + *ha.get(out)?, b + *hb.get(into)?, b); + } + bp.close_path(); + Some(PathData::from_bezpath(&bp)) +} + +/// Has group `n` nothing of its own: no name, lock, transparency, appearance or other properties, +/// shown? +fn plain_group(n: &Node) -> bool { + let plain = Node::new(n.id, NodeKind::Group { children: vec![], clip: false }); + matches!(n.kind, NodeKind::Group { clip: false, .. }) + && (&n.name, n.visible, n.locked, n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) + == (&plain.name, plain.visible, plain.locked, plain.opacity, plain.blend, plain.isolate, plain.knockout, plain.knockout_shape) + && n.appearance == plain.appearance + && n.extras() == plain.extras() +} + +/// `nodes` without the plain group the editing data puts round an envelope's contents. +fn unwrapped(mut nodes: Vec<Node>) -> Vec<Arc<Node>> { + if nodes.len() == 1 + && let Some(n) = nodes.first() + && plain_group(n) + && let Some(n) = nodes.pop() + && let NodeKind::Group { children, .. } = n.kind + { + return children; + } + nodes.into_iter().map(Arc::new).collect() +} + +/// The live envelope of dictionary `o`, the group on `%_` lines before it (`before`) and the art +/// in its `AIDeformArtKey` block (`inner`); `None` where they don't make one. +pub(super) fn live(o: &Obj, before: Option<Node>, inner: Vec<Node>) -> Option<NodeKind> { + let editing = switch(o, "AIDeformEditModeKey")?; + let (options, fidelity) = options(o)?; + let before = before?; + // While the contents are edited, they are the group before the dictionary and the mesh is in it. + let (content, shape): (Vec<Arc<Node>>, Option<&GradientMesh>) = if editing { + let NodeKind::Group { children, clip: false } = &before.kind else { return None }; + let shape = match inner.as_slice() { + [n] => only_mesh(n), + _ => None, + }; + (children.clone(), shape) + } else { + let shape = only_mesh(&before); + (unwrapped(inner), shape) + }; + if content.is_empty() { + return None; + } + let kind = match whole(o, "AIDeformStyle")?? { + 1 => warp(o)?, + 2 => { + let (rows, cols, pts) = upright(shape?)?; + let (points, handles) = pts.into_iter().unzip(); + EnvelopeKind::Mesh { rows, cols, points, handles } + } + 3 => { + let (rows, cols, pts) = upright(shape?)?; + EnvelopeKind::TopObject { path: outline(rows, cols, &pts)? } + } + _ => return None, + }; + Some(NodeKind::Envelope { content, kind: Box::new(kind), fidelity, editing, options, frame: Box::default() }) +} + +/// What the import's documents hold that art refers to: the patterns and image blobs. +pub(super) struct Shared<'a> { + pub(super) patterns: &'a [PatternDef], + pub(super) images: &'a BTreeMap<String, ImageBlob>, +} + +/// A document of `node` alone, on a layer with id `layer`, with the patterns and images it shows. +fn alone(node: &Node, layer: NodeId, shared: &Shared<'_>) -> Document { + let mut doc = Document::new(1.0, 1.0); + let mut l = Node::layer(layer, "", LayerColor::Preset(0)); + if let Some(c) = l.children_mut() { + c.push(Arc::new(node.clone())); + } + doc.layers = vec![Arc::new(l)]; + doc.patterns = shared.patterns.to_vec(); + let mut keys = vec![]; + doc.visit_images(|_, im| keys.push(im.key.clone())); + for k in keys { + if let Some(blob) = shared.images.get(&k) { + doc.images.insert(k, blob.clone()); + } + } + doc +} + +/// How `live` and `drawn`, drawn over `region` at `scale`, differ: the pixels that differ in +/// lightness or colour, those whose neighbours all differ too (where one draws something the other +/// doesn't, not an edge drawn a little apart), and the pixels either inks. `None` when they can't +/// be drawn. +fn differing(live: &Document, drawn: &Document, region: Rect, scale: f64) -> Option<(usize, usize, usize)> { + let x = vectorcraft_render::Renderer::new().render_region(live, region, scale, false); + let y = vectorcraft_render::Renderer::new().render_region(drawn, region, scale, false); + if x.width == 0 || x.height == 0 || x.width != y.width || x.height != y.height { + return None; + } + let (w, h) = (x.width as usize, x.height as usize); + let (xs, ys) = (x.pixels.as_chunks::<4>().0, y.pixels.as_chunks::<4>().0); + let differs: Vec<bool> = xs.iter().zip(ys).map(|(p, q)| differ(p, q) || differ_in_colour(p, q)).collect(); + let inked = xs.iter().zip(ys).filter(|(p, q)| p[3] > 8 || q[3] > 8).count(); + let at = |i: usize, j: usize| differs.get(j * w + i).copied().unwrap_or(false); + let any = differs.iter().filter(|d| **d).count(); + let solid = (1..h.saturating_sub(1)) + .flat_map(|j| (1..w.saturating_sub(1)).map(move |i| (i, j))) + .filter(|&(i, j)| (j - 1..=j + 1).all(|n| (i - 1..=i + 1).all(|m| at(m, n)))) + .count(); + Some((any, solid, inked)) +} + +/// The differences from their drawn art that the live envelopes of one import may add up to, as +/// shares of the page drawn as the page check draws it: half of what that check allows +/// ([`MAX_DIFFERENCE`], [`MAX_SOLID_DIFFERENCE`]), so live envelopes never make the file open from +/// its PDF part instead. +#[derive(Debug, Default)] +pub(super) struct Spent { + any: f64, + solid: f64, +} + +/// Do `live` and `drawn` draw alike: few of the pixels either inks differ, and fewer still where a +/// whole patch differs; and, on `page` (when the file has one), do they differ little enough that +/// with the differences in `spent` the page check still takes the layers' art (it is added to +/// `spent` when they do)? Both are drawn on `layer`, a layer id no other node has. +pub(super) fn drawn_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, page: Option<Rect>, spent: &mut Spent) -> bool { + let (Some(a), Some(b)) = (live.visual_bounds(), drawn.visual_bounds()) else { return false }; + let region = a.union(b).inflate(2.0, 2.0); + if !(region.is_finite() && region.width() > 0.0 && region.height() > 0.0) || region.width().max(region.height()) > 1e6 { + return false; + } + let (x, y) = (alone(live, layer, shared), alone(drawn, layer, shared)); + let Some((any, solid, inked)) = differing(&x, &y, region, compare_scale(region)) else { return false }; + if inked == 0 { + return false; + } + let share = |n: usize| n as f64 / inked as f64; + if share(solid) > MAX_SOLID || share(any) > MAX_ANY { + return false; + } + let Some(page) = page.filter(|p| p.is_finite() && p.width() > 0.0 && p.height() > 0.0) else { return true }; + // Only what is on the page counts, drawn as the page check draws it (about 400 pixels along the + // page's longer side). + let on_page = region.intersect(page); + let scale = compare_scale(page); + if on_page.width() * scale < 1.0 || on_page.height() * scale < 1.0 { + return true; + } + let Some((any, solid, _)) = differing(&x, &y, on_page, scale) else { return false }; + let pixels = (page.width() * scale * page.height() * scale).max(1.0); + let (any, solid) = (spent.any + any as f64 / pixels, spent.solid + solid as f64 / pixels); + if any > MAX_DIFFERENCE / 2.0 || solid > MAX_SOLID_DIFFERENCE / 2.0 { + return false; + } + *spent = Spent { any, solid }; + true +} diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 4791274bd7..cad61b7442 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -84,7 +84,7 @@ use art::preview_png; pub use document::{PaletteSwatches, VariableLibrary, artboards, palette, variables}; pub(crate) use document::{slot_frame, slot_of}; pub use types::IMAGE_TOO_LARGE; -use types::{BLEND_BUDGET, FLIP, Frame, GState, Kind, PatternHead, Place, Raster}; +use types::{BLEND_BUDGET, FLIP, Frame, GState, Kind, PatternHead, PendingEnvelope, Place, Raster}; #[cfg(test)] pub use types::{NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED}; pub(super) use types::{blend_mode, blend_name}; @@ -121,6 +121,9 @@ pub struct Structure { /// move, in its pixels, that places them there (the corner of the box they are written with, /// in place of the canvas point of art space's origin). pub placed_elsewhere: Vec<(NodeId, Affine)>, + /// The live envelopes read from the editing data, by id, with the drawn art each took the place + /// of: the importer puts that art back when the layers with the envelopes don't draw as the page. + pub envelopes_drawn: Vec<(NodeId, Node)>, pub warnings: Vec<String>, } @@ -200,6 +203,17 @@ struct Reader<'a> { blend_record: Option<(usize, Vec<u8>)>, /// How many more objects blends may lay out in this import ([`super::blend::live_blend`]). blend_budget: usize, + /// The group on `%_` lines an envelope's dictionary just took (see [`Reader::drop_envelope_art`]). + envelope_art: Option<Node>, + /// Envelopes waiting for their drawn art, innermost last. + envelopes: Vec<PendingEnvelope>, + /// How many more envelopes this import may draw to check ([`super::envelope::drawn_alike`]). + envelope_checks: usize, + /// How far the live envelopes read so far draw from their drawn art ([`super::envelope::Spent`]). + envelope_spent: super::envelope::Spent, + /// The live envelopes made so far and the drawn art each took the place of + /// ([`Structure::envelopes_drawn`]). + envelopes_drawn: Vec<(NodeId, Node)>, /// A group just ended, its state (`Xy`, `Xd`, `XW`) not yet read. group_ended: bool, /// A gradient mesh just ended (`/End X!`), its own state (`Xy`) not yet read: also after its @@ -318,6 +332,11 @@ impl<'a> Reader<'a> { blend_roles: HashMap::new(), blend_record: None, blend_budget: BLEND_BUDGET, + envelope_art: None, + envelopes: Vec::new(), + envelope_checks: super::envelope::MAX_CHECKED, + envelope_spent: super::envelope::Spent::default(), + envelopes_drawn: Vec::new(), clip_fills: HashSet::new(), looks: HashSet::new(), ruler_guides: HashMap::new(), diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 929f5a0cc9..8d69d8114e 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -1,6 +1,6 @@ use super::document::slot_of; use super::ops::{paints_apart, path_rule}; -use super::types::{Frame, GState, Kind, MAX_DEPTH, MAX_NODES}; +use super::types::{Frame, GState, Kind, MAX_DEPTH, MAX_NODES, PendingEnvelope}; use super::{AppearanceItem, Arc, BezPath, BlendMode, FillRule, HashSet, LayerColor, Node, NodeId, NodeKind, Obj, Paint, PathEl, Rc, Reader, V, obj}; impl<'a> Reader<'a> { @@ -324,17 +324,30 @@ impl<'a> Reader<'a> { "ArtDictionary" => { let envelope = o.get("AIDeformOptionsKey").is_some(); self.art_dictionary(&o); + let before = self.envelope_art.take(); if envelope { let mut slots = vec![]; for child in &children { envelope_text_slots(child, &mut slots); } + let typed = !slots.is_empty() || before.as_ref().is_some_and(has_text_slot); for mut slot in slots { // The editing data keeps the source text inside the envelope's options; // its visible result is the outlined art the PDF page carries. slot.visible = false; self.add(slot, false)?; } + // An envelope of type keeps its drawn art and its type, hidden, as above: the + // type is filled in after reading, which the envelope can't wait for. + if typed { + return Ok(()); + } + if self.envelopes.len() >= crate::import::ai::envelope::MAX_PENDING { + self.warn(crate::import::ai::envelope::DRAWN); + } else { + let siblings = self.frames.last().map_or(0, |f| f.children.len()); + self.envelopes.push(PendingEnvelope { obj: *o, before, inner: children, depth: self.frames.len(), siblings }); + } } } "Document" => self.document(&o), @@ -467,7 +480,8 @@ impl<'a> Reader<'a> { /// envelope's dictionary. It holds the mesh that shapes the envelope, or, while the envelope's /// contents are being edited, those contents (the mesh then is in the dictionary); either way the /// distorted art follows on plain lines. The source text in the contents stays, hidden, as the - /// dictionary's does. Whether it was dropped. + /// dictionary's does. The group is kept in [`Reader::envelope_art`] for the envelope to be made + /// of. Whether it was dropped. pub(super) fn drop_envelope_art(&mut self) -> bool { let Some(n) = self.last_object() else { return false }; let id = n.id; @@ -483,6 +497,7 @@ impl<'a> Reader<'a> { slot.visible = false; f.children.push(slot); } + self.envelope_art = Some(group); } self.hidden_ids.remove(&id); self.after_object = false; @@ -543,6 +558,87 @@ impl<'a> Reader<'a> { // The blend's own state block follows its record, as a group's follows its end. self.after_object = true; } + + /// An envelope's plugin `XP`: the envelope whose dictionary was read last in this container + /// and its drawn art, the one object read since, become one live envelope, or, where they + /// can't, the drawn art stays (see [`crate::import::ai::envelope`]). Envelopes left waiting + /// in containers that closed keep their drawn art. + pub(super) fn end_envelope(&mut self) { + let depth = self.frames.len(); + while self.envelopes.last().is_some_and(|p| p.depth > depth) { + self.envelopes.pop(); + self.warn(crate::import::ai::envelope::DRAWN); + } + if self.envelopes.last().is_none_or(|p| p.depth != depth) { + return; + } + let Some(p) = self.envelopes.pop() else { return }; + let drawn = self.frames.last().filter(|f| f.children.len() == p.siblings + 1).and_then(|f| f.children.last()); + let Some(drawn) = drawn else { + self.warn(crate::import::ai::envelope::DRAWN); + return; + }; + let live = (self.envelope_checks > 0).then(|| crate::import::ai::envelope::live(&p.obj, p.before, p.inner)).flatten(); + let Some(kind) = live else { + self.warn(crate::import::ai::envelope::DRAWN); + return; + }; + // Objects the reader couldn't read come in as the page's art in their place: the envelope's + // drawn art stays round them. + let mut ids = HashSet::new(); + fn collect(n: &Node, ids: &mut HashSet<NodeId>) { + ids.insert(n.id); + for c in n.children().into_iter().flatten() { + collect(c, ids); + } + } + collect(drawn, &mut ids); + if let NodeKind::Envelope { content, .. } = &kind { + content.iter().for_each(|c| collect(c, &mut ids)); + } + if self.unread.iter().any(|(id, _)| ids.contains(id)) { + self.warn(crate::import::ai::envelope::DRAWN); + return; + } + self.envelope_checks -= 1; + // The drawn art's own properties (name, visibility, lock, transparency, appearance, mask, + // attributes) become the envelope's. + let mut envelope = drawn.clone(); + (envelope.id, envelope.kind) = (self.doc.alloc_id(), kind); + let layer = self.doc.alloc_id(); + let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images }; + let mut shown = envelope.clone(); + (shown.visible, shown.opacity) = (true, 1.0); + let mut plain = drawn.clone(); + (plain.visible, plain.opacity) = (true, 1.0); + let page = self.page_in_doc(); + if !crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent) { + self.warn(crate::import::ai::envelope::DRAWN); + return; + } + // The contents are the envelope's own now, not a copy on `%_` lines. + fn forget(n: &Node, hidden: &mut HashSet<NodeId>) { + hidden.remove(&n.id); + for c in n.children().into_iter().flatten() { + forget(c, hidden); + } + } + forget(&envelope, &mut self.hidden_ids); + if let Some(f) = self.frames.last_mut() + && let Some(slot) = f.children.last_mut() + { + let id = envelope.id; + let drawn = std::mem::replace(slot, envelope); + self.envelopes_drawn.push((id, drawn)); + } + } +} + +/// Does `node` hold a text slot? +fn has_text_slot(node: &Node) -> bool { + let mut slots = vec![]; + envelope_text_slots(node, &mut slots); + !slots.is_empty() } /// The source text inside an envelope options dictionary, carried through its containing metadata. diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 892a8893cc..0874ec0959 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -235,7 +235,7 @@ impl<'a> Reader<'a> { // An envelope (a distortion, `AIDeformStyle` / `DeformValue`) is written on `%_` lines as // a group holding the mesh that shapes it (or its contents, while they are being edited); // the distorted art the file's PDF part draws follows on plain lines. That group isn't - // art, so it goes (#2405). + // art, so it goes (#2405), kept aside for the live envelope ([`Reader::end_envelope`]). if (o.get("AIDeformStyle").is_some() || o.get("DeformValue").is_some()) && self.drop_envelope_art() { return; } @@ -317,6 +317,12 @@ impl<'a> Reader<'a> { self.artboards.first().map(|(_, r)| *r).or(self.cropmarks).or_else(|| self.sized_board()) } + /// The page the art is compared with in the document's space, once the art has started. + pub(super) fn page_in_doc(&self) -> Option<Rect> { + let board = self.first_board().or_else(|| self.bbox_board())?; + Some(self.to_doc?.transform_rect_bbox(board)) + } + /// The page of a file that says nothing of its artboard (the legacy format as other apps write /// it): its art's bounding box. fn bbox_board(&self) -> Option<Rect> { @@ -380,6 +386,11 @@ impl<'a> Reader<'a> { } pub(super) fn finish(mut self) -> Result<Structure, String> { + // Envelopes whose plugin never closed them keep their drawn art. + if !self.envelopes.is_empty() { + self.envelopes.clear(); + self.warn(crate::import::ai::envelope::DRAWN); + } if !self.unknown.is_empty() { let ops: Vec<String> = self.unknown.iter().map(|o| format!("`{o}`")).collect(); self.unsupported.insert(format!("operators VectorCraft doesn't know ({})", ops.join(", "))); @@ -491,6 +502,7 @@ impl<'a> Reader<'a> { slot_names: self.slot_names, restyled: self.restyled, placed_elsewhere: self.placed_elsewhere, + envelopes_drawn: self.envelopes_drawn, warnings, }) } diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 9461ecb0cb..7e7b797468 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -298,6 +298,8 @@ impl<'a> Reader<'a> { let len = Self::nums(&vals).last().copied().unwrap_or(0.0); if name == crate::import::ai::blend::PLUGIN && len.is_finite() && len > 0.0 && len <= crate::import::ai::blend::MAX_RECORD as f64 { self.blend_record = Some((len as usize, vec![])); + } else if name == crate::import::ai::envelope::PLUGIN { + self.end_envelope(); } } _ if IGNORED.contains(&w) => {} diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index b73177a37f..3857cbe625 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -166,6 +166,21 @@ pub(super) struct Frame { pub(super) state: Option<(f32, BlendMode, bool, Knockout, bool)>, } +/// An envelope whose dictionary was read, waiting for its drawn art and its plugin's `XP` (see +/// [`super::super::envelope`]). +#[derive(Debug)] +pub(super) struct PendingEnvelope { + pub(super) obj: Obj, + /// The group on `%_` lines before the dictionary. + pub(super) before: Option<Node>, + /// The art in the dictionary's `AIDeformArtKey` block. + pub(super) inner: Vec<Node>, + /// How many frames were open when the dictionary closed, and how many children the innermost + /// had: its drawn art is the one child after them. + pub(super) depth: usize, + pub(super) siblings: usize, +} + /// What a reader of a pattern's definition has of its head, `(name) llx lly urx ury`: the operands /// before its first operator. #[derive(Debug, Default)] diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index 57d7842f23..ede1ae8e93 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -82,6 +82,12 @@ const WARPS: [&str; 15] = [ "warp.twist", ]; +/// The warp style (`arc`, `arcLower`, …) numbered `n` in `DeformStyle`. +pub(super) fn warp_style(n: i64) -> Option<&'static str> { + let id = WARPS.get(usize::try_from(n.checked_sub(1)?).ok()?)?; + id.strip_prefix("warp.") +} + /// A plain style's paint, as the object comes in. #[derive(Clone, Debug, Default, PartialEq)] pub(super) struct ArtStyle { diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index be27b9f5c8..a0a24d8650 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -1997,6 +1997,488 @@ fn an_envelope_s_contents_being_edited_are_not_read_as_art() { assert_eq!(fill(&a[0]).color(), Some(Color::rgb(1.0, 0.0, 0.0))); } +/// `art` on `%_` lines. +fn commented(art: &str) -> String { + art.lines().map(|l| format!("%_{l}\n")).collect() +} + +/// Envelope Options as new envelopes have them (Distort Appearance, Anti-Alias, Clipping Mask), +/// Fidelity 50, the contents not being edited. +const ENVELOPE_KEYS: &str = "131073 /Int (AIDeformOptionsKey) ,\n50 /Int (AIDeformFidelityKey) ,\n0 /Bool (AIDeformEditModeKey) ,\n"; + +/// An envelope as the editing data writes it: on `%_` lines a group holding `before`, then the +/// dictionary with `keys`, the art `block` in its `AIDeformArtKey` block and the kind `kind`; then +/// `drawn` in a group on plain lines, and the plugin's `XP`. +fn envelope_parts(before: &str, keys: &str, block: &str, kind: u32, drawn: &str) -> String { + format!( + "{}%_/ArtDictionary :\n{}%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_{kind} /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\nu\n{drawn}U\n9 () XW\n(Adobe Deform Plugin) 1 0 0 XP\n", + commented(&format!("u\n{before}U\n")), + commented(keys), + commented(block), + ) +} + +/// An envelope of `content` (in the plain group the editing data puts round it) shaped by the mesh +/// `shape`. +fn envelope_of(shape: &str, keys: &str, content: &str, kind: u32, drawn: &str) -> String { + envelope_parts(shape, keys, &format!("u\n{content}U\n9 () XW\n"), kind, drawn) +} + +/// A grid point's place in art space and its handle towards a neighbour. +type MeshAt<'a> = &'a dyn Fn((usize, usize)) -> (f64, f64); +type MeshHandle<'a> = &'a dyn Fn((usize, usize), (usize, usize)) -> (f64, f64); + +/// A grey `/Mesh` of `cols`×`rows` patches (`/P [i j]`, `i` along x, column by column), each +/// corner of patch `(i, j)` at `at`, from the one nearest the origin up, across and down, with its +/// handles towards the next corner and the previous one at `handle`; `anchor`, written after the +/// second corner of the first patch, puts an anchor on its second edge. +fn mesh_text(cols: usize, rows: usize, at: MeshAt<'_>, handle: MeshHandle<'_>, anchor: Option<[f64; 6]>) -> String { + let mut s = format!("/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[{cols} {rows}] /Size X#\n/Data X#\n/DeviceGray /CS X#\n"); + for i in 0..cols { + for j in 0..rows { + s += &format!("[{i} {j}] /P X#\n"); + let (a, b, c, d) = ((i, j), (i, j + 1), (i + 1, j + 1), (i + 1, j)); + for (k, (p, next, prev)) in [(a, b, d), (b, c, a), (c, d, b), (d, a, c)].into_iter().enumerate() { + let ((x, y), (nx, ny), (px, py)) = (at(p), handle(p, next), handle(p, prev)); + s += &format!("[0.8 1 {x} {y} {nx} {ny} 1 {px} {py} 1] /N X#\n"); + if let (1, Some([x, y, ax, ay, bx, by])) = (k, anchor.filter(|_| (i, j) == (0, 0))) { + s += &format!("[{x} {y} {ax} {ay} {bx} {by} 1] /A X#\n"); + } + } + s += "/E X#\n"; + } + } + s + "/End X!\n" +} + +/// A grid in art space, its points `step` apart from (40, 20), handles a third of the way. +fn straight_mesh(cols: usize, rows: usize, step: (f64, f64)) -> String { + let at = move |(i, j): (usize, usize)| (40.0 + i as f64 * step.0, 20.0 + j as f64 * step.1); + let third = move |p: (usize, usize), q: (usize, usize)| { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + }; + mesh_text(cols, rows, &at, &third, None) +} + +/// The red rectangle 40 20 160 80 in art space, which is the same box in the document's. +fn envelope_content() -> String { + format!("{RED}{}f\n", rect_path(40.0, 20.0, 160.0, 80.0)) +} + +/// What envelope `kind` draws of [`envelope_content`]: the rectangle's edges, many points to a +/// side, mapped as VectorCraft maps them, as a red path in art space. +fn drawn_content(kind: &vectorcraft_doc::live::EnvelopeKind) -> String { + let rect = Rect::new(40.0, 20.0, 160.0, 80.0); + let map = vectorcraft_doc::live::envelope_mapper(kind, rect); + let corners = [Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(160.0, 80.0), Point::new(40.0, 80.0)]; + let mut s = RED.to_string(); + for (k, a) in corners.iter().enumerate() { + let b = corners[(k + 1) % 4]; + for t in 0..64 { + let q = map(a.lerp(b, f64::from(t) / 64.0)); + s += &format!("{} {} {}\n", q.x, 100.0 - q.y, if k == 0 && t == 0 { "m" } else { "L" }); + } + } + s + "f\n" +} + +/// The live envelope `n` is: its content, kind, fidelity, editing and options. +fn live_envelope(n: &Node) -> (&[Arc<Node>], &vectorcraft_doc::live::EnvelopeKind, f64, bool, vectorcraft_doc::live::EnvelopeOptions) { + match &n.kind { + NodeKind::Envelope { content, kind, fidelity, editing, options, frame } => { + assert_eq!(**frame, kurbo::Affine::IDENTITY); + (content, kind, *fidelity, *editing, *options) + } + other => panic!("not a live envelope: {other:#?}"), + } +} + +/// A warp's dictionary keys: style number `style`, bend, horizontal and vertical distortion as +/// fractions, and the orientation (vertical with `rotate` 1). +fn warp_keys(style: u32, bend: f64, h: f64, v: f64, rotate: u32) -> String { + format!( + "{ENVELOPE_KEYS}{style} /Int (DeformStyle) ,\n{h} /Real (DeformHoriz) ,\n{bend} /Real (DeformValue) ,\n{v} /Real (DeformVert) ,\n{rotate} /Bool (Rotate) ,\n(Warp) /UnicodeString (DisplayString) ,\n" + ) +} + +/// An envelope made with a warp opens as that live envelope of its contents, its style, bend, +/// distortions (fractions in the file) and orientation read; the warp's drawn art goes. +#[test] +fn a_warp_envelope_opens_live() { + use vectorcraft_doc::live::EnvelopeKind; + for (style, bend, h, v, rotate, id) in + [(1, 0.5, 0.0, 0.0, 0, "arc"), (1, 0.5, -0.2, 0.3, 1, "arc"), (8, 0.5, 0.0, 0.0, 0, "flag"), (15, 0.5, 0.0, 0.0, 0, "twist")] + { + let want = EnvelopeKind::Warp { style: id.into(), bend: bend * 100.0, h: h * 100.0, v: v * 100.0, horizontal: rotate == 0 }; + let body = + envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &warp_keys(style, bend, h, v, rotate), &envelope_content(), 1, &drawn_content(&want)); + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let (content, kind, fidelity, editing, options) = live_envelope(&a[0]); + let EnvelopeKind::Warp { style: s, bend: b, h: dh, v: dv, horizontal } = kind else { panic!("{kind:?}") }; + assert_eq!((s.as_str(), *horizontal), (id, rotate == 0)); + assert!([(*b, bend), (*dh, h), (*dv, v)].iter().all(|(got, f)| (got - f * 100.0).abs() < 1e-9), "{kind:?}"); + assert_eq!((fidelity, editing, options), (50.0, false, vectorcraft_doc::live::EnvelopeOptions::NEW)); + assert_eq!(content.len(), 1, "{content:#?}"); + assert!(matches!(content[0].kind, NodeKind::Path { .. }), "{content:#?}"); + assert_eq!(fill(&content[0]).color(), Some(Color::rgb(1.0, 0.0, 0.0))); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + } +} + +/// Every warp style number reads as its style, in Effect › Warp's order. +#[test] +fn warp_envelopes_read_every_style() { + use vectorcraft_doc::live::EnvelopeKind; + let ids = [ + "arc", + "arcLower", + "arcUpper", + "arch", + "bulge", + "shellLower", + "shellUpper", + "flag", + "wave", + "fish", + "rise", + "fisheye", + "inflate", + "squeeze", + "twist", + ]; + for (n, id) in ids.iter().enumerate() { + let want = EnvelopeKind::Warp { style: (*id).into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true }; + let keys = warp_keys(n as u32 + 1, 0.3, 0.0, 0.0, 0); + let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &keys, &envelope_content(), 1, &drawn_content(&want)))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{id}: {a:#?}"); + assert_eq!(live_envelope(&a[0]).1, &want, "{id}"); + } +} + +/// An envelope made with a mesh opens as a live mesh envelope: its rows and columns, its points +/// row by row from the top left, and each point's four handles, a moved point and an uneven handle +/// included. +#[test] +fn a_mesh_envelope_opens_live_with_its_points_and_handles() { + use vectorcraft_doc::live::{EnvelopeKind, H_DOWN, H_LEFT, H_RIGHT, H_UP}; + // 3 columns 40 apart and 2 rows 30 apart from (40, 20); the inner point (1, 1) moved, and its + // handle towards (2, 1) longer and off the line. + let at = |(i, j): (usize, usize)| if (i, j) == (1, 1) { (90.0, 55.0) } else { (40.0 + i as f64 * 40.0, 20.0 + j as f64 * 30.0) }; + let handle = |p: (usize, usize), q: (usize, usize)| { + if (p, q) == ((1, 1), (2, 1)) { + return (108.0, 62.0); + } + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + }; + let shape = mesh_text(3, 2, &at, &handle, None); + // Row r of the envelope is row 2 - r of the file (art space has y up). + let doc_pt = |(x, y): (f64, f64)| Point::new(x, 100.0 - y); + let mut points = vec![]; + let mut handles = vec![]; + for r in 0..=2usize { + for c in 0..=3usize { + let g = (c, 2 - r); + let p = doc_pt(at(g)); + points.push(p); + let mut h = [kurbo::Vec2::ZERO; 4]; + let towards = |q: Option<(usize, usize)>| q.filter(|q| q.0 <= 3 && q.1 <= 2).map_or(kurbo::Vec2::ZERO, |q| doc_pt(handle(g, q)) - p); + h[H_RIGHT] = towards(Some((g.0 + 1, g.1))); + h[H_LEFT] = towards(g.0.checked_sub(1).map(|i| (i, g.1))); + h[H_UP] = towards(Some((g.0, g.1 + 1))); + h[H_DOWN] = towards(g.1.checked_sub(1).map(|j| (g.0, j))); + handles.push(h); + } + } + let want = EnvelopeKind::Mesh { rows: 2, cols: 3, points: points.clone(), handles: handles.clone() }; + let r = read_ok(&layer(&envelope_of(&shape, ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&want)))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let EnvelopeKind::Mesh { rows, cols, points: got, handles: got_h } = live_envelope(&a[0]).1 else { panic!("{a:#?}") }; + assert_eq!((*rows, *cols, got.len(), got_h.len()), (2, 3, 12, 12)); + for (k, (p, q)) in got.iter().zip(&points).enumerate() { + assert!((*p - *q).hypot() < 1e-6, "point {k}: {p:?}, not {q:?}"); + } + // The moved inner point (row 1, column 1): each of its handles, the uneven one towards the right. + let inner = 4 + 1; + assert!((got[inner] - Point::new(90.0, 45.0)).hypot() < 1e-6, "{:?}", got[inner]); + for slot in [H_RIGHT, H_LEFT, H_DOWN, H_UP] { + assert!((got_h[inner][slot] - handles[inner][slot]).hypot() < 1e-6, "slot {slot}: {:?} vs {:?}", got_h[inner], handles[inner]); + } + assert!((got_h[inner][H_RIGHT] - kurbo::Vec2::new(18.0, -7.0)).hypot() < 1e-6, "{:?}", got_h[inner]); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +/// An envelope made with a top object opens as a live envelope whose top path is the edge of its +/// one-patch mesh, an anchor on the edge included; its contents stay the rectangle. +#[test] +fn a_top_object_envelope_opens_live_with_its_outline() { + use vectorcraft_doc::live::EnvelopeKind; + // Corners (40, 20) (40, 80) (160, 80) (160, 20); the top edge bows up through an anchor at (100, 95). + let at = |(i, j): (usize, usize)| (40.0 + i as f64 * 120.0, 20.0 + j as f64 * 60.0); + let handle = |p: (usize, usize), q: (usize, usize)| match (p, q) { + ((0, 1), (1, 1)) => (60.0, 88.0), + ((1, 1), (0, 1)) => (140.0, 88.0), + _ => { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + } + }; + let shape = mesh_text(1, 1, &at, &handle, Some([100.0, 95.0, 70.0, 95.0, 130.0, 95.0])); + let mut bp = kurbo::BezPath::new(); + bp.move_to((40.0, 20.0)); + bp.curve_to((60.0, 12.0), (70.0, 5.0), (100.0, 5.0)); + bp.curve_to((130.0, 5.0), (140.0, 12.0), (160.0, 20.0)); + bp.curve_to((160.0, 40.0), (160.0, 60.0), (160.0, 80.0)); + bp.curve_to((120.0, 80.0), (80.0, 80.0), (40.0, 80.0)); + bp.curve_to((40.0, 60.0), (40.0, 40.0), (40.0, 20.0)); + bp.close_path(); + let want = EnvelopeKind::TopObject { path: vectorcraft_geom::PathData::from_bezpath(&bp) }; + let r = read_ok(&layer(&envelope_of(&shape, ENVELOPE_KEYS, &envelope_content(), 3, &drawn_content(&want)))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let (content, kind, ..) = live_envelope(&a[0]); + let EnvelopeKind::TopObject { path } = kind else { panic!("{kind:?}") }; + let anchors: Vec<Point> = path.subpaths.iter().flat_map(|s| s.anchors.iter().map(|a| a.p)).collect(); + for p in [(40.0, 20.0), (100.0, 5.0), (160.0, 20.0), (160.0, 80.0), (40.0, 80.0)] { + assert!(anchors.iter().any(|q| (*q - Point::from(p)).hypot() < 1e-6), "{p:?} not in {anchors:?}"); + } + // The curve through the anchor: its handles there run level. + let mid = path.subpaths.iter().flat_map(|s| s.anchors.iter()).find(|a| (a.p - Point::new(100.0, 5.0)).hypot() < 1e-6).unwrap(); + assert!((mid.h_in.y - 5.0).abs() < 1e-6 && (mid.h_out.y - 5.0).abs() < 1e-6, "{mid:?}"); + assert_eq!(content.len(), 1, "{content:#?}"); + assert_eq!(fill(&content[0]).color(), Some(Color::rgb(1.0, 0.0, 0.0))); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +/// Envelope Options come from the options word, Fidelity from its own key. +#[test] +fn an_envelope_reads_its_options_and_fidelity() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, PreserveShape}; + let shape = straight_mesh(1, 1, (120.0, 60.0)); + // A flat 1 × 1 mesh over the box draws the box as it is. + let drawn = drawn_content(&EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(40.0, 80.0), Point::new(160.0, 80.0)], + handles: vec![], + }); + for (word, fidelity, options) in [ + ( + 65536, + 80, + EnvelopeOptions { + anti_alias: false, + preserve_shape: PreserveShape::Transparency, + distort_appearance: false, + distort_linear_gradients: false, + distort_pattern_fills: false, + }, + ), + ( + 0x20007, + 100, + EnvelopeOptions { + anti_alias: true, + preserve_shape: PreserveShape::ClippingMask, + distort_appearance: true, + distort_linear_gradients: true, + distort_pattern_fills: true, + }, + ), + ( + 0x20002, + 0, + EnvelopeOptions { + anti_alias: true, + preserve_shape: PreserveShape::ClippingMask, + distort_appearance: false, + distort_linear_gradients: false, + distort_pattern_fills: true, + }, + ), + ] { + let keys = format!("{word} /Int (AIDeformOptionsKey) ,\n{fidelity} /Int (AIDeformFidelityKey) ,\n0 /Bool (AIDeformEditModeKey) ,\n"); + let r = read_ok(&layer(&envelope_of(&shape, &keys, &envelope_content(), 2, &drawn))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{word}: {a:#?}"); + let (_, _, got_fidelity, _, got) = live_envelope(&a[0]); + assert_eq!((got_fidelity, got), (f64::from(fidelity), options), "{word}"); + } +} + +/// An envelope's contents keep their groups: a group of two rectangles stays that group. +#[test] +fn an_envelope_s_contents_keep_their_groups() { + use vectorcraft_doc::live::EnvelopeKind; + let group = format!( + "u\n{RED}{}f\n{}f\nU\n/ArtDictionary :\n(Pair) /String (AIArtName) ,\n;\n", + rect_path(40.0, 20.0, 90.0, 80.0), + rect_path(110.0, 20.0, 160.0, 80.0) + ); + let mut drawn = RED.to_string(); + drawn += &format!("{}f\n{}f\n", rect_path(40.0, 20.0, 90.0, 80.0), rect_path(110.0, 20.0, 160.0, 80.0)); + let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &group, 2, &drawn))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let (content, kind, ..) = live_envelope(&a[0]); + assert!(matches!(kind, EnvelopeKind::Mesh { rows: 1, cols: 1, .. }), "{kind:?}"); + assert_eq!(content.len(), 1, "{content:#?}"); + assert_eq!(content[0].name.as_deref(), Some("Pair")); + let kids = content[0].children().unwrap(); + assert_eq!(kids.len(), 2, "{kids:#?}"); + assert!(kids.iter().all(|k| matches!(k.kind, NodeKind::Path { .. })), "{kids:#?}"); +} + +/// While an envelope's contents are edited, the contents come first and the mesh is in the +/// dictionary: the envelope opens live all the same, in Edit Contents. +#[test] +fn an_envelope_whose_contents_are_edited_opens_live_in_edit_contents() { + use vectorcraft_doc::live::EnvelopeKind; + let at = |(i, j): (usize, usize)| (40.0 + i as f64 * 120.0, 20.0 + j as f64 * 60.0); + let handle = |p: (usize, usize), q: (usize, usize)| match (p, q) { + ((0, 1), (1, 1)) => (70.0, 95.0), + ((1, 1), (0, 1)) => (130.0, 95.0), + _ => { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + } + }; + let mesh = mesh_text(1, 1, &at, &handle, None); + let mut bp = kurbo::BezPath::new(); + bp.move_to((40.0, 20.0)); + bp.curve_to((70.0, 5.0), (130.0, 5.0), (160.0, 20.0)); + bp.curve_to((160.0, 40.0), (160.0, 60.0), (160.0, 80.0)); + bp.curve_to((120.0, 80.0), (80.0, 80.0), (40.0, 80.0)); + bp.curve_to((40.0, 60.0), (40.0, 40.0), (40.0, 20.0)); + bp.close_path(); + let want = EnvelopeKind::TopObject { path: vectorcraft_geom::PathData::from_bezpath(&bp) }; + let keys = ENVELOPE_KEYS.replace("0 /Bool (AIDeformEditModeKey)", "1 /Bool (AIDeformEditModeKey)"); + let body = envelope_parts(&envelope_content(), &keys, &format!("0 g\n{mesh}"), 3, &drawn_content(&want)); + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let (content, kind, _, editing, _) = live_envelope(&a[0]); + assert!(editing); + assert!(matches!(kind, EnvelopeKind::TopObject { .. }), "{kind:?}"); + assert_eq!(content.len(), 1, "{content:#?}"); + assert!(matches!(content[0].kind, NodeKind::Path { .. }), "{content:#?}"); + assert_eq!(fill(&content[0]).color(), Some(Color::rgb(1.0, 0.0, 0.0))); +} + +/// An envelope that doesn't read (a warp style number past the list, a mesh envelope whose shape +/// isn't a mesh, one whose plugin never closes it) keeps its drawn art, with one note; the art +/// round it is read as ever. +#[test] +fn an_envelope_that_doesnt_read_keeps_its_drawn_art() { + let blue = "0 0 1 1 0 0 1 Xa\n"; + let drawn = format!("{blue}{}f\n", rect_path(40.0, 20.0, 160.0, 80.0)); + let mesh = straight_mesh(1, 1, (120.0, 60.0)); + let cases = [ + envelope_of(&mesh, &warp_keys(99, 0.5, 0.0, 0.0, 0), &envelope_content(), 1, &drawn), + envelope_of(&format!("{}f\n", rect_path(40.0, 20.0, 160.0, 80.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn), + envelope_of(&mesh, ENVELOPE_KEYS, &envelope_content(), 7, &drawn), + envelope_of(&mesh, &ENVELOPE_KEYS.replace("131073", "131081"), &envelope_content(), 2, &drawn), + envelope_of(&mesh, ENVELOPE_KEYS, &envelope_content(), 2, &drawn).replace("(Adobe Deform Plugin) 1 0 0 XP\n", ""), + ]; + for case in cases { + let body = format!("{RED}{}f\n{case}{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0), rect_path(190.0, 0.0, 200.0, 10.0)); + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 3, "{case}\n{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }) && matches!(a[2].kind, NodeKind::Path { .. }), "{a:#?}"); + let NodeKind::Group { children, .. } = &a[1].kind else { panic!("{a:#?}") }; + assert_eq!(fill(&children[0]).color(), Some(Color::rgb(0.0, 0.0, 1.0)), "{case}"); + assert_eq!(r.warnings, [super::envelope::DRAWN], "{case}"); + } +} + +/// An envelope whose contents don't come out as its drawn art (its warp bends them another way) +/// keeps the drawn art. +#[test] +fn an_envelope_that_doesnt_come_out_as_drawn_keeps_its_drawn_art() { + use vectorcraft_doc::live::EnvelopeKind; + let other = EnvelopeKind::Warp { style: "arc".into(), bend: -50.0, h: 0.0, v: 0.0, horizontal: true }; + let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &warp_keys(1, 0.5, 0.0, 0.0, 0), &envelope_content(), 1, &drawn_content(&other)); + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(r.warnings, [super::envelope::DRAWN]); +} + +/// An envelope that comes out close to its drawn art, but with more of the page differing than the +/// page check can take from the live envelopes (its drawn art 2 pt to the side on a 200 × 100 +/// page), keeps the drawn art, so the file still opens from its layers. +#[test] +fn an_envelope_that_differs_from_its_drawn_art_over_the_page_keeps_it() { + let shifted = format!("{RED}{}f\n", rect_path(42.0, 20.0, 162.0, 80.0)); + let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &shifted); + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(r.warnings, [super::envelope::DRAWN]); +} + +/// An envelope whose drawn art holds an object the reader can't read keeps that drawn art, which +/// the page's art replaces. +#[test] +fn an_envelope_whose_drawn_art_holds_an_unread_object_keeps_it() { + let flat = vectorcraft_doc::live::EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(40.0, 80.0), Point::new(160.0, 80.0)], + handles: vec![], + }; + let drawn = format!("{}frobnicate\n", drawn_content(&flat)); + let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(r.unread.iter().map(|(id, _)| *id).collect::<Vec<_>>(), [a[0].id]); + assert_eq!(r.warnings, [super::envelope::DRAWN]); +} + +/// A live envelope takes its drawn art's own properties: its name here. +#[test] +fn a_live_envelope_keeps_its_drawn_art_s_name() { + let flat = vectorcraft_doc::live::EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(40.0, 80.0), Point::new(160.0, 80.0)], + handles: vec![], + }; + let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&flat)) + .replace("U\n9 () XW\n(Adobe Deform Plugin)", "U\n/ArtDictionary :\n(Bent) /String (AIArtName) ,\n;\n9 () XW\n(Adobe Deform Plugin)"); + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + live_envelope(&a[0]); + assert_eq!(a[0].name.as_deref(), Some("Bent")); +} + +/// The same envelope beside the page opens live: what differs off the page isn't counted. +#[test] +fn an_envelope_off_the_page_opens_live_when_it_draws_close_to_its_drawn_art() { + let at = |(i, j): (usize, usize)| (300.0 + i as f64 * 120.0, 20.0 + j as f64 * 60.0); + let third = |p: (usize, usize), q: (usize, usize)| { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + }; + let content = format!("{RED}{}f\n", rect_path(300.0, 20.0, 420.0, 80.0)); + let shifted = format!("{RED}{}f\n", rect_path(302.0, 20.0, 422.0, 80.0)); + let r = read_ok(&layer(&envelope_of(&mesh_text(1, 1, &at, &third, None), ENVELOPE_KEYS, &content, 2, &shifted))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + live_envelope(&a[0]); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + #[test] fn a_gradient_mesh_reads_as_a_patch() { let corner = |rgb: &str, x: i32, y: i32, next: (i32, i32), prev: (i32, i32)| { diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index 8744db0eac..13a746b788 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -40,7 +40,7 @@ use super::ai::{self, Structure, slot_of}; use super::ate::{Story, Texts}; mod build; -mod compare; +pub(super) mod compare; mod layers; mod plan; mod slots; diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 88524ef58d..bf0a8d4a5a 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -71,6 +71,7 @@ pub(super) fn build_from( slot_names, restyled, placed_elsewhere, + envelopes_drawn, warnings, } = structure; // Editing data in the units of the page's user space ([`in_units`]) is compared with the page @@ -311,10 +312,10 @@ pub(super) fn build_from( doc = other; notes.extend(unseen_note(unseen).into_iter().chain(note)); } - _ if trust => { - notes.extend(unseen_note(unseen).into_iter().chain([format!("{why}: they come from its editing data all the same")])) + _ => { + let more = drawn_or_trusted(&frame, &mut view, &mut doc, &envelopes_drawn, ¬es, unseen, trust, why, reflow)?; + notes.extend(more); } - _ => return Err(why), }, } } @@ -755,6 +756,46 @@ fn slot_content( Ok((plan(infos, stories, made, template, to_doc, pages, notes), false)) } +/// The layers `doc` don't draw as the page (`why`), `unseen` text objects of them taken out: the +/// notes to add when `doc` with each live envelope `drawn` lists replaced by the drawn art it took +/// the place of (see [`ai::Structure::envelopes_drawn`]) draws as the page, `doc` then being that; +/// else, with `trust`, the notes for `doc` as it is. An error, `why`, otherwise. The envelope note +/// is added unless `notes` has it. +#[allow(clippy::too_many_arguments)] +fn drawn_or_trusted( + frame: &Frame<'_>, + view: &mut PageView, + doc: &mut Document, + drawn: &[(NodeId, Node)], + notes: &[String], + unseen: usize, + trust: bool, + why: String, + reflow: bool, +) -> Result<Vec<String>, String> { + let unseen_note = |n: usize| (n > 0).then(|| format!("{n} {UNSEEN_TEXT}")); + let mut put_back = doc.clone(); + let mut any = false; + for (id, art) in drawn { + if let Some(n) = put_back.node_mut(*id) { + *n = art.clone(); + any = true; + } + } + if any { + let more = prune_unseen(frame, view, &mut put_back, reflow); + if let Ok(note) = compare(frame, view, &put_back, reflow) { + *doc = put_back; + let envelope = (!notes.iter().any(|n| n == ai::ENVELOPE_DRAWN)).then(|| ai::ENVELOPE_DRAWN.to_string()); + return Ok(envelope.into_iter().chain(unseen_note(unseen + more)).chain(note).collect()); + } + } + if trust { + return Ok(unseen_note(unseen).into_iter().chain([format!("{why}: they come from its editing data all the same")]).collect()); + } + Err(why) +} + /// `doc` with the placed files `placed` lists at their other placement (see /// [`ai::Structure::placed_elsewhere`]): each image's transform followed by its move. `None` when /// no listed image survives replacement. diff --git a/crates/eps/src/import/native/compare.rs b/crates/eps/src/import/native/compare.rs index e8ebed707f..f382059b64 100644 --- a/crates/eps/src/import/native/compare.rs +++ b/crates/eps/src/import/native/compare.rs @@ -47,7 +47,7 @@ const WHITE: u32 = 8; /// Do two pixels look different: in lightness, or one inked (as a light yellow is) where the other /// is white? -pub(super) fn differ(p: &[u8; 4], q: &[u8; 4]) -> bool { +pub(in crate::import) fn differ(p: &[u8; 4], q: &[u8; 4]) -> bool { let (p, q) = (on_white(p), on_white(q)); let (a, b) = (ink(p), ink(q)); lightness(p).abs_diff(lightness(q)) > SAME_PIXEL || (a.min(b) <= WHITE && a.abs_diff(b) > SAME_PIXEL) @@ -59,7 +59,7 @@ const SAME_COLOUR: u32 = 64; /// Are two pixels different colours ([`differ`] also takes a red and a dark red of about the same /// lightness to be alike)? -pub(super) fn differ_in_colour(p: &[u8; 4], q: &[u8; 4]) -> bool { +pub(in crate::import) fn differ_in_colour(p: &[u8; 4], q: &[u8; 4]) -> bool { let (p, q) = (on_white(p), on_white(q)); p.iter().zip(q).any(|(a, b)| a.abs_diff(b) > SAME_COLOUR) } @@ -84,7 +84,7 @@ impl Difference { } /// The scale the comparisons draw a region at: about 400 pixels along its longer side. -fn compare_scale(r: Rect) -> f64 { +pub(in crate::import) fn compare_scale(r: Rect) -> f64 { (400.0 / r.width().max(r.height()).max(1.0)).min(4.0) } @@ -362,14 +362,14 @@ const MARKED: f64 = 0.05; /// More of the page than this differing between the layers' art and the page's own, and the /// layers aren't used. -pub(super) const MAX_DIFFERENCE: f64 = 0.05; +pub(in crate::import) const MAX_DIFFERENCE: f64 = 0.05; /// More than this and the import says so. const NOTABLE_DIFFERENCE: f64 = 0.002; /// More of the page than this where one draws an object that the other doesn't (see /// [`Difference`]), and the layers aren't used: about a centimetre square on a letter page. -pub(super) const MAX_SOLID_DIFFERENCE: f64 = 0.001; +pub(in crate::import) const MAX_SOLID_DIFFERENCE: f64 = 0.001; /// How far (points) the art the layers print may reach past a page that holds it all. const PAST_THE_PAGE: f64 = 1.0; diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 6ba17640d7..94127e8cfd 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -2861,6 +2861,40 @@ fn envelope_options_keep_the_source_text_hidden_under_its_outlined_appearance() assert!(r.warnings.is_empty(), "{:?}", r.warnings); } +/// A live envelope that draws a little apart from its drawn art, in layers that already differ +/// from the page almost as much as the page check takes, would make them differ too much: its +/// drawn art is put back, so the file still opens from its layers. +#[test] +fn a_live_envelope_that_would_tip_the_page_check_keeps_its_drawn_art() { + let rect = |x0: f64, y0: f64, x1: f64, y1: f64| format!("{x0} {y0} m\n{x0} {y1} L\n{x1} {y1} L\n{x1} {y0} L\n{x0} {y0} L\n"); + let hidden = |s: &str| -> String { s.lines().map(|l| format!("%_{l}\n")).collect() }; + let corner = |x: f64, y: f64, nx: f64, ny: f64, px: f64, py: f64| format!("[0.8 1 {x} {y} {nx} {ny} 1 {px} {py} 1] /N X#\n"); + let mesh = format!( + "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[1 1] /Size X#\n/Data X#\n/DeviceGray /CS X#\n[0 0] /P X#\n{}{}{}{}/E X#\n/End X!\n", + corner(20.0, 5.0, 20.0, 35.0, 40.0, 5.0), + corner(20.0, 95.0, 40.0, 95.0, 20.0, 65.0), + corner(80.0, 95.0, 80.0, 65.0, 60.0, 95.0), + corner(80.0, 5.0, 60.0, 5.0, 80.0, 35.0), + ); + let red = "0 1 1 0 1 0 0 Xa\n"; + let envelope = format!( + "{}%_/ArtDictionary :\n%_131073 /Int (AIDeformOptionsKey) ,\n%_50 /Int (AIDeformFidelityKey) ,\n%_0 /Bool (AIDeformEditModeKey) ,\n%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_2 /Int (AIDeformStyle) ,\n%_;\n%_\nu\n{red}{}f\nU\n(Adobe Deform Plugin) 1 0 0 XP\n", + hidden(&format!("u\n{mesh}U\n")), + hidden(&format!("u\n{red}{}f\nU\n", rect(20.0, 5.0, 80.0, 95.0))), + rect(20.5, 5.0, 80.5, 95.0), + ); + // Hairlines the page doesn't draw: about 4.5% of it differs before the envelope. + let lines: String = [3, 6, 9, 12, 15, 85, 88, 91, 94].iter().map(|x| format!("0 0 0 1 K\n0.5 w\n{x} 0 m\n{x} 100 L\nS\n")).collect(); + let art = native(&layer("Art", true, &format!("{lines}{envelope}"))); + let page = "1 0 0 setrgbcolor 20.5 5 moveto 80.5 5 lineto 80.5 95 lineto 20.5 95 lineto closepath fill"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let mut envelopes = 0; + r.document.walk(|n| envelopes += usize::from(matches!(n.kind, NodeKind::Envelope { .. }))); + assert_eq!(envelopes, 0, "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w == crate::import::ai::ENVELOPE_DRAWN), "{:?}", r.warnings); +} + /// An art style section with style `Comic`: a white fill offset and repeated by Transform under a /// red fill with its own blend mode, the characters at the bottom. fn comic_style() -> String { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7fd540e93a..ddcee05b26 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1068,6 +1068,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When the editing data of a `.ai` or EPS is for a page of another size than the file's, the warning that its layers weren't read gives both sizes in points, and the scale of the editing data's page to the file's page (1:10 for a tenth of its size) when their sides are in proportion (#2034; `crates/eps/src/import/tests_native.rs`). A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). + In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type keeps its drawn art, with its type hidden (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); in PDF 1.3 to 1.5 files and PDF/X files such a page is written in points. Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). `.ai` and EPS editing-data import keeps template layers, and opens canvas and artboard ruler guides as ruler guides on their layers; guide objects stay editable guide paths (#779; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). From 427bce12b0b8a90aae750a72ac0ac1349d4a6a8c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 1 Nov 2026 11:08:55 +0700 Subject: [PATCH 251/260] Character: Font Size can measure the cap height, x-height or ICF box Squashed from #5026 onto main. --- crates/cad/Cargo.toml | 5 +- crates/cad/src/scene.rs | 5 +- crates/cad/src/tests.rs | 17 +++ crates/doc/src/lib.rs | 1 + crates/doc/src/text.rs | 2 +- crates/doc/src/text/char_style.rs | 20 +++ crates/doc/src/text/tests.rs | 18 +++ crates/engine/src/cmd/panelcmds.rs | 7 +- crates/engine/src/cmd/textedit.rs | 28 +++- crates/engine/src/cmd/textstyles.rs | 1 + crates/engine/src/cmd/typecmd/area_tests.rs | 91 +++++++++++ crates/eps/src/legacy_ai/tests.rs | 33 ++++ crates/eps/src/legacy_ai/writer.rs | 9 +- crates/svg/src/css.rs | 6 +- crates/svg/src/export/text.rs | 7 +- crates/svg/tests/it/css_rules.rs | 20 +++ crates/svg/tests/it/text_layout.rs | 17 +++ crates/text/src/fontdb/face.rs | 20 +++ crates/text/src/fontdb/lookup.rs | 31 ++++ crates/text/src/layout/driver.rs | 5 +- crates/text/src/shape.rs | 2 + crates/text/src/test_fonts.rs | 80 ++++++++++ crates/text/src/tests.rs | 56 +++++++ crates/ui-egui/src/i18n/bg.tsv | 6 + crates/ui-egui/src/i18n/bs.tsv | 6 + crates/ui-egui/src/i18n/ca.tsv | 6 + crates/ui-egui/src/i18n/cs.tsv | 7 + crates/ui-egui/src/i18n/da.tsv | 6 + crates/ui-egui/src/i18n/de.tsv | 8 + crates/ui-egui/src/i18n/el.tsv | 7 + crates/ui-egui/src/i18n/es.tsv | 7 + crates/ui-egui/src/i18n/fi.tsv | 7 + crates/ui-egui/src/i18n/fr.tsv | 7 + crates/ui-egui/src/i18n/hu.tsv | 7 + crates/ui-egui/src/i18n/id.tsv | 6 + crates/ui-egui/src/i18n/it.tsv | 8 + crates/ui-egui/src/i18n/ja.tsv | 8 + crates/ui-egui/src/i18n/ka.tsv | 7 + crates/ui-egui/src/i18n/ko.tsv | 8 + crates/ui-egui/src/i18n/nl.tsv | 6 + crates/ui-egui/src/i18n/pl.tsv | 7 + crates/ui-egui/src/i18n/pt-br.tsv | 7 + crates/ui-egui/src/i18n/ru.tsv | 7 + crates/ui-egui/src/i18n/sv.tsv | 7 + crates/ui-egui/src/i18n/tests.rs | 11 ++ crates/ui-egui/src/i18n/tr.tsv | 7 + crates/ui-egui/src/i18n/uk.tsv | 8 + crates/ui-egui/src/i18n/vi.tsv | 8 + crates/ui-egui/src/i18n/zh-hans.tsv | 8 + crates/ui-egui/src/i18n/zh-hant.tsv | 8 + crates/ui-egui/src/panels/character.rs | 88 ++++++++--- crates/ui-egui/src/panels/character/tests.rs | 149 ++++++++++++++++++- docs/mcp.md | 21 +++ docs/target-app-parity.md | 1 + 54 files changed, 895 insertions(+), 40 deletions(-) diff --git a/crates/cad/Cargo.toml b/crates/cad/Cargo.toml index 4886d9ea5b..2ea6dea4fb 100644 --- a/crates/cad/Cargo.toml +++ b/crates/cad/Cargo.toml @@ -21,5 +21,6 @@ image = { workspace = true } [dev-dependencies] serde_json = { workspace = true } -# The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine). -vectorcraft-text = { workspace = true, features = ["bundled-fonts"] } +# The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine) +# and in fonts built in code (`vectorcraft_text::test_fonts`). +vectorcraft-text = { workspace = true, features = ["bundled-fonts", "test-fonts"] } diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index 6ae29487a8..ea3b8558d7 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -1062,7 +1062,8 @@ impl<'a> Scene<'a> { } /// Type: glyph outlines (Preserve Appearance, Outline Text, type on a path), else one text - /// entity per run of each line. + /// entity per run of each line, whose height (group 40) is [`CAP_HEIGHT`] times the em size its + /// run is drawn at ([`vectorcraft_text::FontDb::font_heights_resolved`]). fn text(&mut self, n: &Node, t: &TextObject) { let outline = self.o.preserve == Preserve::Appearance || self.o.outline_text || matches!(t.kind, TextKind::OnPath { .. }); if outline { @@ -1074,6 +1075,8 @@ impl<'a> Scene<'a> { if !n.appearance.items.is_empty() { self.warn(TYPE_ITEMS); } + let resolved = vectorcraft_text::FontDb::global().font_heights_resolved(t); + let t = &*resolved; let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); let plain = t.plain_text(); let xf = self.to_dxf * t.xf; diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index ba0a13b768..f1b537b70b 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -906,6 +906,23 @@ fn text_outside_ascii_is_escaped_before_2007() { assert_eq!(text(DxfVersion::R2018), "Größe"); } +/// Type whose font size measures the cap height is written at the em size it is drawn at: 14 pt +/// measuring a 0.7 em cap height is 20 pt type, whose TEXT height is 14. +#[test] +fn a_font_height_reference_is_written_as_the_size_drawn() { + use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; + vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()); + let mut d = text_doc("Plan A", 14.0); + let id = d.layers[0].children().and_then(|c| c.first()).map(|n| n.id).unwrap(); + if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) { + t.runs[0].style.font_family = HEIGHT_FAMILY.into(); + t.runs[0].style.font_height_reference = vectorcraft_doc::FontHeightReference::CapHeight; + } + let editable = export(&d, &DxfOptions { preserve: Preserve::Editability, ..opts(&d) }).unwrap(); + let e = entities(&editable); + assert!((all(&e[0], 40)[0] - 14.0).abs() < 1e-6, "{:?}", all(&e[0], 40)); +} + #[test] fn images_link_png_or_jpeg_files() { let mut png = vec![]; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 26e2bfebf1..8d3b2a8833 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -106,6 +106,7 @@ pub use selection::{AnchorRef, SegmentRef, Selection}; pub use setup::{Background, DocSetup, ExportText, GridSize, Quotes}; pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOptions, SliceSource}; pub use style_libs::StyleLibrary; +pub use text::FontHeightReference; pub use text::{ AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt, JustificationOptions, Justify, Kinsoku, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign, RubyPosition, diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index c1a36e0583..675245b56b 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -15,7 +15,7 @@ mod tabs_lists; pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape}; use char_style::yes; -pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, ScriptMetrics}; +pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, ScriptMetrics}; pub use para_style::{ Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, LeadingModel, Mojikumi, ParaDirection, ParaStyle, SingleWordJustify, diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index dd84912f09..b5bc7e0654 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -116,6 +116,10 @@ pub struct CharStyle { /// these characters are drawn in, whatever digits were typed. #[serde(default, skip_serializing_if = "crate::skip::is_default")] pub digits: Digits, + /// Font height reference (Character panel menu › Show Font Height Options): the height of the + /// font that [`Self::size`] measures, the em box by default. + #[serde(default, rename = "fontHeightReference", skip_serializing_if = "crate::skip::is_default")] + pub font_height_reference: FontHeightReference, /// No Break (Character panel menu): these characters are not broken across lines, including /// at a space or a hyphenation point inside the run. A run longer than the line stays together /// and can overflow it. @@ -130,6 +134,21 @@ pub struct CharStyle { pub language: Option<String>, } +/// What a character's font size measures ([`CharStyle::font_height_reference`]): the em square +/// of the font, the height of its capitals or of its lowercase letters (the cap height and x +/// height of its OS/2 table), or its ideographic character face (ICF, OpenType's `icfb` and +/// `icft` baselines). Layout sets the characters at the em size at which the chosen height equals +/// the font size; with a font that has no such value, the size measures the em box. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum FontHeightReference { + #[default] + EmBox, + CapHeight, + XHeight, + IcfBox, +} + /// The numeral system digits are drawn in ([`CharStyle::digits`]): as typed, or every digit of /// the Western, Arabic-Indic and Eastern Arabic-Indic sets drawn in one of them or in the digits /// of an Indic script. The text keeps the digits that were typed; only the glyphs change (like @@ -380,6 +399,7 @@ impl Default for CharStyle { standard_vertical_roman: false, small_caps: None, digits: Digits::Default, + font_height_reference: FontHeightReference::EmBox, no_break: false, language: None, } diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index bd53024b1c..04deae8ee3 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -60,6 +60,24 @@ fn digits_map_between_the_numeral_systems() { assert_eq!(serde_json::from_value::<CharStyle>(serde_json::to_value(&farsi).unwrap()).unwrap(), farsi); } +/// The font height reference is the em box by default and is saved only when it is another. +#[test] +fn font_height_reference_is_saved_only_when_not_the_em_box() { + let st = CharStyle::default(); + assert_eq!(st.font_height_reference, FontHeightReference::EmBox); + assert!(serde_json::to_value(&st).unwrap().get("fontHeightReference").is_none()); + for (r, key) in + [(FontHeightReference::CapHeight, "capHeight"), (FontHeightReference::XHeight, "xHeight"), (FontHeightReference::IcfBox, "icfBox")] + { + let set = CharStyle { font_height_reference: r, ..CharStyle::default() }; + assert_eq!(serde_json::to_value(&set).unwrap()["fontHeightReference"], key); + assert_eq!(serde_json::from_value::<CharStyle>(serde_json::to_value(&set).unwrap()).unwrap(), set); + } + // Styles written before the attribute existed read as the em box. + let old = serde_json::to_value(&st).unwrap(); + assert_eq!(serde_json::from_value::<CharStyle>(old).unwrap().font_height_reference, FontHeightReference::EmBox); +} + /// Each Indic numeral system draws 0–9 (and the Arabic-Indic sets) as the ten digits of its /// script's block; every system saves under its id, which reads back, and other names are refused. #[test] diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 7f504dcc4f..7934dbe691 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", has_doc, set_format ), @@ -373,6 +373,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { "standardVerticalRoman", "noBreak", "digits", + "fontHeightReference", "language", "fontAxes", "burasagari", @@ -397,6 +398,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { let digits = super::textedit::digits_param(p, C)?; let language = super::textedit::language_param(p, C)?; let font_axes = super::textedit::font_axes_param(p, C)?; + let font_height_reference = super::textedit::font_height_reference_param(p, C)?; let mojikumi = match p.get("mojikumi") { None => None, Some(v) => Some(match v.as_str() { @@ -545,6 +547,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { if let Some(v) = &font_axes { super::textedit::change_font_axes(st, v); } + if let Some(v) = font_height_reference { + st.font_height_reference = v; + } }; s.edit("Character", |d, _| { for id in &ids { diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 8cfdaf47f4..5f5f653a97 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -325,6 +325,7 @@ pub(crate) struct CharChange { /// The language to set: a tag, or `None` for the default. language: Option<Option<String>>, font_axes: Option<AxisChange>, + font_height_reference: Option<vectorcraft_doc::FontHeightReference>, } /// `charDirection: "default"|"leftToRight"|"rightToLeft"` → the Character Direction to set (`None` @@ -452,6 +453,20 @@ pub(crate) fn char_align_param(p: &Value, cmd: &str) -> Result<Option<vectorcraf })) } +/// `fontHeightReference: "emBox"|"capHeight"|"xHeight"|"icfBox"` (Character panel › Set Font Height +/// Reference): the height of the font that the font size measures. +pub(crate) fn font_height_reference_param(p: &Value, cmd: &str) -> Result<Option<vectorcraft_doc::FontHeightReference>> { + use vectorcraft_doc::FontHeightReference; + let Some(v) = p.get("fontHeightReference").filter(|v| !v.is_null()) else { return Ok(None) }; + Ok(Some(match v.as_str() { + Some("emBox") => FontHeightReference::EmBox, + Some("capHeight") => FontHeightReference::CapHeight, + Some("xHeight") => FontHeightReference::XHeight, + Some("icfBox") => FontHeightReference::IcfBox, + _ => return Err(bad(cmd, "`fontHeightReference` must be \"emBox\", \"capHeight\", \"xHeight\" or \"icfBox\"")), + })) +} + fn paint_param(p: &Value, k: &str, cmd: &str) -> Result<Option<Paint>> { match p.get(k) { None | Some(Value::Null) => Ok(None), @@ -523,6 +538,7 @@ impl CharChange { digits: digits_param(p, cmd)?, language: language_param(p, cmd)?, font_axes: font_axes_param(p, cmd)?, + font_height_reference: font_height_reference_param(p, cmd)?, }; if c.size.is_some_and(|v| v <= 0.0) { return Err(bad(cmd, "size must be positive")); @@ -570,6 +586,7 @@ impl CharChange { && self.digits.is_none() && self.language.is_none() && self.font_axes.is_none() + && self.font_height_reference.is_none() } fn localize(&mut self, t: &TextObject, cmd: &str) -> Result<()> { @@ -680,6 +697,9 @@ impl CharChange { if let Some(v) = self.digits { st.digits = v; } + if let Some(v) = self.font_height_reference { + st.font_height_reference = v; + } if let Some(v) = &self.language { st.language.clone_from(v); } @@ -1216,7 +1236,11 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> { match step { Step::Size => st.size = super::typecmd::local_type_value(t, st.size * points + inc, (0.1, 1296.0), false, C)?, Step::Leading => { - let leading = t.para_at(paras.get(i).copied().unwrap_or(0)).effective_leading(st); + // With Auto leading the step starts from the leading the lines are set with: + // the paragraph's Auto Leading share of the em size the font height reference + // gives the characters. An inline graphic keeps its size. + let em = if run.inline.is_some() { st.size } else { vectorcraft_text::FontDb::global().em_size(st, t.vertical) }; + let leading = t.para_at(paras.get(i).copied().unwrap_or(0)).effective_leading(&CharStyle { size: em, ..st.clone() }); st.leading = Some(super::typecmd::local_type_value(t, leading * points + inc, (0.1, 5000.0), false, C)?); } Step::Tracking => st.tracking = (st.tracking + inc).clamp(-1000.0, 10000.0), diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 5995c490d8..ee8ab1d3c5 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -178,6 +178,7 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> { ("standardVerticalRoman", json!(v.standard_vertical_roman)), ("noBreak", json!(v.no_break)), ("digits", json!(v.digits)), + ("fontHeightReference", json!(v.font_height_reference)), ("language", json!(v.language)), ] { m.insert(k.into(), x); diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index 65febdf0bd..4a1200c256 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -1306,6 +1306,97 @@ fn digits_are_a_character_attribute_saved_only_when_set() { assert_eq!(set, [("صفحة ".to_string(), Digits::Default), ("12".to_string(), Digits::Farsi)]); } +/// Font height reference (Character panel › Set Font Height Reference): a character attribute, +/// saved only when not the em box; the type is laid out again at the em size it gives, so 20 pt +/// type measuring a 0.7 em cap height grows by 1 / 0.7, and a leading step from Auto starts at +/// 120% of that em size. +#[test] +fn font_height_reference_is_a_character_attribute_saved_only_when_not_the_em_box() { + use vectorcraft_doc::FontHeightReference as R; + use vectorcraft_text::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, height_font}; + vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hx Hx", "font": HEIGHT_FAMILY, "size": 20})).unwrap()["id"].as_u64().unwrap(); + let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.clone(), + _ => panic!("text"), + }; + let height = |s: &Session| text(s).cached_bounds.unwrap().height(); + let em_box = height(&s); + assert_eq!(text(&s).runs[0].style.font_height_reference, R::EmBox); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + for (key, want) in [("capHeight", R::CapHeight), ("xHeight", R::XHeight), ("icfBox", R::IcfBox), ("emBox", R::EmBox)] { + s.execute("text.setFormat", &json!({"fontHeightReference": key})).unwrap(); + assert!(text(&s).runs.iter().all(|r| r.style.font_height_reference == want && r.style.size == 20.0)); + let saved = serde_json::to_value(&text(&s).runs[0].style).unwrap(); + assert_eq!(saved.get("fontHeightReference").and_then(|v| v.as_str()), (want != R::EmBox).then_some(key)); + } + s.execute("text.setFormat", &json!({"fontHeightReference": "capHeight"})).unwrap(); + let grown = height(&s) / em_box; + assert!((grown - 1000.0 / f64::from(HEIGHT_CAP)).abs() < 1e-6, "{grown}"); + // A leading step from Auto starts at the leading the lines are set with: 120% of the em size + // (the paragraph's Auto Leading). + s.execute("type.step", &json!({"attribute": "leading"})).unwrap(); + let stepped = text(&s).runs[0].style.leading.unwrap(); + assert!((stepped - (1.2 * 20.0 * 1000.0 / f64::from(HEIGHT_CAP) + 2.0)).abs() < 1e-9, "{stepped}"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(text(&s).runs[0].style.font_height_reference, R::EmBox); + assert!((height(&s) - em_box).abs() < 1e-9); + let err = s.execute("text.setFormat", &json!({"fontHeightReference": "baseline"})).unwrap_err().to_string(); + assert!(err.contains("`fontHeightReference` must be"), "{err}"); + // Characters selected with the Type tool: only the range takes it. + s.execute("text.setRangeStyle", &json!({"id": id, "start": 3, "end": 5, "fontHeightReference": "xHeight"})).unwrap(); + let set: Vec<_> = text(&s).runs.iter().map(|r| (r.text.clone(), r.style.font_height_reference)).collect(); + assert_eq!(set, [("Hx ".to_string(), R::EmBox), ("Hx".to_string(), R::XHeight)]); +} + +/// A leading step from Auto starts at the leading each paragraph's lines are set with, its +/// Auto Leading share of the em size: 20 pt type in paragraphs at 120% and 150% steps from 24 pt +/// and from 30 pt. +#[test] +fn a_leading_step_from_auto_starts_at_each_paragraphs_auto_leading() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab\nCd", "size": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setFormat", &json!({"id": id, "start": 3, "end": 5, "autoLeading": 150})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("type.step", &json!({"attribute": "leading"})).unwrap(); + let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else { + panic!("text"); + }; + let leading: Vec<_> = t.runs.iter().map(|r| (r.text.as_str(), r.style.leading)).collect(); + assert_eq!(leading, [("Ab\n", Some(26.0)), ("Cd", Some(32.0))]); +} + +/// An inline graphic keeps its size whatever the font height reference, so a leading step from +/// Auto starts at 120% of that size: 20 pt Cap Height type steps from 120% of 20 / 0.7 pt and +/// the graphic in it from 24 pt. +#[test] +fn a_leading_step_from_auto_starts_at_an_inline_graphics_own_size() { + use vectorcraft_text::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, height_font}; + vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 300, "y": 300, "width": 10, "height": 10})).unwrap(); + s.execute("symbol.new", &json!({"name": "Dot"})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hx", "font": HEIGHT_FAMILY, "size": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.insertInline", &json!({"id": id, "at": 2, "symbol": "Dot"})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("text.setFormat", &json!({"fontHeightReference": "capHeight"})).unwrap(); + s.execute("type.step", &json!({"attribute": "leading"})).unwrap(); + let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else { + panic!("text"); + }; + let leading: Vec<_> = t.runs.iter().map(|r| (r.inline.is_some(), r.style.leading.unwrap())).collect(); + let text = 1.2 * 20.0 * 1000.0 / f64::from(HEIGHT_CAP) + 2.0; + assert_eq!(leading.len(), 2, "{leading:?}"); + assert!(leading.iter().all(|&(inline, l)| (l - if inline { 26.0 } else { text }).abs() < 1e-9), "{leading:?}"); +} + /// The Indic digits (#4942): each set by its id through text.setFormat and text.setRangeStyle, /// saved under it, kept by save and reopen and by character styles; the text stays as typed. #[test] diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index ee55b0a5dc..1c750d983c 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -1017,6 +1017,39 @@ fn variable_font_settings_are_warned_as_left_out() { assert!(String::from_utf8(out.bytes).unwrap().contains("(H\\351llo \\2005\\r) Tx\n"), "still written as text"); } +/// Type whose font size measures the cap height is written at the em size it is drawn at, with +/// no warning: 14 pt measuring a 0.7 em cap height reads back as 20 pt type. +#[test] +fn a_font_height_reference_is_written_as_the_size_drawn() { + use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; + vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()); + let mut doc = typed(); + let id = texts(&doc)[0].0.id; + if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) { + let st = &mut t.runs[0].style; + (st.font_family, st.size) = (HEIGHT_FAMILY.into(), 14.0); + st.font_height_reference = vectorcraft_doc::FontHeightReference::CapHeight; + } + let out = write(&doc); + assert!(!out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES || w == TYPE), "{:?}", out.warnings); + let imported = crate::import(&out.bytes).unwrap(); + let size = texts(&imported.document)[0].1.runs[0].style.size; + assert!((size - 20.0).abs() < 1e-6, "{size}"); +} + +/// Characters with Auto leading are written with their paragraph's Auto Leading share of the +/// size: 18 pt type in paragraphs at 150% is written with 27 pt leading. +#[test] +fn auto_leading_is_written_at_the_paragraphs_share() { + let mut doc = typed(); + let id = texts(&doc)[0].0.id; + if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) { + t.edit_paras(None, |p| p.justification.auto_leading = 150.0); + } + let text = String::from_utf8(write(&doc).bytes).unwrap(); + assert!(text.contains("\n27 0 Tl\n"), "{text}"); +} + /// A legacy `.ai` paragraph has no list: type with a bulleted or numbered list is written as its /// text, with the warning that the bullets and numbers are left out. #[test] diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index b0ba5508fa..9879a51abb 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -719,11 +719,15 @@ impl<'a> Writer<'a> { // ---------- type ---------- - /// Type: a text object when the format can hold it as text, else its outlines. + /// Type: a text object when the format can hold it as text, else its outlines. A run whose + /// font size measures a height other than the em box is written at the em size it is drawn + /// at ([`vectorcraft_text::FontDb::font_heights_resolved`]). fn text(&mut self, t: &TextObject) { if !invertible(t.xf) { return; } + let resolved = vectorcraft_text::FontDb::global().font_heights_resolved(t); + let t = &*resolved; if !self.outline_text { if writable(t) { return self.text_object(t); @@ -849,7 +853,8 @@ impl<'a> Writer<'a> { ps::push_num(&mut self.body, finite(st.tracking, 0.0)); self.line(" Tt"); self.line(if st.kerning.is_none() { "1 TA" } else { "0 TA" }); - ps::push_nums(&mut self.body, &[finite(st.effective_leading(), size * 1.2), finite(p.space_before, 0.0)]); + let leading = st.leading.unwrap_or_else(|| p.justification.auto_leading_for(st.size)); + ps::push_nums(&mut self.body, &[finite(leading, size * 1.2), finite(p.space_before, 0.0)]); self.line("Tl"); } diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index 1785288872..747dae25bb 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -567,8 +567,12 @@ impl Rules<'_> { } } - /// Type: its first character style's font, colour and spacing, its paragraph's alignment. + /// Type: its first character style's font, colour and spacing, its paragraph's alignment. The + /// font size is the em size the characters are drawn at + /// ([`vectorcraft_text::FontDb::font_heights_resolved`]). fn type_art(&mut self, n: &Node, t: &vectorcraft_doc::TextObject, art: &mut Art) { + let resolved = vectorcraft_text::FontDb::global().font_heights_resolved(t); + let t = &*resolved; if matches!(t.kind, TextKind::OnPath { .. }) { art.unsupported("type on a path"); } diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index b94a7449c7..c8b6ced722 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -73,11 +73,14 @@ impl Writer<'_> { /// instances of their symbols (a `<use>` of the symbol's def where it can be shared), all in /// one group carrying the object's transparency. The live text skips their characters and /// places the text after each one; type on a path with inline graphics is written as outlines - /// (a `<textPath>` couldn't leave room for the art). + /// (a `<textPath>` couldn't leave room for the art). A run whose font size measures a height + /// other than the em box is written at the em size it is drawn at + /// ([`vectorcraft_text::FontDb::font_heights_resolved`]). pub(super) fn text_node(&mut self, n: &Node, t: &TextObject) { let doc = self.doc; let resolved = doc.inline_resolved(t); - let t = &*resolved; + let heights = vectorcraft_text::FontDb::global().font_heights_resolved(&resolved); + let t = &*heights; let inline = t.runs.iter().any(|r| r.inline.is_some()); // Ruby is written as outlines with its base text: a reader's <text> can't place it. So are // small capitals, superscript and subscript and tab leaders, which SVG text doesn't draw (#3869). diff --git a/crates/svg/tests/it/css_rules.rs b/crates/svg/tests/it/css_rules.rs index 1c385a095a..88e96cddf5 100644 --- a/crates/svg/tests/it/css_rules.rs +++ b/crates/svg/tests/it/css_rules.rs @@ -148,6 +148,26 @@ fn ellipses_round_fully_and_options_change_units_and_names() { assert!(prop(&r, "width").is_none() && prop(&r, "height").is_none()); } +/// Type whose font size measures the cap height gives the em size it is drawn at: 14 pt measuring +/// a 0.7 em cap height is `font-size: 20px`, and its Auto leading is not written. +#[test] +fn type_gives_the_font_size_it_is_drawn_at() { + use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; + vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()); + let mut d = doc(); + let st = CharStyle { + font_family: HEIGHT_FAMILY.into(), + size: 14.0, + font_height_reference: vectorcraft_doc::FontHeightReference::CapHeight, + ..CharStyle::default() + }; + let n = text(&mut d, "Hello", st); + let id = add(&mut d, n); + let r = one(&d, id, &CssOptions::default()); + assert_eq!(prop(&r, "font-size"), Some("20px")); + assert!(prop(&r, "line-height").is_none()); +} + #[test] fn type_gives_font_properties() { let mut d = doc(); diff --git a/crates/svg/tests/it/text_layout.rs b/crates/svg/tests/it/text_layout.rs index 76c30a1073..3107a1f44a 100644 --- a/crates/svg/tests/it/text_layout.rs +++ b/crates/svg/tests/it/text_layout.rs @@ -176,6 +176,23 @@ fn digits_are_written_as_drawn() { assert!(!text.contains("page 4") && !text.contains("page ٥"), "{svg}"); } +/// A run whose font size measures the cap height is written at the em size it is drawn at: 14 pt +/// measuring a 0.7 em cap height is `font-size="20"`, after a 12 pt run measuring the em box, +/// which takes the `<text>` element's 12. +#[test] +fn font_height_reference_writes_the_size_drawn() { + use vectorcraft_doc::FontHeightReference; + use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; + vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()); + let em_box = CharStyle { font_family: HEIGHT_FAMILY.into(), ..style(12.0) }; + let cap = CharStyle { size: 14.0, font_height_reference: FontHeightReference::CapHeight, ..em_box.clone() }; + let d = area_doc(vec![run("Hx ", em_box), run("Hx", cap)], 280.0, Justify::Left); + let svg = export(&d, &ExportOptions::default()); + assert!(svg.contains("font-size=\"12\" fill"), "{svg}"); + let sizes: Vec<_> = tspans(&svg).iter().map(|t| attr(t, "font-size")).collect(); + assert_eq!(sizes, [None, Some(20.0)], "{svg}"); +} + #[test] fn fewer_tspans_writes_one_per_line() { let bold = CharStyle { font_style: "Bold".into(), ..style(12.0) }; diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index 758acc2c2e..0df8c2e333 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -279,6 +279,26 @@ impl FontFace { *self.icf_margins.get_or_init(|| self.icf_from_base().or_else(|| self.icf_from_glyphs()).unwrap_or_default()) } + /// The height of the face that a font size measures with `reference`, in ems: 1 for the em + /// box; the cap height or x height of its OS/2 table; the height of its ideographic character + /// face ([`Self::icf_margins`]), or across a `vertical` line its width. None for a face whose + /// font has no such value (an OS/2 table without the heights, no ICF), or one outside 0.1 to + /// 2 ems. + pub fn font_height(&self, reference: vectorcraft_doc::FontHeightReference, vertical: bool) -> Option<f64> { + use vectorcraft_doc::FontHeightReference as R; + let units = |v: Option<f32>| v.map(f64::from).map(|v| v / self.upem); + let h = match reference { + R::EmBox => Some(1.0), + R::CapHeight => units(self.skrifa()?.metrics(Size::unscaled(), self.location()).cap_height), + R::XHeight => units(self.skrifa()?.metrics(Size::unscaled(), self.location()).x_height), + R::IcfBox => { + let m = self.icf_margins(); + (m != IcfMargins::default()).then_some(if vertical { 1.0 - m.left - m.right } else { 1.0 - m.top - m.bottom }) + } + }; + h.filter(|h| (0.1..=2.0).contains(h)) + } + /// [`Self::icf_margins`] from the BASE table: the ICF's bottom edge `icfb` (top edge `icft`, else /// as far below the em box top) against the em box `ideo` .. `idtp` (else the OS/2 typographic /// descender, and one em above it); across vertical lines, `icfb` and `icft` of the vertical diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index e01a474931..010f96ffab 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -247,6 +247,37 @@ impl FontDb { Some(self.instance(&face, &st.font_axes)) } + /// The em size characters of style `st` are set at, in `vertical` type or not: its size, or + /// with a font height reference other than the em box ([`vectorcraft_doc::FontHeightReference`]) + /// the size at which its face ([`Self::style_face`]) has that height + /// ([`FontFace::font_height`]). The size itself when the face has no such height. + pub fn em_size(&self, st: &vectorcraft_doc::CharStyle, vertical: bool) -> f64 { + let reference = st.font_height_reference; + if reference == vectorcraft_doc::FontHeightReference::EmBox { + return st.size; + } + self.style_face(st).and_then(|f| f.font_height(reference, vertical)).map_or(st.size, |h| st.size / h) + } + + /// `t` as layout sets it: each run takes its [`Self::em_size`] and the em box as its font + /// height reference; an inline graphic keeps its size. Explicit leading and baseline shift + /// stay in points; Auto leading, tracking and kerning follow the em size. `t` itself when every + /// run measures the em box. + pub fn font_heights_resolved<'a>(&self, t: &'a vectorcraft_doc::TextObject) -> std::borrow::Cow<'a, vectorcraft_doc::TextObject> { + use vectorcraft_doc::FontHeightReference; + if t.runs.iter().all(|r| r.style.font_height_reference == FontHeightReference::EmBox) { + return std::borrow::Cow::Borrowed(t); + } + let mut out = t.clone(); + for r in &mut out.runs { + if r.inline.is_none() { + r.style.size = self.em_size(&r.style, t.vertical); + } + r.style.font_height_reference = FontHeightReference::EmBox; + } + std::borrow::Cow::Owned(out) + } + /// `face` with the axis settings `axes` (by tag, in the axes' own units) in place of its own, /// each clamped to its axis's range: its outlines, metrics and advances taken there, and its /// file embedded instanced there. Tags the font has no axis for are left out. `face` itself diff --git a/crates/text/src/layout/driver.rs b/crates/text/src/layout/driver.rs index 4cb518d0d5..58ca0a525c 100644 --- a/crates/text/src/layout/driver.rs +++ b/crates/text/src/layout/driver.rs @@ -106,8 +106,11 @@ pub fn decorations(layout: &TextLayout, db: &FontDb, t: &TextObject) -> Vec<(usi const SHRINK_PASSES: usize = 11; /// Lay out a text object with explicit options (area type rows/columns, inset, first baseline, -/// fit, composer, OpenType features). +/// fit, composer, OpenType features). Each run is set at the em size its font height reference +/// gives it ([`FontDb::font_heights_resolved`]). pub fn layout_with(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLayout { + let resolved = db.font_heights_resolved(t); + let t = &*resolved; let first = layout_once(db, t, opts); match (opts.fit.min_scale(), &t.kind) { (Some(min), TextKind::Area { .. }) if first.overflow => shrink_to_fit(db, t, opts, min).unwrap_or(first), diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index e04c6c6dca..6f22baa7fd 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -718,6 +718,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { tate_chu_yoko, standard_vertical_roman: _, digits, + font_height_reference, no_break, language, } = a; @@ -735,6 +736,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { && *proportional_metrics == b.proportional_metrics && *tate_chu_yoko == b.tate_chu_yoko && *digits == b.digits + && *font_height_reference == b.font_height_reference && *no_break == b.no_break && *language == b.language && ligatures_suppressed_by(*tracking) == ligatures_suppressed_by(b.tracking) diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 817f1689f4..a4e0fcde6a 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -254,6 +254,86 @@ pub fn vertical_font(vorg: bool) -> Option<Vec<u8>> { Some(builder.build()) } +/// The family of [`height_font`] with its heights. +pub const HEIGHT_FAMILY: &str = "Heighttest Sans"; + +/// The family of [`height_font`] without them. +pub const HEIGHTLESS_FAMILY: &str = "Heightlesstest Sans"; + +/// The cap height and x height [`height_font`] gives, in font units (1,000 to the em). +pub const HEIGHT_CAP: i16 = 700; +pub const HEIGHT_X: i16 = 500; + +/// The height (and the width across a vertical line) of [`height_font`]'s ideographic character +/// face, in ems. +pub const HEIGHT_ICF: f64 = 0.9; + +/// The family of [`height_outside_font`]. +pub const HEIGHT_OUTSIDE_FAMILY: &str = "Heightoutsidetest Sans"; + +/// The cap height and x height [`height_outside_font`] gives, in font units (1,000 to the em): +/// 2.5 em and 0.05 em, outside the 0.1 to 2 ems a font size measures. +pub const HEIGHT_OUTSIDE_CAP: i16 = 2500; +pub const HEIGHT_OUTSIDE_X: i16 = 50; + +/// The bundled Source Sans 3 Regular as family [`HEIGHT_FAMILY`], with the cap height +/// [`HEIGHT_CAP`] and x height [`HEIGHT_X`] in its OS/2 table and a `BASE` table whose Han +/// baselines put the ideographic character face [`HEIGHT_ICF`] em high inside the em box (`ideo` +/// -120, `idtp` 880, `icfb` -70, `icft` 830). Without `heights`: family [`HEIGHTLESS_FAMILY`], +/// with a version 1 OS/2 table, which holds neither height, and no `BASE` table. `None` when it +/// can't be built. +pub fn height_font(heights: bool) -> Option<Vec<u8>> { + if heights { heights_font(HEIGHT_FAMILY, Some((HEIGHT_X, HEIGHT_CAP)), true) } else { heights_font(HEIGHTLESS_FAMILY, None, false) } +} + +/// The bundled Source Sans 3 Regular as family [`HEIGHT_OUTSIDE_FAMILY`], with the cap height +/// [`HEIGHT_OUTSIDE_CAP`] and x height [`HEIGHT_OUTSIDE_X`] in its OS/2 table and no `BASE` +/// table. `None` when it can't be built. +pub fn height_outside_font() -> Option<Vec<u8>> { + heights_font(HEIGHT_OUTSIDE_FAMILY, Some((HEIGHT_OUTSIDE_X, HEIGHT_OUTSIDE_CAP)), false) +} + +/// The bundled Source Sans 3 Regular as `family`: with the x height and cap height `heights` in +/// its OS/2 table, else a version 1 OS/2 table, which holds neither; with `base`, the `BASE` +/// table of [`height_font`]. +fn heights_font(family: &str, heights: Option<(i16, i16)>, base: bool) -> Option<Vec<u8>> { + use write_fonts::tables::base::{Axis, Base, BaseCoord, BaseScript, BaseScriptList, BaseScriptRecord, BaseTagList, BaseValues}; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let full = format!("{family} Regular"); + let postscript = format!("{}-Regular", family.replace(' ', "")); + let name = name_table(&[(1, family), (2, "Regular"), (4, &full), (6, &postscript)])?; + let mut builder = FontBuilder::new(); + builder.add_raw(Tag::new(b"name"), name); + if base { + let tags = BaseTagList::new([b"icfb", b"icft", b"ideo", b"idtp"].map(Tag::new).to_vec()); + let values = BaseValues::new(2, [-70, 830, -120, 880].map(BaseCoord::format_1).to_vec()); + let hani = BaseScriptRecord::new(Tag::new(b"hani"), BaseScript::new(Some(values), None, vec![])); + let axis = Axis::new(Some(tags), BaseScriptList::new(vec![hani])); + builder.add_table(&Base::new(Some(axis), None)).ok()?; + } + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if builder.contains(tag) { + continue; + } + let mut data = font.table_data(r.tag())?.as_bytes().to_vec(); + if tag == Tag::new(b"OS/2") { + if let Some((x, cap)) = heights { + // sxHeight and sCapHeight, at bytes 86 and 88 of a version 2 or later table. + data.get_mut(86..90)?.copy_from_slice(&[x.to_be_bytes(), cap.to_be_bytes()].concat()); + } else { + // Version 1 ends before sxHeight. + data.truncate(86); + data.get_mut(0..2)?.copy_from_slice(&1_u16.to_be_bytes()); + } + } + builder.add_raw(tag, data); + } + Some(builder.build()) +} + /// The family of [`vertical_punctuation_font`]. pub const VERTICAL_PUNCTUATION_FAMILY: &str = "Punctuationtest Sans"; diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 7ed2eb48ce..db28b20138 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1347,6 +1347,62 @@ fn character_alignment_on_the_icf_lines_small_characters_up_with_the_largest_fac } } +/// The font height reference: 20 pt type that measures the cap height is set at the em size at +/// which the font's cap height (OS/2) is 20 pt, and the same for the x height and for the ideographic +/// character face's height (its width in vertical type); the em box keeps 20 pt to the em, and +/// so does every reference in a font without these values. Auto leading follows the em size, +/// and two runs that measure different heights each take their own em size. +#[test] +fn font_size_measures_the_font_height_reference() { + use crate::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, HEIGHT_ICF, HEIGHT_X, HEIGHTLESS_FAMILY, height_font}; + use vectorcraft_doc::FontHeightReference as R; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(height_font(true).unwrap()); + db.add_font(height_font(false).unwrap()); + let st = |family: &str, r: R| CharStyle { font_family: family.into(), font_height_reference: r, ..style(20.0) }; + // The em size each glyph of `t` is drawn at (its transform's scale times 1,000 units). + let ems = |t: &TextObject| layout(&db, t).glyphs.iter().map(|g| g.xf.determinant().abs().sqrt() * 1000.0).collect::<Vec<_>>(); + let near = |a: f64, b: f64| (a - b).abs() < 1e-6; + let (cap, x) = (f64::from(HEIGHT_CAP) / 1000.0, f64::from(HEIGHT_X) / 1000.0); + for vertical_type in [false, true] { + for (r, h) in [(R::EmBox, 1.0), (R::CapHeight, cap), (R::XHeight, x), (R::IcfBox, HEIGHT_ICF)] { + let mut t = point("Hx", st(HEIGHT_FAMILY, r)); + t.vertical = vertical_type; + assert!(ems(&t).iter().all(|e| near(*e, 20.0 / h)), "{r:?} vertical {vertical_type}: {:?}", ems(&t)); + t.runs[0].style.font_family = HEIGHTLESS_FAMILY.into(); + assert!(ems(&t).iter().all(|e| near(*e, 20.0)), "{r:?} without the value, vertical {vertical_type}: {:?}", ems(&t)); + } + } + let face = db.face(HEIGHT_FAMILY, "Regular").unwrap(); + assert_eq!(face.font_height(R::CapHeight, false), Some(cap)); + assert_eq!(db.face(HEIGHTLESS_FAMILY, "Regular").unwrap().font_height(R::XHeight, false), None); + // Auto leading: 120% of the em size the line is set at. + let lines = layout(&db, &point("H\nH", st(HEIGHT_FAMILY, R::CapHeight))).lines; + assert!(near(lines[1].baseline - lines[0].baseline, 1.2 * 20.0 / cap), "{lines:?}"); + // One run at the em box, the next at the cap height. + let mut t = point("H", st(HEIGHT_FAMILY, R::EmBox)); + t.runs.push(TextRun { text: "H".into(), style: st(HEIGHT_FAMILY, R::CapHeight), inline: None }); + let set = ems(&t); + assert!(set.len() == 2 && near(set[0], 20.0) && near(set[1], 20.0 / cap), "{set:?}"); +} + +/// A font height outside 0.1 to 2 ems is not used: 20 pt type that measures a font's 2.5 em cap +/// height or its 0.05 em x height is set at 20 pt to the em. +#[test] +fn a_font_height_outside_a_tenth_to_two_ems_measures_the_em_box() { + use crate::test_fonts::{HEIGHT_OUTSIDE_FAMILY, height_outside_font}; + use vectorcraft_doc::FontHeightReference as R; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(height_outside_font().unwrap()); + let face = db.face(HEIGHT_OUTSIDE_FAMILY, "Regular").unwrap(); + for r in [R::CapHeight, R::XHeight] { + assert_eq!(face.font_height(r, false), None, "{r:?}"); + let st = CharStyle { font_family: HEIGHT_OUTSIDE_FAMILY.into(), font_height_reference: r, ..style(20.0) }; + let ems = layout(&db, &point("Hx", st)).glyphs.iter().map(|g| g.xf.determinant().abs().sqrt() * 1000.0).collect::<Vec<_>>(); + assert!(!ems.is_empty() && ems.iter().all(|e| (e - 20.0).abs() < 1e-6), "{r:?}: {ems:?}"); + } +} + /// Burasagari leaves Latin punctuation alone: in a measure of exactly "abcd", the full stop of /// "abcd. ef" doesn't hang with Standard or Forced (the line breaks as it does with None), and a /// Latin line ending in a full stop isn't shortened by Forced. diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 801ed44b5c..904c220bab 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4500,6 +4500,12 @@ axis Both И двете Insert Inline Symbol Вграждане на вграден символ ICF Top/Right ICF горе/дясно ICF Bottom/Left ICF долу/ляво + Show Font Height Options Показване на опциите за височина на шрифта + Hide Font Height Options Скриване на опциите за височина на шрифта + Set Font Height Reference Задаване на референтна височина на шрифта + Em Box Квадратна касетка (Em Box) + x-Height Височина на x + ICF Box Касетка ICF @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` е референцията за стъпка {r}, която се разрешава само от `run` и `command_batch` @msg `ids` must be an array of object ids, not {v} `ids` трябва да бъде масив от идентификатори на обекти, а не {v} @msg `corners` must be an array of anchor indices, not {v} `corners` трябва да бъде масив от индекси на опорни точки, а не {v} diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d2e67c11da..d9e96915f4 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1454,6 +1454,12 @@ digits Malayalam Malajalam Axis Osa ICF Top/Right ICF vrh/desno ICF Bottom/Left ICF dno/lijevo + Show Font Height Options Prikaži opcije visine fonta + Hide Font Height Options Sakrij opcije visine fonta + Set Font Height Reference Postavi referentnu visinu fonta + Em Box Em okvir + x-Height Visina malih slova + ICF Box ICF okvir Copy Color Value (Hex) Kopiraj vrijednost boje (hex) Create New Swatch… Kreiraj novi uzorak boje… Name 40% Naziv 40% diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index ffb752f8a9..5cbf470f69 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5735,6 +5735,12 @@ theme Appearance Aparença Glyph Bounds Límits del glif Proximity Guides Guies de proximitat Angular Guides Guies angulars + Show Font Height Options Mostra les opcions d’alçada de la font + Hide Font Height Options Amaga les opcions d’alçada de la font + Set Font Height Reference Estableix la referència d’alçada de la font + Em Box Caixa em + x-Height Alçada de la x + ICF Box Caixa ICF # Average & Join (Object › Path, Cmd+Alt+Shift+J). Average & Join… Mitjana i unió… Average & Join Mitjana i unió diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 97ab1c407a..86c2c2ef43 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1478,6 +1478,12 @@ digits Malayalam Malajálamské Axis Osa ICF Top/Right ICF horní/pravý ICF Bottom/Left ICF dolní/levý + Show Font Height Options Zobrazit možnosti výšky písma + Hide Font Height Options Skrýt možnosti výšky písma + Set Font Height Reference Nastavit referenční výšku písma + Em Box Čtverčík + x-Height Výška x + ICF Box Rámeček ICF Copy Color Value (Hex) Kopírovat hodnotu barvy (hex) Create New Swatch… Vytvořit novou položku vzorníku… Name 40% Název 40 % @@ -4209,6 +4215,7 @@ imageTrace Outline Obrys @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer vrstvy souboru nebyly načteny ({_1}): soubor se otevře jako jeho stránka v jedné vrstvě @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part vrstvy souboru nebyly načteny z jeho dat pro úpravy ({_1}): pocházejí z jeho části PDF @msg `to` must be "corner" or "smooth" `to` musí být "corner" nebo "smooth" +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` musí být "emBox", "capHeight", "xHeight" nebo "icfBox" @msg BMP files are RGB or grayscale: colorModel rgb or gray soubory BMP jsou RGB nebo ve stupních šedi: colorModel rgb nebo gray @msg Blend colors: select at least three objects with filled colours Prolnout barvy: vyberte alespoň tři objekty s barevnou výplní @msg Combine Slices: the slices have no bounds Spojit řezy: řezy nemají hranice diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 1d1741662b..bee5e72703 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1388,6 +1388,12 @@ digits Malayalam Malayalam Axis Akse ICF Top/Right ICF øverst/højre ICF Bottom/Left ICF nederst/venstre + Show Font Height Options Vis indstillinger for skrifthøjde + Hide Font Height Options Skjul indstillinger for skrifthøjde + Set Font Height Reference Angiv reference for skrifthøjde + Em Box Em-felt + x-Height x-højde + ICF Box ICF-felt Copy Color Value (Hex) Kopiér farveværdi (hex) Create New Swatch… Opret ny farveprøve… Name 40% Navn 40% diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 8045420136..92ca0c2399 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3821,6 +3821,7 @@ theme Appearance Erscheinungsbild @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer die Ebenen der Datei wurden nicht gelesen ({_1}): sie wird als ihre Seite in einer Ebene geöffnet @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part die Ebenen der Datei wurden nicht aus ihren Bearbeitungsdaten gelesen ({_1}): sie stammen aus ihrem PDF-Teil @msg `to` must be "corner" or "smooth" `to` muss "corner" oder "smooth" sein +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` muss "emBox", "capHeight", "xHeight" oder "icfBox" sein @msg BMP files are RGB or grayscale: colorModel rgb or gray BMP-Dateien sind RGB oder Graustufen: colorModel rgb oder gray @msg Blend colors: select at least three objects with filled colours Farben angleichen: Wählen Sie mindestens drei Objekte mit Flächenfarbe aus @msg Combine Slices: the slices have no bounds Slices kombinieren: Die Slices haben keine Begrenzung @@ -4555,6 +4556,13 @@ theme Appearance Erscheinungsbild Insert Inline Symbol Inline-Symbol einfügen ICF Top/Right ICF oben/rechts ICF Bottom/Left ICF unten/links + Show Font Height Options Optionen für Schrifthöhe einblenden + Hide Font Height Options Optionen für Schrifthöhe ausblenden + Set Font Height Reference Bezugsgröße der Schrifthöhe festlegen + Em Box Geviert + Cap Height Versalhöhe + x-Height x-Höhe + ICF Box ICF-Rahmen @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` ist der Schrittverweis {r}, den nur `run` und `command_batch` auflösen @msg `ids` must be an array of object ids, not {v} `ids` muss ein Array von Objekt-IDs sein, nicht {v} @msg `corners` must be an array of anchor indices, not {v} `corners` muss ein Array von Ankerpunkt-Indizes sein, nicht {v} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index ce061787a2..30ab097ecd 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2123,6 +2123,7 @@ axis Both Και τα δύο @msg the art on them differs from the page's in {_1}% of it: they come from its editing data all the same Τα γραφικά τους διαφέρουν από εκείνα της σελίδας κατά {_1}%, αλλά θα χρησιμοποιηθούν τα δεδομένα επεξεργασίας @msg `Custom` stands for changed settings: save the preset under another name Το `Custom` αντιστοιχεί σε αλλαγμένες ρυθμίσεις: αποθηκεύστε την προεπιλογή με άλλο όνομα @msg `to` must be "corner" or "smooth" Το `to` πρέπει να είναι "corner" ή "smooth" +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" Το `fontHeightReference` πρέπει να είναι "emBox", "capHeight", "xHeight" ή "icfBox" @msg BMP files are RGB or grayscale: colorModel rgb or gray Τα αρχεία BMP πρέπει να είναι RGB ή σε κλίμακα του γκρι: colorModel rgb ή gray @msg Blend colors: select at least three objects with filled colours Ανάμειξη χρωμάτων: επιλέξτε τουλάχιστον τρία αντικείμενα με χρώμα γεμίσματος @msg Combine Slices: the slices have no bounds Συνδυασμός τομών: οι τομές δεν έχουν όρια @@ -4580,6 +4581,12 @@ digits Malayalam Μαλαγιάλαμ Insert Inline Symbol Εισαγωγή ενσωματωμένου συμβόλου ICF Top/Right ICF επάνω/δεξιά ICF Bottom/Left ICF κάτω/αριστερά + Show Font Height Options Εμφάνιση επιλογών ύψους γραμματοσειράς + Hide Font Height Options Απόκρυψη επιλογών ύψους γραμματοσειράς + Set Font Height Reference Ορισμός αναφοράς ύψους γραμματοσειράς + Em Box Τετράγωνο em + x-Height Ύψος x + ICF Box Πλαίσιο ICF @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve το `id` είναι η αναφορά βήματος {r}, την οποία αναλύουν μόνο τα `run` και `command_batch` @msg `ids` must be an array of object ids, not {v} το `ids` πρέπει να είναι πίνακας αναγνωριστικών αντικειμένων, όχι {v} @msg `corners` must be an array of anchor indices, not {v} το `corners` πρέπει να είναι πίνακας δεικτών αγκύρωσης, όχι {v} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f389ff274..48797306ca 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -949,6 +949,12 @@ font-technology Variable Variables Em Box Top/Right Arriba/derecha del cuadro eme ICF Top/Right Arriba/derecha del ICF ICF Bottom/Left Abajo/izquierda del ICF + Show Font Height Options Mostrar opciones de altura de fuente + Hide Font Height Options Ocultar opciones de altura de fuente + Set Font Height Reference Definir la referencia de altura de fuente + Em Box Cuadro eme + x-Height Altura de la x + ICF Box Cuadro ICF Em Dash Raya Em Space Espacio eme Embed Incrustar @@ -3901,6 +3907,7 @@ axis Both Ambos @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer no se leyeron las capas del archivo ({_1}): se abre como su página, en una sola capa @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part no se leyeron las capas del archivo desde sus datos de edición ({_1}): proceden de su parte PDF @msg `to` must be "corner" or "smooth" `to` debe ser "corner" o "smooth" +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` debe ser "emBox", "capHeight", "xHeight" o "icfBox" @msg BMP files are RGB or grayscale: colorModel rgb or gray los archivos BMP son RGB o en escala de grises: colorModel rgb o gray @msg Blend colors: select at least three objects with filled colours Fusionar colores: selecciona al menos tres objetos con relleno de color @msg Combine Slices: the slices have no bounds Combinar sectores: los sectores no tienen límites diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d3cf99cd8b..1f7de4be19 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1451,6 +1451,12 @@ digits Malayalam Malajalam Axis Akseli ICF Top/Right ICF ylä/oikea ICF Bottom/Left ICF ala/vasen + Show Font Height Options Näytä fontin korkeuden asetukset + Hide Font Height Options Piilota fontin korkeuden asetukset + Set Font Height Reference Aseta fontin korkeuden viite + Em Box Em-laatikko + x-Height x-korkeus + ICF Box ICF-laatikko Copy Color Value (Hex) Kopioi väriarvo (heksa) Create New Swatch… Luo uusi värimalli… Name 40% Nimi 40% @@ -4123,6 +4129,7 @@ imageTrace Outline Ääriviiva @msg the art on them differs from the page's in {_1}% of it: they come from its editing data all the same niiden kuvitus eroaa sivun kuvituksesta {_1} %:n osalta: ne tuodaan silti sen muokkaustiedoista @msg `Custom` stands for changed settings: save the preset under another name `Custom` tarkoittaa muutettuja asetuksia: tallenna esiasetus toisella nimellä @msg `to` must be "corner" or "smooth" `to` on oltava "corner" tai "smooth" +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` on oltava "emBox", "capHeight", "xHeight" tai "icfBox" @msg BMP files are RGB or grayscale: colorModel rgb or gray BMP-tiedostot ovat RGB- tai harmaasävykuvia: colorModel rgb tai gray @msg Blend colors: select at least three objects with filled colours Sulauta värit: valitse vähintään kolme objektia, joilla on väritäyttö @msg Combine Slices: the slices have no bounds Yhdistä viipaleet: viipaleilla ei ole rajoja diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e82972fbc6..523c06bb54 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3897,6 +3897,7 @@ axis Both Les deux @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer les calques du fichier n’ont pas été lus ({_1}) : il est ouvert tel que sa page, sur un seul calque @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part les calques du fichier n’ont pas été lus depuis ses données de modification ({_1}) : ils proviennent de sa partie PDF @msg `to` must be "corner" or "smooth" `to` doit être "corner" ou "smooth" +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` doit être "emBox", "capHeight", "xHeight" ou "icfBox" @msg BMP files are RGB or grayscale: colorModel rgb or gray Les fichiers BMP sont en RVB ou en niveaux de gris : colorModel rgb ou gray @msg Blend colors: select at least three objects with filled colours Fusion des couleurs : sélectionnez au moins trois objets dotés d’un fond de couleur @msg Combine Slices: the slices have no bounds Combiner les tranches : les tranches n’ont pas de limites @@ -4628,6 +4629,12 @@ axis Both Les deux Free Transform Transformation manuelle Perspective Distort Distorsion de perspective Insert Inline Symbol Insérer un symbole dans le texte + Show Font Height Options Afficher les options de hauteur de police + Hide Font Height Options Masquer les options de hauteur de police + Set Font Height Reference Définir la référence de hauteur de police + Em Box Cadratin + x-Height Hauteur d’x + ICF Box Cadre ICF ICF Top/Right ICF haut/droite ICF Bottom/Left ICF bas/gauche @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` est la référence d’étape {r}, que seuls `run` et `command_batch` résolvent diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 1f7317fad8..af31ed39cb 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1937,6 +1937,12 @@ file-filter Templates Sablonok Hyphenate Capitalized Words Nagybetűs szavak elválasztása ICC Profile ICC-profil ICF Bottom/Left ICF alja/bal oldala + Show Font Height Options Betűmagasság-beállítások megjelenítése + Hide Font Height Options Betűmagasság-beállítások elrejtése + Set Font Height Reference Betűmagasság viszonyítási alapjának beállítása + Em Box Kvirtmező + x-Height x-magasság + ICF Box ICF-mező ICF Top/Right ICF teteje/jobb oldala Identify Objects By Objektumok azonosítása Ignore Kihagy @@ -4518,6 +4524,7 @@ imageTrace Outline Körvonal @msg `stops` must be an array `stops`: tömb kell @msg `svg` must be an object of SVG options (see document.formats) `svg`: SVG-beállításokat tartalmazó objektum kell (lásd: document.formats) @msg `to` must be "corner" or "smooth" `to`: "corner" vagy "smooth" kell +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference`: "emBox", "capHeight", "xHeight" vagy "icfBox" kell @msg `{_1}` is no save command nem mentési parancs: `{_1}` @msg `{area}` is no recovery area name nem helyreállítási terület neve: `{area}` @msg `{color}` is not a colour (#rrggbb or a preset name) nem szín: `{color}` (#rrggbb vagy előbeállítás neve) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index b90aadc98d..a15105ef92 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1388,6 +1388,12 @@ digits Malayalam Malayalam Axis Sumbu ICF Top/Right ICF atas/kanan ICF Bottom/Left ICF bawah/kiri + Show Font Height Options Tampilkan opsi tinggi font + Hide Font Height Options Sembunyikan opsi tinggi font + Set Font Height Reference Atur acuan tinggi font + Em Box Em Box + x-Height Tinggi x + ICF Box Kotak ICF Copy Color Value (Hex) Salin nilai warna (Hex) Create New Swatch… Buat swatch baru… Name 40% Nama 40% diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 9a9709b8df..e94ffaf0b1 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -949,6 +949,13 @@ font-technology Variable Variabili Em Box Top/Right Riquadro em in alto/a destra ICF Top/Right ICF in alto/a destra ICF Bottom/Left ICF in basso/a sinistra + Show Font Height Options Mostra opzioni altezza font + Hide Font Height Options Nascondi opzioni altezza font + Set Font Height Reference Imposta riferimento altezza font + Em Box Riquadro em + Cap Height Altezza maiuscole + x-Height Altezza x + ICF Box Riquadro ICF Em Dash Lineetta Em Space Spazio em Embed Incorpora @@ -3941,6 +3948,7 @@ axis Both Entrambi @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer i livelli del file non sono stati letti ({_1}): si apre come la sua pagina, in un solo livello @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part i livelli del file non sono stati letti dai suoi dati di modifica ({_1}): provengono dalla sua parte PDF @msg `to` must be "corner" or "smooth" `to` deve essere "corner" o "smooth" +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` deve essere "emBox", "capHeight", "xHeight" o "icfBox" @msg BMP files are RGB or grayscale: colorModel rgb or gray I file BMP sono RGB o in scala di grigi: colorModel rgb o gray @msg Blend colors: select at least three objects with filled colours Fondi colori: seleziona almeno tre oggetti con riempimento colore @msg Combine Slices: the slices have no bounds Combina sezioni: le sezioni non hanno limiti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index b901b93366..902df6a9dd 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -42,6 +42,13 @@ font-technology Variable バリアブル Em Box Top/Right 仮想ボディの上 / 右 ICF Top/Right 平均字面の上 / 右 ICF Bottom/Left 平均字面の下 / 左 + Show Font Height Options フォントの高さオプションを表示 + Hide Font Height Options フォントの高さオプションを隠す + Set Font Height Reference フォントの高さの基準を設定 + Em Box 仮想ボディ + Cap Height キャップハイト + x-Height x ハイト + ICF Box 平均字面 Proportional Metrics プロポーショナルメトリクス Character Direction 文字の方向 Digits 数字 @@ -3983,6 +3990,7 @@ swatch Bright Violet ビビッドバイオレット @msg Saving {_1} {_1} を保存中 @msg Sent to {_1} {_1} に送信しました @msg `to` must be "corner" or "smooth" `to` には "corner" または "smooth" を指定してください +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` には "emBox"、"capHeight"、"xHeight"、"icfBox" のいずれかを指定してください @msg a layer couldn't be read 読み込めなかったレイヤーがあります @msg it has more than one artboard アートボードが複数あります @msg its editing data has no layers 編集データにレイヤーがありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index be58e0b36d..d6dcb9e033 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1305,6 +1305,12 @@ digits Malayalam მალაიალამური Axis ღერძი ICF Top/Right ICF ზედა/მარჯვენა ICF Bottom/Left ICF ქვედა/მარცხენა + Show Font Height Options შრიფტის სიმაღლის პარამეტრების ჩვენება + Hide Font Height Options შრიფტის სიმაღლის პარამეტრების დამალვა + Set Font Height Reference შრიფტის სიმაღლის საზომის დაყენება + Em Box Em-ბლოკი + x-Height x-სიმაღლე + ICF Box ICF-ბლოკი Copy Color Value (Hex) ფერის მნიშვნელობის კოპირება (Hex) Create New Swatch… ახალი ფერის ნიმუშის შექმნა… Name 40% სახელი 40% @@ -3692,6 +3698,7 @@ font-technology Variable ცვლადი @msg the art on them differs from the page's in {_1}% of it მათზე არსებული ნახატი გვერდისას {_1}%-ით განსხვავდება @msg `Custom` stands for changed settings: save the preset under another name `Custom` შეცვლილ პარამეტრებს ნიშნავს: შეინახეთ პრესეტი სხვა სახელით @msg `to` must be "corner" or "smooth" `to` უნდა იყოს "corner" ან "smooth" +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` უნდა იყოს "emBox", "capHeight", "xHeight" ან "icfBox" @msg BMP files are RGB or grayscale: colorModel rgb or gray BMP ფაილები RGB-ა ან ნაცრისფერი: colorModel rgb ან gray @msg Blend colors: select at least three objects with filled colours ფერების შერევა: მონიშნეთ მინიმუმ სამი ობიექტი ფერადი შევსებით @msg Combine Slices: the slices have no bounds ნაჭრების გაერთიანება: ნაჭრებს საზღვრები არ აქვს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index b979e26136..e2da7c92af 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -36,6 +36,13 @@ font-technology Variable 가변 Em Box Top/Right 엠 박스 위/오른쪽 ICF Top/Right ICF 위/오른쪽 ICF Bottom/Left ICF 아래/왼쪽 + Show Font Height Options 글꼴 높이 옵션 표시 + Hide Font Height Options 글꼴 높이 옵션 숨기기 + Set Font Height Reference 글꼴 높이 기준 설정 + Em Box 엠 박스 + Cap Height 대문자 높이 + x-Height x 높이 + ICF Box ICF 박스 Proportional Metrics 비례 메트릭 Character Direction 문자 방향 Digits 숫자 @@ -3910,6 +3917,7 @@ theme Appearance 외관 @msg Saving {_1} {_1} 저장 중 @msg Sent to {_1} {_1}(으)로 보냈습니다 @msg `to` must be "corner" or "smooth" `to`는 "corner" 또는 "smooth"여야 합니다 +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference`는 "emBox", "capHeight", "xHeight" 또는 "icfBox"여야 합니다 @msg a layer couldn't be read 레이어를 읽을 수 없습니다 @msg it has more than one artboard 아트보드가 둘 이상입니다 @msg its editing data has no layers 편집 데이터에 레이어가 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 60b73cb0fd..9d3d2c7c80 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1402,6 +1402,12 @@ digits Malayalam Malayalam Axis As ICF Top/Right ICF boven/rechts ICF Bottom/Left ICF onder/links + Show Font Height Options Opties voor letterhoogte tonen + Hide Font Height Options Opties voor letterhoogte verbergen + Set Font Height Reference Referentie voor letterhoogte instellen + Em Box Em-vak + x-Height x-hoogte + ICF Box ICF-vak Copy Color Value (Hex) Kleurwaarde kopiëren (Hex) Create New Swatch… Nieuw staal maken… Name 40% Naam 40% diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index e32cb1fa11..24c3685b3b 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1391,6 +1391,12 @@ digits Malayalam Malajalam Axis Oś ICF Top/Right ICF góra/prawo ICF Bottom/Left ICF dół/lewo + Show Font Height Options Pokaż opcje wysokości czcionki + Hide Font Height Options Ukryj opcje wysokości czcionki + Set Font Height Reference Ustaw odniesienie wysokości czcionki + Em Box Ramka firetowa + x-Height Wysokość x + ICF Box Ramka ICF Copy Color Value (Hex) Kopiuj wartość koloru (hex) Create New Swatch… Utwórz nową próbkę… Name 40% Nazwa 40% @@ -4032,6 +4038,7 @@ imageTrace Outline Kontur @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer nie odczytano warstw pliku ({_1}): plik jest wczytywany jako jego strona, na jednej warstwie @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part nie odczytano warstw pliku z jego danych edycyjnych ({_1}): pochodzą z jego części PDF @msg `to` must be "corner" or "smooth" `to` musi mieć wartość "corner" lub "smooth" +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` musi mieć wartość "emBox", "capHeight", "xHeight" lub "icfBox" @msg BMP files are RGB or grayscale: colorModel rgb or gray Pliki BMP są w RGB lub skali szarości: colorModel rgb lub gray @msg Blend colors: select at least three objects with filled colours Przejście kolorów: zaznacz co najmniej trzy obiekty z wypełnieniem kolorem @msg Combine Slices: the slices have no bounds Połącz plasterki: plasterki nie mają granic diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index af74d69dd8..152cb4b41b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -840,6 +840,12 @@ Em Box Top/Right Topo/Direita da Caixa Eme ICF Top/Right Topo/Direita do ICF ICF Bottom/Left Base/Esquerda do ICF + Show Font Height Options Mostrar Opções de Altura da Fonte + Hide Font Height Options Ocultar Opções de Altura da Fonte + Set Font Height Reference Definir Referência de Altura da Fonte + Em Box Caixa Eme + x-Height Altura do x + ICF Box Caixa ICF Em Dash Travessão Em Space Espaço Em Embed Incorporar @@ -3485,6 +3491,7 @@ axis Both Ambos @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer as camadas do arquivo não foram lidas ({_1}): ele entra como sua página, em uma só camada @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part as camadas do arquivo não foram lidas dos seus dados de edição ({_1}): elas vêm da sua parte PDF @msg `to` must be "corner" or "smooth" `to` deve ser "corner" ou "smooth" +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` deve ser "emBox", "capHeight", "xHeight" ou "icfBox" @msg BMP files are RGB or grayscale: colorModel rgb or gray arquivos BMP são RGB ou em tons de cinza: colorModel rgb ou gray @msg Blend colors: select at least three objects with filled colours Mesclar cores: selecione pelo menos três objetos com preenchimento de cor @msg Combine Slices: the slices have no bounds Combinar fatias: as fatias não têm limites diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index c497b2ad2b..f60e17a755 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -947,6 +947,12 @@ font-technology Variable Вариативные Em Box Top/Right Верх/право кегельной площадки ICF Top/Right Верх/право ICF ICF Bottom/Left Низ/лево ICF + Show Font Height Options Показать параметры высоты шрифта + Hide Font Height Options Скрыть параметры высоты шрифта + Set Font Height Reference Задать опорную высоту шрифта + Em Box Кегельная площадка + x-Height Высота строчных + ICF Box Рамка ICF Em Dash Длинное тире Em Space Круглая шпация Embed Внедрить @@ -3937,6 +3943,7 @@ axis Both Оба @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer слои файла не прочитаны ({_1}): он открывается как его страница, на одном слое @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part слои файла не прочитаны из его данных для редактирования ({_1}): они взяты из его PDF-части @msg `to` must be "corner" or "smooth" `to` должно быть "corner" или "smooth" +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` должно быть "emBox", "capHeight", "xHeight" или "icfBox" @msg BMP files are RGB or grayscale: colorModel rgb or gray файлы BMP бывают RGB или в оттенках серого: colorModel rgb или gray @msg Blend colors: select at least three objects with filled colours Смешивание цветов: выберите не менее трёх объектов с цветными заливками @msg Combine Slices: the slices have no bounds Объединение фрагментов: у фрагментов нет границ diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 4b8742d00a..91595dfa2f 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3818,6 +3818,7 @@ axis Both Båda @msg the art on them differs from the page's in {_1}% of it: they come from its editing data all the same grafiken på dem skiljer sig från sidans i {_1} % av ytan: de hämtas ändå från dess redigeringsdata @msg `Custom` stands for changed settings: save the preset under another name `Custom` står för ändrade inställningar: spara förinställningen med ett annat namn @msg `to` must be "corner" or "smooth" `to` måste vara "corner" eller "smooth" +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` måste vara "emBox", "capHeight", "xHeight" eller "icfBox" @msg BMP files are RGB or grayscale: colorModel rgb or gray BMP-filer är RGB eller gråskala: colorModel rgb eller gray @msg Blend colors: select at least three objects with filled colours Blanda färger: markera minst tre objekt med färgfyllning @msg Combine Slices: the slices have no bounds Kombinera skivor: skivorna har inga gränser @@ -4537,6 +4538,12 @@ axis Both Båda Insert Inline Symbol Infoga symbol i texten ICF Top/Right ICF överkant/höger ICF Bottom/Left ICF nederkant/vänster + Show Font Height Options Visa alternativ för teckenhöjd + Hide Font Height Options Dölj alternativ för teckenhöjd + Set Font Height Reference Ange referens för teckenhöjd + Em Box Em-ruta + x-Height x-höjd + ICF Box ICF-ruta @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` är stegreferensen {r}, som bara `run` och `command_batch` löser upp @msg `ids` must be an array of object ids, not {v} `ids` måste vara en array med objekt-id:n, inte {v} @msg `corners` must be an array of anchor indices, not {v} `corners` måste vara en array med index för ankarpunkter, inte {v} diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index e6517df494..7e5ca938c6 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -144,6 +144,17 @@ fn catalan_reads_as_catalan() { assert_eq!(message(ca, nested), "l’ordre `object.group` no està disponible ara mateix: no hi ha res seleccionat"); } +#[test] +fn font_height_reference_labels_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in + ["Show Font Height Options", "Hide Font Height Options", "Set Font Height Reference", "Em Box", "Cap Height", "x-Height", "ICF Box"] + { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } +} + /// Each language counts with its own plural rule: the form a count picks (`one`, then `few`, then /// `other`/`many`). #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 5aeae9118b..18449679b8 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3703,6 +3703,7 @@ axis Both Her İkisi @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer dosyanın katmanları okunmadı ({_1}): tek katmanda kendi sayfası olarak geliyor @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part dosyanın katmanları düzenleme verilerinden okunmadı ({_1}): PDF kısmından geliyorlar @msg `to` must be "corner" or "smooth" "to" "köşe" veya "pürüzsüz" olmalıdır +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` "emBox", "capHeight", "xHeight" veya "icfBox" olmalıdır @msg BMP files are RGB or grayscale: colorModel rgb or gray BMP dosyaları RGB veya gri tonlamalıdır: colorModel rgb veya gri @msg Blend colors: select at least three objects with filled colours Renkleri karıştır: dolgulu renklere sahip en az üç nesne seçin @msg Combine Slices: the slices have no bounds Dilimleri Birleştir: dilimlerin sınırları yoktur @@ -4380,6 +4381,12 @@ axis Both Her İkisi Insert Inline Symbol Satır İçi Sembol Ekle ICF Top/Right ICF Üst/Sağ ICF Bottom/Left ICF Alt/Sol + Show Font Height Options Yazı Tipi Yüksekliği Seçeneklerini Göster + Hide Font Height Options Yazı Tipi Yüksekliği Seçeneklerini Gizle + Set Font Height Reference Yazı Tipi Yüksekliği Referansını Ayarla + Em Box Em Kutusu + x-Height x-Yüksekliği + ICF Box ICF Kutusu @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve "id", yalnızca "run" ve "command_batch" çözümleyen {r} adım referansıdır @msg `ids` must be an array of object ids, not {v} "kimlikler" {v} değil, bir nesne kimlikleri dizisi olmalıdır @msg `corners` must be an array of anchor indices, not {v} "köşeler" {v} değil, bir bağlantı indeksleri dizisi olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 53fe1f4623..ba2ae98bc9 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -943,6 +943,13 @@ font-technology Variable Варіативні Em Box Top/Right Верх/право кегельного майданчика ICF Top/Right Верх/право ICF ICF Bottom/Left Нижній/лівий край ICF + Show Font Height Options Показати параметри висоти шрифту + Hide Font Height Options Приховати параметри висоти шрифту + Set Font Height Reference Задати опорну висоту шрифту + Em Box Кегельний майданчик + Cap Height Висота великих літер + x-Height Висота малих літер + ICF Box Рамка ICF Em Dash Довге тире Em Space Кругла шпація Embed Вбудувати @@ -3925,6 +3932,7 @@ axis Both Обидві @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer шари файлу не прочитано ({_1}): він відкривається як його сторінка, на одному шарі @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part шари файлу не прочитано з його даних для редагування ({_1}): їх взято з його PDF-частини @msg `to` must be "corner" or "smooth" `to` має бути "corner" або "smooth" +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` має бути "emBox", "capHeight", "xHeight" або "icfBox" @msg BMP files are RGB or grayscale: colorModel rgb or gray Файли BMP бувають RGB або у відтінках сірого: colorModel rgb або gray @msg Blend colors: select at least three objects with filled colours Змішування кольорів: виберіть не менше трьох об’єктів із кольоровими заливками @msg Combine Slices: the slices have no bounds Об’єднання фрагментів: фрагменти не мають кордонів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index ea692ca644..e215bb2ebf 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1781,6 +1781,13 @@ digits Hindi Hindi Hyphenate Capitalized Words Gạch nối từ viết hoa chữ đầu ICC Profile Hồ sơ ICC ICF Bottom/Left ICF Dưới/Trái + Show Font Height Options Hiện tùy chọn chiều cao phông chữ + Hide Font Height Options Ẩn tùy chọn chiều cao phông chữ + Set Font Height Reference Đặt tham chiếu chiều cao phông chữ + Em Box Ô em + Cap Height Chiều cao chữ hoa + x-Height Chiều cao chữ x + ICF Box Ô ICF ICF Top/Right ICF Trên/Phải Identify Objects By Nhận diện đối tượng theo Ignore Bỏ qua @@ -4169,6 +4176,7 @@ theme Appearance Giao diện @msg `stops` must be an array `stops` phải là một mảng @msg `svg` must be an object of SVG options (see document.formats) `svg` phải là đối tượng tùy chọn SVG (xem document.formats) @msg `to` must be "corner" or "smooth" `to` phải là "corner" hoặc "smooth" +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` phải là "emBox", "capHeight", "xHeight" hoặc "icfBox" @msg `{_1}` is no save command `{_1}` không phải là lệnh lưu @msg `{area}` is no recovery area name `{area}` không phải là tên vùng phục hồi @msg `{color}` is not a colour (#rrggbb or a preset name) `{color}` không phải là màu (#rrggbb hoặc tên thiết lập sẵn) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 431eb33552..acdfaf1b1c 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -889,6 +889,13 @@ Em Box Top/Right 全角字框上 / 右 ICF Top/Right ICF 上 / 右 ICF Bottom/Left ICF 下 / 左 + Show Font Height Options 显示字体高度选项 + Hide Font Height Options 隐藏字体高度选项 + Set Font Height Reference 设置字体高度参考 + Em Box 全角字框 + Cap Height 大写字母高度 + x-Height x 字高 + ICF Box ICF 框 Em Dash 长破折号 Em Space 全角空格 Embed 嵌入 @@ -3720,6 +3727,7 @@ imageTrace Outline 轮廓 @msg Saving {_1} 正在保存 {_1} @msg Sent to {_1} 已发送到 {_1} @msg `to` must be "corner" or "smooth" `to` 必须是 "corner" 或 "smooth" +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` 必须是 "emBox"、"capHeight"、"xHeight" 或 "icfBox" @msg a layer couldn't be read 无法读取某个图层 @msg it has more than one artboard 它有多个画板 @msg its editing data has no layers 其编辑数据中没有图层 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index c55958717b..460926d92b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -911,6 +911,13 @@ font-technology Variable 可變 Em Box Top/Right 全形字框上 / 右 ICF Top/Right ICF 上 / 右 ICF Bottom/Left ICF 下 / 左 + Show Font Height Options 顯示字體高度選項 + Hide Font Height Options 隱藏字體高度選項 + Set Font Height Reference 設定字體高度參考 + Em Box 全形字框 + Cap Height 大寫字母高度 + x-Height x 字高 + ICF Box ICF 框 Em Dash 長破折號 Em Space 全形空格 Embed 嵌入 @@ -1645,6 +1652,7 @@ file-filter Templates 範本 @msg Saving {_1} 正在儲存 {_1} @msg Sent to {_1} 已傳送至 {_1} @msg `to` must be "corner" or "smooth" `to` 必須是 "corner" 或 "smooth" +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` 必須是 "emBox"、"capHeight"、"xHeight" 或 "icfBox" @msg a layer couldn't be read 有一個圖層無法讀取 @msg it has more than one artboard 它有多個工作區域 @msg its editing data has no layers 其編輯資料中沒有圖層 diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index b3a72b9d3b..f00c33d70f 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -91,20 +91,27 @@ pub(crate) fn shared_text_flag(app: &VectorcraftApp, f: impl Fn(&vectorcraft_doc /// caret's style at a caret), else every run of the selected type, groups' included. `None` (a /// blank field) where they differ, or with no type. pub(crate) fn shared<T: PartialEq>(app: &VectorcraftApp, f: impl Fn(&CharStyle) -> T) -> Option<T> { - shared_styles(app, |_, _, style| Some(f(style))) + shared_styles(app, |_, _, style, _| Some(f(style))) } /// Dimensional controls use document units and tolerate arithmetic roundoff when comparing /// compensated runs. Keep raw styles available to font/paragraph controls and style definitions, /// even if a collapsed affine prevents editing dimensions. fn shared_effective(app: &VectorcraftApp, f: impl Fn(&CharStyle) -> f64) -> Option<f64> { - shared_styles(app, |t, _, style| t.effective_char_style(style).map(|s| Metric(f(&s)))).map(|v| v.0) + shared_styles(app, |t, _, style, _| t.effective_char_style(style).map(|s| Metric(f(&s)))).map(|v| v.0) } -/// The Leading shown: each character's own, or for Auto leading the share of its size its -/// paragraph's Justification › Auto Leading sets, as the layout uses. +/// The Leading shown: each character's own, or for Auto leading the share of the em size their +/// font height reference gives them ([`vectorcraft_text::FontDb::em_size`]) that their paragraph's +/// Justification › Auto Leading sets, as the layout uses. An inline graphic keeps its size. fn shared_leading(app: &VectorcraftApp) -> Option<f64> { - shared_styles(app, |t, para, style| t.effective_char_style(style).map(|s| Metric(para.effective_leading(&s)))).map(|v| v.0) + let db = vectorcraft_text::FontDb::global(); + shared_styles(app, |t, para, style, inline| { + let s = t.effective_char_style(style)?; + let em = if inline { s.size } else { db.em_size(&s, t.vertical) }; + Some(Metric(para.effective_leading(&CharStyle { size: em, ..s }))) + }) + .map(|v| v.0) } pub(crate) struct Metric(pub(crate) f64); @@ -115,11 +122,12 @@ impl PartialEq for Metric { } } -/// `f` of each character style in the selection, with its text object and the paragraph the -/// characters are in (a run that spans paragraphs counts once for each). +/// `f` of each character style in the selection, with its text object, the paragraph the +/// characters are in (a run that spans paragraphs counts once for each) and whether the run is an +/// inline graphic. fn shared_styles<T: PartialEq>( app: &VectorcraftApp, - f: impl Fn(&vectorcraft_doc::TextObject, &vectorcraft_doc::ParaStyle, &CharStyle) -> Option<T>, + f: impl Fn(&vectorcraft_doc::TextObject, &vectorcraft_doc::ParaStyle, &CharStyle, bool) -> Option<T>, ) -> Option<T> { let st = app.session.active()?; let text = |id: NodeId| match st.doc.node(id).map(|n| &n.kind) { @@ -131,14 +139,14 @@ fn shared_styles<T: PartialEq>( let t = text(id)?; if b <= a { let para = t.plain_text().get(..a).map_or(0, |s| s.bytes().filter(|&c| c == b'\n').count()); - return f(t, t.para_at(para), &vectorcraft_text::edit::insertion_style(&t.runs, a, b)); + return f(t, t.para_at(para), &vectorcraft_text::edit::insertion_style(&t.runs, a, b), false); } - each_paragraph_run(t, Some((a, b)), |para, style| acc.add(f(t, para, style))); + each_paragraph_run(t, Some((a, b)), |para, style, inline| acc.add(f(t, para, style, inline))); } else { for n in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { n.walk(&mut |c| { if let NodeKind::Text(t) = &c.kind { - each_paragraph_run(t, None, |para, style| acc.add(f(t, para, style))); + each_paragraph_run(t, None, |para, style, inline| acc.add(f(t, para, style, inline))); } }); } @@ -147,13 +155,14 @@ fn shared_styles<T: PartialEq>( } /// `f` of the paragraph and style of each piece of `t`'s runs that lies in one paragraph (a -/// paragraph's closing line break belongs to it): the pieces within bytes `a..b`, or with no -/// range every run's, empty ones included. With no range, a final empty paragraph (the text ends -/// in a line break) counts too, with the style of the run before it, as the caret there types. +/// paragraph's closing line break belongs to it), and whether the run is an inline graphic: the +/// pieces within bytes `a..b`, or with no range every run's, empty ones included. With no range, a +/// final empty paragraph (the text ends in a line break) counts too, with the style of the run +/// before it, as the caret there types. fn each_paragraph_run<'a>( t: &'a vectorcraft_doc::TextObject, range: Option<(usize, usize)>, - mut f: impl FnMut(&'a vectorcraft_doc::ParaStyle, &'a CharStyle), + mut f: impl FnMut(&'a vectorcraft_doc::ParaStyle, &'a CharStyle, bool), ) { let (mut end, mut para) = (0, 0); // The style of the last character and whether it is a line break: the paragraph after it has @@ -162,7 +171,7 @@ fn each_paragraph_run<'a>( for r in &t.runs { if r.text.is_empty() { if range.is_none_or(|(a, b)| a < end && end < b) { - f(t.para_at(para), &r.style); + f(t.para_at(para), &r.style, r.inline.is_some()); } continue; } @@ -170,7 +179,7 @@ fn each_paragraph_run<'a>( let start = end; end += piece.len(); if range.is_none_or(|(a, b)| start < b && end > a) { - f(t.para_at(para), &r.style); + f(t.para_at(para), &r.style, r.inline.is_some()); } para += usize::from(piece.ends_with('\n')); last = Some((&r.style, piece.ends_with('\n'))); @@ -179,7 +188,7 @@ fn each_paragraph_run<'a>( if range.is_none() && let Some((style, true)) = last { - f(t.para_at(para), style); + f(t.para_at(para), style, false); } } @@ -657,7 +666,8 @@ fn cell(ui: &mut Ui, label: &str, tip: &str, add: impl FnOnce(&mut Ui)) { /// The Character panel's grid of numeric fields, `w` wide: Font Size, Leading, Kerning and /// Tracking, then with `more` the scales, Baseline Shift and Character Rotation (`s`: the style -/// shown). The Properties panel shows its first rows. +/// shown). With Show Font Height Options on, a row under Font Size holds the Set Font Height +/// Reference dropdown. The Properties panel shows its first rows. pub(crate) fn metrics_grid(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, s: &CharStyle, w: f32, more: bool) { let fw = ((w - 66.0) / 2.0).clamp(60.0, 100.0); let unit = app.session.type_unit(); @@ -674,6 +684,10 @@ pub(crate) fn metrics_grid(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, s: & } }); ui.end_row(); + if pstate::<bool>(ui.ctx(), FONT_HEIGHT_OPTIONS) { + cell(ui, "T↕", tl!("Set Font Height Reference"), |ui| font_height_reference(app, ui, fw)); + ui.end_row(); + } cell(ui, "VA", tl!("Kerning"), |ui| { let mode = shared(app, |s| (s.optical_kerning, s.kerning)); let caret = text_editing(app).is_some_and(|(_, a, b)| a == b); @@ -741,6 +755,30 @@ pub(crate) fn size_field(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, width: } } +/// The panel state of the Character panel menu's Show Font Height Options. +const FONT_HEIGHT_OPTIONS: &str = "ch-font-height-options"; + +/// The font height references the Set Font Height Reference dropdown lists, with their +/// `text.setFormat` values. +const FONT_HEIGHT_REFERENCES: [(vectorcraft_doc::FontHeightReference, &str); 4] = [ + (vectorcraft_doc::FontHeightReference::EmBox, "emBox"), + (vectorcraft_doc::FontHeightReference::CapHeight, "capHeight"), + (vectorcraft_doc::FontHeightReference::XHeight, "xHeight"), + (vectorcraft_doc::FontHeightReference::IcfBox, "icfBox"), +]; + +/// The Set Font Height Reference dropdown, `width` wide: the height of the font that the Font Size +/// measures, blank where the characters the panel acts on differ. +fn font_height_reference(app: &mut VectorcraftApp, ui: &mut Ui, width: f32) { + // The labels of [`FONT_HEIGHT_REFERENCES`], in its order. + let labels = [tl!("Em Box"), tl!("Cap Height"), tl!("x-Height"), tl!("ICF Box")]; + let current = shared(app, |s| s.font_height_reference); + let shown = FONT_HEIGHT_REFERENCES.iter().zip(labels).find(|(r, _)| Some(r.0) == current).map_or("", |(_, l)| l); + if let Some((_, key)) = widgets::dropdown_names(ui, "ch-font-height", shown, &labels, width).and_then(|i| FONT_HEIGHT_REFERENCES.get(i)) { + format(app, json!({"fontHeightReference": key})); + } +} + /// The font family menu and the font style dropdown of style `s` (Character and Properties panels, /// Control bar), with their `ids` and `widths`. pub(crate) fn font_pickers(app: &mut VectorcraftApp, ui: &mut Ui, s: &CharStyle, ids: (&str, &str), widths: (f32, f32)) { @@ -1065,6 +1103,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, if glyph { tl!("Hide Snap to Glyph Options") } else { tl!("Show Snap to Glyph Options") }, true, false) { set_pstate(ui.ctx(), SNAP_TO_GLYPH_OPTIONS, !glyph); } + // Show Font Height Options shows the Set Font Height Reference dropdown under Font Size. + let heights: bool = pstate(ui.ctx(), FONT_HEIGHT_OPTIONS); + if menu_item(ui, if heights { tl!("Hide Font Height Options") } else { tl!("Show Font Height Options") }, true, false) { + set_pstate(ui.ctx(), FONT_HEIGHT_OPTIONS, !heights); + } ui.separator(); let s = st.map(|x| x.0); for (label, key, on) in [ @@ -1191,8 +1234,9 @@ fn fractional_widths_on(app: &VectorcraftApp) -> bool { /// kerning, no baseline shift, 100% scales, no rotation, no underline or strikethrough, All Caps /// and Small Caps off, the normal position (neither superscript nor subscript), Roman Baseline /// character alignment, Proportional Metrics, Tate-chu-yoko, Standard Vertical Roman Alignment and -/// No Break off, the Default character direction and the Default digits, whether or not Show East -/// Asian Options and Show Indic Options are on. +/// No Break off, the Default character direction, the Default digits and the Em Box font height +/// reference, whether or not Show East Asian Options, Show Indic Options and Show Font Height +/// Options are on. fn reset_panel(app: &mut VectorcraftApp) { let d = CharStyle::default(); style(app, json!({"tracking": 0, "leading": "auto"})); @@ -1203,7 +1247,7 @@ fn reset_panel(app: &mut VectorcraftApp) { "allCaps": false, "smallCaps": d.small_caps.is_some(), "position": d.position.id(), "charAlign": d.char_align, "proportionalMetrics": d.proportional_metrics, "tateChuYoko": d.tate_chu_yoko, "standardVerticalRoman": d.standard_vertical_roman, "noBreak": d.no_break, "charDirection": "default", - "digits": d.digits + "digits": d.digits, "fontHeightReference": d.font_height_reference }), ); } diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 92809a2a49..da7a3dc09c 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -89,6 +89,102 @@ fn scaled_character_fields_show_document_sizes_and_mixed_group_values() { assert_eq!(shared_effective(&app, |s| s.h_scale), Some(100.0)); } +/// The Leading field shows the Auto leading the characters are set with, their paragraph's Auto +/// Leading share (120% by default) of their em size: 20 pt type measuring a 0.7 em cap height +/// is set at 20 / 0.7 pt. Paragraphs whose Auto leading differs show a blank field, and an +/// explicit leading shows as it is. +#[test] +fn leading_shows_the_auto_leading_of_the_em_size() { + use vectorcraft_text::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, height_font}; + vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Hx", "size": 20, "font": HEIGHT_FAMILY})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let near = |l: Option<f64>, want: f64| l.is_some_and(|l| (l - want).abs() < 1e-9); + assert!(near(shared_leading(&app), 24.0), "{:?}", shared_leading(&app)); + app.run("text.setFormat", json!({"fontHeightReference": "capHeight"})).unwrap(); + let cap = f64::from(HEIGHT_CAP) / 1000.0; + assert!(near(shared_leading(&app), 1.2 * 20.0 / cap), "{:?}", shared_leading(&app)); + app.run("text.setFormat", json!({"autoLeading": 150})).unwrap(); + assert!(near(shared_leading(&app), 1.5 * 20.0 / cap), "{:?}", shared_leading(&app)); + // The second paragraph ends in a two-byte character. + let two = app.run("text.create", json!({"x": 20, "y": 120, "text": "Hx\nHé", "size": 20, "font": HEIGHT_FAMILY})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [two]})).unwrap(); + assert!(near(shared_leading(&app), 24.0), "{:?}", shared_leading(&app)); + app.run("text.setFormat", json!({"id": two, "start": 3, "end": 6, "autoLeading": 150})).unwrap(); + assert_eq!(shared_leading(&app), None, "the second paragraph's Auto leading is 30 pt"); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("text.setStyle", json!({"leading": 30})).unwrap(); + assert!(near(shared_leading(&app), 30.0), "{:?}", shared_leading(&app)); +} + +/// An inline graphic keeps its size whatever the font height reference, so the Leading field +/// shows 120% of that size for it: blank for 20 pt Cap Height type with a graphic in it, and +/// 24 pt for the graphic alone. +#[test] +fn leading_of_an_inline_graphic_follows_its_own_size() { + use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; + vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("shape.ellipse", json!({"x": 200, "y": 150, "width": 10, "height": 10})).unwrap(); + app.run("symbol.new", json!({"name": "Dot"})).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Hx", "size": 20, "font": HEIGHT_FAMILY})).unwrap()["id"].clone(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + app.run("text.insertInline", json!({"id": id, "at": 2, "symbol": "Dot"})).unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 5, "fontHeightReference": "capHeight"})).unwrap(); + app.session.set_tool_option("select", &json!({"start": 0, "end": 5})); + assert_eq!(shared_leading(&app), None, "the type is set with 34.3 pt Auto leading and the graphic with 24 pt"); + app.session.set_tool_option("select", &json!({"start": 2, "end": 5})); + assert_eq!(text_editing(&app).map(|(_, a, b)| (a, b)), Some((2, 5))); + let shown = shared_leading(&app); + assert!(shown.is_some_and(|l| (l - 24.0).abs() < 1e-9), "{shown:?}"); +} + +/// A selected text object that ends in a line break has an empty last paragraph, which the +/// Leading field takes in; a Type tool selection of all the text does not. +#[test] +fn leading_of_a_whole_object_takes_in_the_empty_last_paragraph() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Ab\n", "size": 20})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let near = |l: Option<f64>, want: f64| l.is_some_and(|l| (l - want).abs() < 1e-9); + assert!(near(shared_leading(&app), 24.0), "{:?}", shared_leading(&app)); + app.run("text.setFormat", json!({"id": id, "start": 3, "end": 3, "autoLeading": 150})).unwrap(); + assert_eq!(shared_leading(&app), None, "the empty last paragraph's Auto leading is 30 pt"); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + app.session.set_tool_option("select", &json!({"start": 0, "end": 3})); + assert_eq!(text_editing(&app).map(|(_, a, b)| (a, b)), Some((0, 3))); + assert!(near(shared_leading(&app), 24.0), "a line break belongs to the paragraph it ends: {:?}", shared_leading(&app)); +} + +/// With the Type tool, the Leading field shows the Auto leading of the paragraphs the selection +/// covers (a line break belongs to the paragraph it ends), and at a caret that of the caret's +/// paragraph. +#[test] +fn leading_follows_the_paragraphs_the_type_tool_selection_covers() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + // é is two bytes, 4..6. + let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Ab\nCé", "size": 20})).unwrap()["id"].clone(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + app.run("text.setFormat", json!({"id": id, "start": 3, "end": 6, "autoLeading": 150})).unwrap(); + let ranges = [((0, 2), Some(24.0)), ((0, 3), Some(24.0)), ((3, 6), Some(30.0)), ((1, 4), None), ((1, 6), None), ((4, 4), Some(30.0))]; + for ((start, end), want) in ranges { + app.session.set_tool_option("select", &json!({"start": start, "end": end})); + assert_eq!(text_editing(&app).map(|(_, a, b)| (a, b)), Some((start, end))); + let shown = shared_leading(&app); + assert_eq!(shown.is_some(), want.is_some(), "{start}..{end}: {shown:?}"); + assert!(shown.zip(want).is_none_or(|(l, w)| (l - w).abs() < 1e-9), "{start}..{end}: {shown:?}"); + } +} + #[test] fn scaled_range_fields_follow_the_type_tool_selection() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -498,6 +594,48 @@ fn character_alignment_shows_with_the_east_asian_options() { assert_eq!(shown(&mut app), (true, true)); } +/// The panel menu's Show Font Height Options shows the Set Font Height Reference dropdown, +/// which shows the selected type's reference and sets the one picked (one undo step); Hide +/// Font Height Options hides it again. +#[test] +fn show_font_height_options_shows_the_font_height_reference() { + use super::super::tests_appearance::{click, frame_events, text_rect}; + use vectorcraft_doc::FontHeightReference as R; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Hx", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let reference = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| r.style.font_height_reference).collect::<Vec<_>>(), + _ => panic!("text"), + }; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let texts = |ctx: &egui::Context, app: &mut VectorcraftApp, f: fn(&mut VectorcraftApp, &mut Ui)| { + frame_events(ctx, app, vec![], f); + frame_events(ctx, app, vec![], f) + }; + // A menu item's label is drawn after its check column (a check mark or spaces). + let item = |texts: &[(String, egui::Rect)], s: &str| texts.iter().find(|(t, _)| t.trim_start_matches(['✓', ' ']) == s).map(|(_, r)| r.center()); + assert!(item(&texts(&ctx, &mut app, show), "Em Box").is_none()); + let at = item(&texts(&ctx, &mut app, menu), "Show Font Height Options").unwrap(); + click(&ctx, &mut app, at, menu); + assert!(item(&texts(&ctx, &mut app, menu), "Hide Font Height Options").is_some()); + let panel = texts(&ctx, &mut app, show); + assert!(item(&panel, "Em Box").is_some(), "{panel:?}"); + // Pick Cap Height from the dropdown. + click(&ctx, &mut app, text_rect(&panel, "Em Box").center(), show); + let undo = app.session.active().unwrap().history.undo.len(); + let open = texts(&ctx, &mut app, show); + click(&ctx, &mut app, text_rect(&open, "Cap Height").center(), show); + assert_eq!(reference(&app), [R::CapHeight]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + assert!(item(&texts(&ctx, &mut app, show), "Cap Height").is_some()); + let at = item(&texts(&ctx, &mut app, menu), "Hide Font Height Options").unwrap(); + click(&ctx, &mut app, at, menu); + assert!(item(&texts(&ctx, &mut app, show), "Cap Height").is_none()); +} + /// Tate-chu-yoko is in the panel menu with the East Asian options, and choosing it marks the /// selected characters. #[test] @@ -723,8 +861,8 @@ fn no_break_menu_item_toggles_the_selected_characters() { /// Reset Panel sets every character attribute the panel shows, except the font family, style /// and size, back to its default (Small Caps, the position, Character Alignment, Proportional -/// Metrics, Tate-chu-yoko, No Break, Character Direction and Digits included), in the selected -/// type and in the text the Type tool has selected while it edits. +/// Metrics, Tate-chu-yoko, No Break, Character Direction, Digits and the font height reference +/// included), in the selected type and in the text the Type tool has selected while it edits. #[test] fn reset_panel_resets_every_attribute_but_the_font() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -755,6 +893,7 @@ fn reset_panel_resets_every_attribute_but_the_font() { s.no_break != d.no_break, s.char_direction != d.char_direction, s.digits != d.digits, + s.font_height_reference != d.font_height_reference, ] }; let custom = |app: &mut VectorcraftApp| { @@ -764,16 +903,16 @@ fn reset_panel_resets_every_attribute_but_the_font() { "id": id, "tracking": 50, "leading": 30, "kerning": 20, "baselineShift": 3, "hScale": 120, "vScale": 90, "rotation": 15, "underline": true, "strikethrough": true, "allCaps": true, "smallCaps": true, "position": "superscript", "charAlign": "emBoxCenter", "proportionalMetrics": true, "tateChuYoko": true, "standardVerticalRoman": true, - "noBreak": true, "charDirection": "rightToLeft", "digits": "hindi" + "noBreak": true, "charDirection": "rightToLeft", "digits": "hindi", "fontHeightReference": "capHeight" }), ) .unwrap(); }; let plain = runs(&app)[0].1.clone(); - assert_eq!(differs(&plain, &CharStyle::default()), [false; 19]); + assert_eq!(differs(&plain, &CharStyle::default()), [false; 20]); custom(&mut app); let styled = runs(&app)[0].1.clone(); - assert_eq!(differs(&styled, &CharStyle::default()), [true; 19]); + assert_eq!(differs(&styled, &CharStyle::default()), [true; 20]); app.run("select.set", json!({"ids": [id]})).unwrap(); reset_panel(&mut app); assert_eq!(runs(&app), [("One 12".to_string(), plain.clone())]); diff --git a/docs/mcp.md b/docs/mcp.md index ddd23ecfae..0f586deb38 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5119,6 +5119,27 @@ A digit the font lacks comes from a fallback font. Default and saved only when s {"name":"run_command","arguments":{"command":"text.setFormat","params":{"digits":"hindi"}}} ``` +## Font height reference + +`text.setFormat {fontHeightReference: "emBox"|"capHeight"|"xHeight"|"icfBox"}` (the selected type, or `ids`) and +`text.setRangeStyle {id, start, end, fontHeightReference}` (a range) set the height of the font that the characters' font +size measures, as the Character panel's Set Font Height Reference dropdown does (panel menu › Show Font Height Options). +With `emBox`, the default, the font size is the size of the em square. With `capHeight`, `xHeight` or `icfBox`, the +characters are set at the em size at which the font's cap height or x height (OS/2 `sCapHeight`, `sxHeight`), or the +height of its ideographic character face (the BASE table's `icfb` and `icft`, else the ink of some ideographs and kana; +across a vertical line, its width), equals the font size: 20 pt Cap Height type in a font whose capitals are 0.7 em +tall is set at about 28.6 pt, and its font size stays 20 pt. With a font that has no such value, or one outside 0.1 to 2 +em, the size measures the em box. Auto leading, tracking and kerning follow the em size the characters are set at (the +Character panel's Leading field shows that Auto leading, and `type.step {attribute: "leading"}` starts from it); +explicit leading and baseline shift stay in points, and an inline graphic keeps its size. +SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size. DXF export writes 0.7 times the em +size as each TEXT entity's height (group 40, the height of its capitals). +Saved only when not `emBox`. One undo step. + +```json +{"name":"run_command","arguments":{"command":"text.setFormat","params":{"fontHeightReference":"capHeight"}}} +``` + ## Language `text.setFormat {language}` (the selected type, or `ids`) and `text.setRangeStyle {id, start, end, language}` (a range) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ddcee05b26..581f4bd9fd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -855,6 +855,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Kerning across style runs:** characters that differ only in fill, stroke, underline, strikethrough, overprint, character style name, leading, baseline shift, rotation, Character Alignment, kerning, or tracking that keeps or drops ligatures alike are shaped together, so restyling one character keeps the font's kerning pairs with its neighbors. A character with manual kerning that follows one with automatic kerning keeps the font's kerning with it (unless All Caps or Small Caps sets it as two letters, as ß becomes SS), and its value replaces the font's kerning after it. A ligature does not form across a change of style, and a change of font, size or OpenType features still shapes the characters apart. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/text/src/tests/bidi.rs`. - **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515). - **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `<use>` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). + The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in rectangular area type, rows and columns included. In area type of another shape, or with text wrap, such a paragraph is broken with the Single-line Composer. The Character panel's Small Caps, Superscript and Subscript buttons and the panel menu's items of the same names turn small caps and the superscript or subscript position on and off for the selected type, or for the text the Type tool has selected (`text.setFormat` or `text.setRangeStyle` `{smallCaps, position}`), in Document Setup's proportions. Turning Superscript on turns Subscript off, and turning Subscript on turns Superscript off. A button or item shows as on when the first selected character (at a caret, the character before it) has its attribute. The OpenType panel's Stylistic Alternates and Titling Alternates checkboxes turn `salt` and `titl` on and off for the selected type, and its Figure menu lists Default Figure, Tabular Lining, Proportional Lining, Proportional Oldstyle and Tabular Oldstyle; Proportional Lining sets `pnum` and `lnum` and turns `tnum` and `onum` off, Tabular Lining turns `pnum` off and keeps `lnum`, Proportional Oldstyle turns `lnum` off and keeps `pnum`, and Default Figure and Tabular Oldstyle turn `pnum` and `lnum` off. Behavior reference: [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) and [Use swashes, titling alternates, or stylistic alternates](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/use-swashes-titling-alternates-or-stylistic-alternates.html) (public documentation). Tests: `panels::opentype::tests`. From 94ef9b87c28bd289f270d696454dd34a08f3200b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 19:37:34 -0700 Subject: [PATCH 252/260] Type: Character panel toggles show off for a mixed selection, and text.setFormat checks on/off values The Character panel's All Caps, Underline and Strikethrough buttons, and its menu's All Caps, Underline, Strikethrough, Proportional Metrics, Tate-chu-yoko and No Break, read the first selected character's style. With only some characters marked they could show on, and choosing one turned the attribute off for every character. They now show on only when every selected character has the attribute, and a click on a mixed selection turns it on for all, as Small Caps and Standard Vertical Roman Alignment do. type.underline (Cmd+Shift+U) underlines a mixed selection the same way. The Character Alignment and Digits submenus check no item while the selected characters differ. text.setFormat ignored a value that was not true or false for underline, strikethrough, allCaps, proportionalMetrics, tateChuYoko, standardVerticalRoman, noBreak, hyphenate, hyphenateCapitalized and romanHangingPunctuation. It now refuses it with "`<key>` must be true or false" and changes nothing, as text.setRangeStyle does. --- crates/engine/src/cmd/panelcmds.rs | 16 +++ crates/engine/src/tests/textedit.rs | 13 +- crates/ui-egui/src/panels/character.rs | 41 +++--- crates/ui-egui/src/panels/character/tests.rs | 140 ++++++++++++++++++- docs/mcp.md | 3 +- docs/target-app-parity.md | 1 + 6 files changed, 191 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 7934dbe691..68449f5ebd 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -318,6 +318,22 @@ fn spacing_param(p: &Value, key: &str, c: &str) -> Result<Option<[Option<f64>; 3 fn set_format(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.setFormat"; let ids = super::typecmd::text_targets(s, p, C)?; + check_switches( + p, + &[ + "underline", + "strikethrough", + "allCaps", + "proportionalMetrics", + "tateChuYoko", + "standardVerticalRoman", + "noBreak", + "hyphenate", + "hyphenateCapitalized", + "romanHangingPunctuation", + ], + C, + )?; let num = |k: &str| p.get(k).and_then(Value::as_f64); let flag = |k: &str| p.get(k).and_then(Value::as_bool); let kerning = match p.get("kerning") { diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 025cf6d30a..178f8f5284 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -325,6 +325,16 @@ fn type_commands_refuse_a_number_or_boolean_given_as_text() { ("text.setRangeStyle", json!({"id": id.0, "allCaps": 1}), "allCaps"), ("text.setRangeStyle", json!({"id": id.0, "noBreak": "true"}), "noBreak"), ("text.setRangeStyle", json!({"id": id.0, "size": 30, "tateChuYoko": 1}), "tateChuYoko"), + ("text.setFormat", json!({"ids": [id.0], "underline": "true"}), "underline"), + ("text.setFormat", json!({"ids": [id.0], "strikethrough": 1}), "strikethrough"), + ("text.setFormat", json!({"ids": [id.0], "allCaps": "false"}), "allCaps"), + ("text.setFormat", json!({"ids": [id.0], "proportionalMetrics": 1}), "proportionalMetrics"), + ("text.setFormat", json!({"ids": [id.0], "tateChuYoko": "true"}), "tateChuYoko"), + ("text.setFormat", json!({"ids": [id.0], "standardVerticalRoman": "true"}), "standardVerticalRoman"), + ("text.setFormat", json!({"ids": [id.0], "rotation": 10, "noBreak": 1}), "noBreak"), + ("text.setFormat", json!({"ids": [id.0], "hyphenate": "false"}), "hyphenate"), + ("text.setFormat", json!({"ids": [id.0], "hyphenateCapitalized": 0}), "hyphenateCapitalized"), + ("text.setFormat", json!({"ids": [id.0], "romanHangingPunctuation": "true"}), "romanHangingPunctuation"), ("text.getRange", json!({"id": id.0, "effective": "true"}), "effective"), ("type.opticalMarginAlignment", json!({"on": "true"}), "on"), ("type.systemLayout", json!({"on": "true"}), "on"), @@ -338,12 +348,13 @@ fn type_commands_refuse_a_number_or_boolean_given_as_text() { assert!(wrong.is_empty(), "not refused: {wrong:#?}"); let style = json!({"id": id.0, "size": 30, "underline": true, "tracking": null, "start": null, "noBreak": true}); s.execute("text.setRangeStyle", &style).unwrap(); + s.execute("text.setFormat", &json!({"ids": [id.0], "strikethrough": true, "hyphenate": null})).unwrap(); s.execute("type.size.increase", &json!({"by": null})).unwrap(); s.execute("type.opticalMarginAlignment", &json!({"on": true})).unwrap(); s.execute("type.ruby", &json!({"text": "a", "size": null, "overhang": false})).unwrap(); let t = obj(&s, id); let st = &t.runs[0].style; - assert!(st.underline && st.no_break && t.optical_margin && st.size > 30.0, "{st:?}"); + assert!(st.underline && st.strikethrough && st.no_break && t.optical_margin && st.size > 30.0, "{st:?}"); assert!(!t.ruby.is_empty() && t.ruby.iter().all(|r| !r.overhang && r.size_percent == 50.0), "{:?}", t.ruby); } diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index f00c33d70f..db01f2e387 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -419,11 +419,12 @@ pub(crate) fn highlight(app: &mut VectorcraftApp, field: Field) -> Result<Value, } /// `type.underline` (Cmd+Shift+U): what the Underline button does, on the text the panels act on. -/// Returns whether the text is now underlined. +/// Returns whether the text is now underlined: off only when every character was underlined. pub(crate) fn toggle_underline(app: &mut VectorcraftApp) -> Result<Value, String> { - let (s, _) = text_style(app).ok_or("select some type first")?; - format(app, json!({"underline": !s.underline})); - Ok(json!(!s.underline)) + text_style(app).ok_or("select some type first")?; + let on = shared(app, |s| s.underline) != Some(true); + format(app, json!({"underline": on})); + Ok(json!(on)) } /// `text.setRangeStyle` with `p` on the range the Type tool has selected (the whole text when @@ -946,15 +947,19 @@ fn attributes(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.add_space(4.0); ui.horizontal(|ui| { + // On only when every character the panel acts on has it; a mixed selection turns it on. + let all_caps = shared(app, |s| s.all_caps) == Some(true); let small = shared(app, |s| s.small_caps.is_some()) == Some(true); let position = shared(app, |s| s.position).map(|p| p.id()).unwrap_or(""); + let underline = shared(app, |s| s.underline) == Some(true); + let strike = shared(app, |s| s.strikethrough) == Some(true); for (kind, tip, on, change) in [ - (Glyph::AllCaps, tl!("All Caps"), s.all_caps, json!({"allCaps": !s.all_caps})), + (Glyph::AllCaps, tl!("All Caps"), all_caps, json!({"allCaps": !all_caps})), (Glyph::SmallCaps, tl!("Small Caps"), small, json!({"smallCaps": !small})), (Glyph::Super, tl!("Superscript"), position == "superscript", position_toggle(position, "superscript")), (Glyph::Sub, tl!("Subscript"), position == "subscript", position_toggle(position, "subscript")), - (Glyph::Underline, tl!("Underline"), s.underline, json!({"underline": !s.underline})), - (Glyph::Strike, tl!("Strikethrough"), s.strikethrough, json!({"strikethrough": !s.strikethrough})), + (Glyph::Underline, tl!("Underline"), underline, json!({"underline": !underline})), + (Glyph::Strike, tl!("Strikethrough"), strike, json!({"strikethrough": !strike})), ] { if style_toggle(ui, kind, tip, on) { format(app, change); @@ -1093,8 +1098,7 @@ fn digits_items(app: &mut VectorcraftApp, ui: &mut Ui, digits: Option<vectorcraf } pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { - let st = text_style(app); - let has = st.is_some(); + let has = text_style(app).is_some(); let hidden: bool = pstate(ui.ctx(), "ch-hide-options"); if menu_item(ui, if hidden { tl!("Show Options") } else { tl!("Hide Options") }, true, false) { set_pstate(ui.ctx(), "ch-hide-options", !hidden); @@ -1109,11 +1113,12 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { set_pstate(ui.ctx(), FONT_HEIGHT_OPTIONS, !heights); } ui.separator(); - let s = st.map(|x| x.0); + // A check item is checked when every character the panel acts on has it; choosing it with a + // mixed selection turns it on. for (label, key, on) in [ - (tl!("All Caps"), "allCaps", s.as_ref().is_some_and(|s| s.all_caps)), - (tl!("Underline"), "underline", s.as_ref().is_some_and(|s| s.underline)), - (tl!("Strikethrough"), "strikethrough", s.as_ref().is_some_and(|s| s.strikethrough)), + (tl!("All Caps"), "allCaps", shared(app, |s| s.all_caps) == Some(true)), + (tl!("Underline"), "underline", shared(app, |s| s.underline) == Some(true)), + (tl!("Strikethrough"), "strikethrough", shared(app, |s| s.strikethrough) == Some(true)), ] { if menu_item(ui, label, has, on) { format(app, json!({key: !on})); @@ -1134,7 +1139,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { // Character Alignment: where characters smaller than the largest on their line line up, with // the East Asian options. if app.session.prefs.show_east_asian_options { - let align = s.as_ref().map(|s| s.char_align); + let align = shared(app, |s| s.char_align); ui.add_enabled_ui(has, |ui| { // Indented like the items beside it (their check column). ui.menu_button(format!(" {}", tl!("Character Alignment")), |ui| { @@ -1154,12 +1159,12 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { }); }); // Proportional Metrics: full-width glyphs on the font's proportional widths (`palt`, `vpal`). - let proportional = s.as_ref().is_some_and(|s| s.proportional_metrics); + let proportional = shared(app, |s| s.proportional_metrics) == Some(true); if menu_item(ui, tl!("Proportional Metrics"), has, proportional) { format(app, json!({"proportionalMetrics": !proportional})); } // Tate-chu-yoko: the selected characters stand side by side across one em of a vertical column. - let tcy = s.as_ref().is_some_and(|s| s.tate_chu_yoko); + let tcy = shared(app, |s| s.tate_chu_yoko) == Some(true); if menu_item(ui, tl!("Tate-chu-yoko"), has, tcy) { format(app, json!({"tateChuYoko": !tcy})); } @@ -1175,7 +1180,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { // Digits: the numeral system the selected characters' digits are drawn in, with the Middle // Eastern (Indic) options, as Paragraph Direction is in the Paragraph panel. if app.session.prefs.show_indic_options { - let digits = s.as_ref().map(|s| s.digits); + let digits = shared(app, |s| s.digits); ui.add_enabled_ui(has, |ui| { ui.menu_button(format!(" {}", tl!("Digits")), |ui| digits_items(app, ui, digits)); }); @@ -1185,7 +1190,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { ui.separator(); } // No Break: the selected characters stay on one line. - let no_break = s.as_ref().is_some_and(|s| s.no_break); + let no_break = shared(app, |s| s.no_break) == Some(true); if menu_item(ui, tl!("No Break"), has, no_break) { format(app, json!({"noBreak": !no_break})); } diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index da7a3dc09c..f4774dd016 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -415,9 +415,17 @@ fn bold_and_italic_pick_the_familys_own_faces() { } /// From one frame of the panel: a point inside each of the Small Caps, Superscript and -/// Subscript buttons, and which of them are drawn on. The two buttons with a "1" are -/// Superscript (the "1" up) and Subscript; Small Caps is the button before them. +/// Subscript buttons, and which of them are drawn on. fn script_buttons(ctx: &egui::Context, app: &mut VectorcraftApp) -> ([egui::Pos2; 3], [bool; 3]) { + let (points, on) = style_buttons(ctx, app); + ([points[1], points[2], points[3]], [on[1], on[2], on[3]]) +} + +/// From one frame of the panel: a point inside each of the All Caps, Small Caps, Superscript, +/// Subscript, Underline and Strikethrough buttons, and which of them are drawn on. The two buttons +/// with a "1" are Superscript (the "1" up) and Subscript; the others sit one button apart from them +/// in that order. +fn style_buttons(ctx: &egui::Context, app: &mut VectorcraftApp) -> ([egui::Pos2; 6], [bool; 6]) { let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui)); out.textures_delta.clear(); fn walk(s: &egui::Shape, on: egui::Color32, ones: &mut Vec<egui::Pos2>, lit: &mut Vec<egui::Rect>) { @@ -437,7 +445,8 @@ fn script_buttons(ctx: &egui::Context, app: &mut VectorcraftApp) -> ([egui::Pos2 // Each "1" is drawn 6 points right of its button's center and 5 points above or below it. let y = (sup.y + sub.y) / 2.0; let (sup, sub) = (egui::pos2(sup.x - 6.0, y), egui::pos2(sub.x - 6.0, y)); - let points = [sup - vec2(sub.x - sup.x, 0.0), sup, sub]; + let step = vec2(sub.x - sup.x, 0.0); + let points = [sup - step * 2.0, sup - step, sup, sub, sub + step, sub + step * 2.0]; (points, points.map(|p| lit.iter().any(|r| r.contains(p)))) } @@ -802,6 +811,131 @@ fn character_mixed_small_caps_and_position_show_off() { assert_eq!(checked(&mut app), [false, false, false]); } +/// The All Caps, Underline and Strikethrough buttons are drawn off when only some of the selected +/// characters have them, and a click turns them on for every character. +#[test] +fn mixed_all_caps_underline_and_strikethrough_buttons_show_off_and_turn_on() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "AB", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 1, "allCaps": true, "underline": true, "strikethrough": true})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let flags = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| [r.style.all_caps, r.style.underline, r.style.strikethrough]).collect::<Vec<_>>(), + _ => panic!("text"), + }; + let ctx = egui::Context::default(); + let (at, lit) = style_buttons(&ctx, &mut app); + assert_eq!([lit[0], lit[4], lit[5]], [false; 3]); + for (i, button) in [0, 4, 5].into_iter().enumerate() { + super::super::tests_appearance::click(&ctx, &mut app, at[button], show); + assert!(flags(&app).iter().all(|f| f[i]), "button {button}: {:?}", flags(&app)); + assert!(style_buttons(&ctx, &mut app).1[button], "button {button}"); + } +} + +/// `type.underline` does what the Underline button does: with only some of the selected characters +/// underlined it underlines all of them, and with all of them underlined it turns underlining off. +#[test] +fn underline_command_underlines_a_mixed_selection() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "AB", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 1, "underline": true})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let underlined = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| r.style.underline).collect::<Vec<_>>(), + _ => panic!("text"), + }; + assert_eq!(super::toggle_underline(&mut app), Ok(json!(true))); + assert!(underlined(&app).iter().all(|u| *u), "{:?}", underlined(&app)); + assert_eq!(super::toggle_underline(&mut app), Ok(json!(false))); + assert!(underlined(&app).iter().all(|u| !*u), "{:?}", underlined(&app)); +} + +/// The panel menu's All Caps, Underline, Strikethrough, Proportional Metrics, Tate-chu-yoko and +/// No Break are unchecked when only some of the selected characters have them, and choosing one +/// turns it on for every character. +#[test] +fn mixed_check_items_show_unchecked_and_turn_on() { + type Attribute = fn(&CharStyle) -> bool; + let items: [(&str, &str, Attribute); 6] = [ + ("All Caps", "allCaps", |s| s.all_caps), + ("Underline", "underline", |s| s.underline), + ("Strikethrough", "strikethrough", |s| s.strikethrough), + ("Proportional Metrics", "proportionalMetrics", |s| s.proportional_metrics), + ("Tate-chu-yoko", "tateChuYoko", |s| s.tate_chu_yoko), + ("No Break", "noBreak", |s| s.no_break), + ]; + let mut wrong = vec![]; + for (label, key, has) in items { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.show_east_asian_options = true; + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "AB"})).unwrap()["id"].as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 1, key: true})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let on = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| has(&r.style)).collect::<Vec<_>>(), + _ => panic!("text"), + }; + assert_eq!(on(&app), [true, false], "{label}"); + let ctx = egui::Context::default(); + let row = |app: &mut VectorcraftApp| { + let texts = super::super::tests_appearance::frame_events(&ctx, app, vec![], menu); + texts.into_iter().find(|(t, _)| t.trim_start_matches(['✓', ' ']) == label).unwrap_or_else(|| panic!("{label} missing")) + }; + let (text, at) = row(&mut app); + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + let shown = row(&mut app).0; + if text.starts_with('✓') || !on(&app).iter().all(|o| *o) || !shown.starts_with('✓') { + wrong.push(format!("{label}: shown as {text:?}, then {:?} and {shown:?}", on(&app))); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// The panel menu's Character Alignment and Digits submenus check no item when the selected +/// characters differ, and check the value they share. +#[test] +fn character_alignment_and_digits_check_nothing_for_a_mixed_selection() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.show_east_asian_options = true; + app.session.prefs.show_indic_options = true; + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "A1"})).unwrap()["id"].as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 1, "charAlign": "emBoxTop", "digits": "hindi"})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let press = |pos: egui::Pos2, pressed: bool| egui::Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: Default::default(), + }; + let ticked = |texts: &[(String, egui::Rect)]| texts.iter().filter_map(|(t, _)| t.strip_prefix("✓ ")).map(str::to_string).collect::<Vec<_>>(); + // The items checked in the submenu `name` opens (not in the panel menu itself), in a fresh + // context, so that no other submenu is open. + let checked = |app: &mut VectorcraftApp, name: &str| { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut frame = |events: Vec<egui::Event>| super::super::tests_appearance::frame_events(&ctx, app, events, menu); + let texts = frame(vec![]); + let before = ticked(&texts); + let sub = texts.iter().find(|(t, _)| t.trim() == name).unwrap_or_else(|| panic!("{name} missing from {texts:?}")).1.center(); + for e in [egui::Event::PointerMoved(sub), press(sub, true), press(sub, false)] { + frame(vec![e]); + } + let texts = frame(vec![]); + assert!(texts.iter().any(|(t, _)| t.contains("Roman Baseline") || t.contains("Hindi")), "{name} did not open: {texts:?}"); + ticked(&texts).into_iter().filter(|t| !before.contains(t)).collect::<Vec<_>>() + }; + let mixed = (checked(&mut app, "Character Alignment"), checked(&mut app, "Digits")); + assert_eq!(mixed, (vec![], vec![])); + app.run("text.setRangeStyle", json!({"id": id, "charAlign": "emBoxTop", "digits": "hindi"})).unwrap(); + let same = (checked(&mut app, "Character Alignment"), checked(&mut app, "Digits")); + assert_eq!(same, (vec!["Em Box Top/Right".to_string()], vec!["Hindi".to_string()])); +} + /// At a caret in text the Type tool edits, with no characters selected, the Character /// Direction items are disabled: a click on one leaves the direction of every character as it was. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 0f586deb38..8f0b9b7fff 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1155,7 +1155,8 @@ These commands refuse a string, a number or another value that is not true or fa `` `closed` must be true or false ``, naming the key, and leave the document and its undo history as they were: `clockwise` in `shape.spiral`; `closed` in `shape.arc` and `path.create`; `vertical` and `placeholder` in `text.create` and `text.createInPath`; `underline`, `strikethrough`, `allCaps`, `proportionalMetrics`, `tateChuYoko`, `standardVerticalRoman` and `noBreak` -in `text.setRangeStyle`; `effective` in `text.getRange`; `on` in `type.opticalMarginAlignment`, `type.systemLayout` +in `text.setRangeStyle` and `text.setFormat`, which also checks `hyphenate`, `hyphenateCapitalized` and +`romanHangingPunctuation`; `effective` in `text.getRange`; `on` in `type.opticalMarginAlignment`, `type.systemLayout` and `type.fractionalWidths`; `remove` and `overhang` in `type.ruby`; `expandInstances` in `symbol.delete`; `alt` in `symbol.spray` and `symbol.adjust`; `spot` and `global` in `swatch.new` and `swatch.edit`; `unlink` in `swatch.delete`; `fromArtwork`, `toGlobal` and `includeTints` in `swatch.newGroup`; `global` and `selection` in diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 581f4bd9fd..3c5f07c836 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -892,6 +892,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Tabs panel menu's Clear All Tabs (`text.tabs.clear`), Delete Tab and Repeat Tab (`text.tabs.set`) can be chosen while the panel's ruler shows tab stops. Delete Tab removes the stop selected on the ruler. Repeat Tab replaces the stops after the selected stop with up to 20 copies of it. The copies are spaced by the selected stop's distance from the stop before it, or from the paragraph's left indent when it is the first stop, and no copy is placed at 2,000 pt or beyond. Clear All Tabs removes every stop, so the default stops every ½ inch apply again. - **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian and Finnish also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). Character panel menu › Standard Vertical Roman Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {standardVerticalRoman}`, off by default) stands the selected Latin letters, digits and other half-width characters upright one below the other in vertical type instead of rotating them ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); spaces keep their width, tate-chu-yoko blocks stay across the column, and Character Style Options gives it its own checkbox beside Character Alignment. + The Character panel's All Caps, Underline and Strikethrough buttons and its menu's All Caps, Underline, Strikethrough, Proportional Metrics, Tate-chu-yoko and No Break show off while only some of the selected characters have the attribute, and choosing one then turns it on for all of them, as `type.underline` (Cmd+Shift+U) does for underlining; the Character Alignment and Digits submenus check no item while the selected characters differ. `text.setFormat` refuses a value that is not true or false for its on/off attributes, as `text.setRangeStyle` does. - **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `<mask>` and PDF soft masks. The constant alpha soft mask that PDF and `.ai` export draw a CMYK page with transparency through is white, so applications that read every soft mask by its luminosity show the page too (#1359, part of #1286). Isolation mode and opacity mask editing exclude each other ([transparency and blending modes](https://web.archive.org/web/20230102045151/https://helpx.adobe.com/illustrator/using/transparency-blending-modes.html)): in isolation mode a click or Alt-click on the mask thumbnail does not edit the mask, and Make Mask is off for one object; while a mask is edited, Enter Isolation Mode and Object › Perspective › Edit Text are off, the Contextual Task Bar leaves out Isolate, and Quick Actions leave out Isolate Group. Pattern editing mode and opacity mask editing exclude each other, by a rule of VectorCraft itself: in pattern editing mode a click or Alt-click on the mask thumbnail does not edit the mask, and Make Mask is off for one object; while a mask is edited, Object › Pattern › Make and Edit Pattern are off. From 5716a996abfb1ef5f1679dff415c45d4c204c60f Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 19:59:12 -0700 Subject: [PATCH 253/260] Type: Touch Type moves a character rotated near 90 degrees across its line Baseline shift now moves a character in the line's frame, outside Character Rotation, so a positive shift moves a character up from its line at any rotation, and the character turns about its shifted pen position. The Touch Type tool splits a drag into its part along the line (kerning) and its part up from the line (baseline shift) at every rotation; before, within about 6 degrees of a quarter turn it dropped the cross-line part. Characters that already combine a rotation with a baseline shift are drawn in a new position. Their stored values do not change. - text: glyph transform order, PositionedGlyph::pivot (the turning point), tab leaders in the same order - tools: Touch Type splits drags against the line's up axis and measures rotate-handle turns about the shifted pen position - engine: text.touchType description; dy is up from the line - docs: mcp.md Touch Type paragraph, target-app-parity.md progress line --- crates/engine/src/cmd/textedit.rs | 7 ++- crates/engine/src/tests/textedit.rs | 61 ++++++++++++++++++++- crates/text/src/layout.rs | 15 +++++- crates/text/src/layout/breaking.rs | 2 +- crates/text/src/layout/ruby.rs | 1 + crates/text/src/lib.rs | 3 ++ crates/text/src/tests/bidi.rs | 1 + crates/text/src/tests/typo.rs | 45 ++++++++++++++++ crates/tools/src/touchtype.rs | 28 +++++----- crates/tools/src/touchtype/tests.rs | 83 +++++++++++++++++++++++++++++ docs/mcp.md | 7 +-- docs/target-app-parity.md | 1 + 12 files changed, 230 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 5f5f653a97..c028e29b1f 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> { "Touch Type", [], None, - "{id, start: byte (a character of it), dx?: pt, dy?: pt, hScale?: %, vScale?: %, rotation?: deg} change one character (a ligature, one glyph for several characters, as a whole) as a Touch Type tool drag does, as one undo step: dx moves it along its line in reading order by changing the kerning of the character before it on the line and its own kerning, and the characters after it stay where they are (an error for the first character of a line and for a right-to-left character; limited to what kerning from -1000 to 10000 can give); dy raises it (baseline shift, along its own up axis when it is rotated); dx and dy are document points; hScale (including the object transform), vScale and rotation set its scales and rotation as text.setRangeStyle does. The kerning of the two characters also keeps the character and the ones after it where they were along the line when the font kerned them with their neighbors; a wider or narrower character moves the ones after it by the change in its width → {id, start, end} (the character's bytes)", + "{id, start: byte (a character of it), dx?: pt, dy?: pt, hScale?: %, vScale?: %, rotation?: deg} change one character (a ligature, one glyph for several characters, as a whole) as a Touch Type tool drag does, as one undo step: dx moves it along its line in reading order by changing the kerning of the character before it on the line and its own kerning, and the characters after it stay where they are (an error for the first character of a line and for a right-to-left character; limited to what kerning from -1000 to 10000 can give); dy raises it (baseline shift, up from its line whatever its rotation, also for the first character of a line and a right-to-left character); dx and dy are document points; hScale (including the object transform), vScale and rotation set its scales and rotation as text.setRangeStyle does. The kerning of the two characters also keeps the character and the ones after it where they were along the line when the font kerned them with their neighbors; a wider or narrower character moves the ones after it by the change in its width → {id, start, end} (the character's bytes)", has_doc, touch_type ), @@ -916,9 +916,8 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> { }); }; // The baseline shift that raises the character `dy` document points. Baseline shift moves it - // along its own up axis, turned with its rotation (the new one, when the call sets it), by a - // length that the object transform, Shrink Text to Fit and a path effect such as Skew scale: - // two layouts with the call's other changes and shifts one step apart, both within the range, + // up from its line, whatever its rotation, by a length that the object transform, Shrink Text + // to Fit and a path effect such as Skew scale: two layouts with the call's other changes and shifts one step apart, both within the range, // measure that length. Neither shift is one that a run already has, so the character's run // splits off alike in both. let raise = if dy == 0.0 { diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 178f8f5284..ed47cb1d57 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -518,7 +518,7 @@ fn touch_type_moves_one_character_in_centered_and_right_aligned_lines() { } } -/// `dy` moves a rotated character that many document points along its own up axis, also in type +/// `dy` moves a rotated character that many document points up from its line, also in type /// scaled unevenly. #[test] fn touch_type_raises_a_rotated_character_in_unevenly_scaled_type() { @@ -529,9 +529,66 @@ fn touch_type_raises_a_rotated_character_in_unevenly_scaled_type() { let before = glyph_pens(&s, id); s.execute("text.touchType", &json!({"id": id.0, "start": 1, "dy": 10})).unwrap(); let (x, y) = moved_by(&before, &glyph_pens(&s, id), 1); - assert!(((x * x + y * y).sqrt() - 10.0).abs() < 1e-6, "({x}, {y})"); + assert!(near((x, y), (0.0, -10.0)), "({x}, {y})"); } +/// A character rotated near or at a quarter turn moves across its line and along it: in "ABCD" +/// with the B at 85, 90 and 95 degrees, `dx` 10 and `dy` 4 move the B 10 pt right and 4 pt up and +/// leave the C and D where they are, through baseline shift and kerning only, with Auto and +/// Optical kerning and in type scaled unevenly. Undo, redo and the native format keep the place. +#[test] +fn touch_type_moves_a_character_turned_near_a_quarter_turn_across_its_line() { + for rotation in [85.0, 90.0, 95.0, -90.0] { + for (kerning, scaled) in [("auto", false), ("optical", false), ("auto", true)] { + let case = format!("{rotation}°, {kerning}, scaled {scaled}"); + let mut s = session(); + let id = NodeId(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "ABCD", "size": 40})).unwrap()["id"].as_u64().unwrap()); + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": kerning})).unwrap(); + if scaled { + s.execute("object.transform", &json!({"ids": [id.0], "matrix": [2, 0, 0, 0.5, 0, 0]})).unwrap(); + } + s.execute("text.touchType", &json!({"id": id.0, "start": 1, "rotation": rotation})).unwrap(); + let before = glyph_pens(&s, id); + let runs_before = obj(&s, id).runs; + s.execute("text.touchType", &json!({"id": id.0, "start": 1, "dx": 10, "dy": 4})).unwrap(); + let after = glyph_pens(&s, id); + assert!(near(moved_by(&before, &after, 1), (10.0, -4.0)), "{case}: {:?}", moved_by(&before, &after, 1)); + for byte in [0, 2, 3] { + assert!(near(moved_by(&before, &after, byte), (0.0, 0.0)), "{case}, byte {byte}: {:?}", moved_by(&before, &after, byte)); + } + // Only kerning and baseline shift change. + let t = obj(&s, id); + let style = |byte: usize| vectorcraft_text::edit::slice_runs(&t.runs, byte, byte + 1)[0].style.clone(); + let plain = |mut st: CharStyle| { + st.kerning = None; + st.baseline_shift = 0.0; + st + }; + for byte in 0..4 { + let was = vectorcraft_text::edit::slice_runs(&runs_before, byte, byte + 1)[0].style.clone(); + assert_eq!(plain(style(byte)), plain(was), "{case}, byte {byte}"); + } + let shift = style(1).baseline_shift; + assert!(shift > 0.0, "{case}: {shift}"); + // A drag straight across the line is baseline shift alone. + let before = glyph_pens(&s, id); + s.execute("text.touchType", &json!({"id": id.0, "start": 1, "dy": -6})).unwrap(); + assert!(near(moved_by(&before, &glyph_pens(&s, id), 1), (0.0, 6.0)), "{case}: {:?}", moved_by(&before, &glyph_pens(&s, id), 1)); + s.execute("edit.undo", &json!({})).unwrap(); + let moved = glyph_pens(&s, id); + assert!(near(moved_by(&after, &moved, 1), (0.0, 0.0)), "{case}: undone"); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + // The native format keeps both attributes and the place they give. + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let NodeKind::Text(reopened) = &back.node(id).unwrap().kind else { panic!("not text") }; + assert_eq!(reopened.runs, obj(&s, id).runs, "{case}"); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), reopened); + let pens: Vec<(usize, Point)> = lay.glyphs.iter().map(|g| (g.byte, reopened.xf * (g.xf * Point::ZERO))).collect(); + assert!(near(moved_by(&moved, &pens, 1), (0.0, 0.0)), "{case}: reopened"); + } + } +} /// `dy` moves a character that many document points in type scaled up 2000 times, where baseline /// shift is limited to 0.648 pt of text space. #[test] diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index f217eaa3a3..67c52220d3 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -227,12 +227,22 @@ impl Ctx<'_> { let local = match &g.inline { // Inline graphics: art space to glyph space (no font outline). Some(ib) => Affine::translate((-lead, -g.bshift)) * ib.xf, + // Baseline shift moves the glyph across its line, and Character Rotation then turns it + // about its shifted pen position, so the shift is across the line at any rotation. None => { - Affine::rotate(-g.rotation.to_radians()) * Affine::translate((g.dx - lead, g.dy - g.bshift)) * Affine::scale_non_uniform(g.sx, g.sy) + Affine::translate((0.0, -g.bshift)) + * Affine::rotate(-g.rotation.to_radians()) + * Affine::translate((g.dx - lead, g.dy)) + * Affine::scale_non_uniform(g.sx, g.sy) } }; + // The turning point in font units, which later moves of the glyph's transform keep. + let pivot = match local.determinant() { + det if det != 0.0 && det.is_finite() => local.inverse() * Point::new(0.0, -g.bshift), + _ => Point::ZERO, + }; let unturned = if g.inline.is_none() && g.rotation != 0.0 && g.sx != 0.0 && g.sy != 0.0 { - let placed = Affine::translate((g.dx - lead, g.dy - g.bshift)) * Affine::scale_non_uniform(g.sx, g.sy); + let placed = Affine::translate((g.dx - lead, g.dy)) * Affine::scale_non_uniform(g.sx, g.sy); placed.inverse() * Affine::rotate(g.rotation.to_radians()) * placed } else { Affine::IDENTITY @@ -306,6 +316,7 @@ impl Ctx<'_> { colour, bend: None, unturned, + pivot, }); } diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index b83640d029..54d8941e83 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -224,7 +224,7 @@ pub(super) fn leader_outline(db: &FontDb, g: &SGlyph, leader: &str, origin: f64, } let first = ((from - origin) / width - EPS).ceil(); let copies = (((to - origin) / width + EPS).floor() - first).clamp(0.0, MAX_LEADER_COPIES) as usize; - let local = Affine::rotate(-g.rotation.to_radians()) * Affine::translate((0.0, -g.bshift)) * Affine::scale_non_uniform(g.sx, g.sy); + let local = Affine::translate((0.0, -g.bshift)) * Affine::rotate(-g.rotation.to_radians()) * Affine::scale_non_uniform(g.sx, g.sy); for k in 0..copies { let mut pen = origin + (first + k as f64) * width; for &(gid, adv) in &glyphs { diff --git a/crates/text/src/layout/ruby.rs b/crates/text/src/layout/ruby.rs index 54681da89d..59ce52c4ca 100644 --- a/crates/text/src/layout/ruby.rs +++ b/crates/text/src/layout/ruby.rs @@ -368,5 +368,6 @@ fn ruby_glyph(g: &PositionedGlyph, m: Affine, run: usize, byte: usize, line: usi colour: None, bend: None, unturned: Affine::IDENTITY, + pivot: m * g.origin, } } diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index a382eabce2..ac82b90083 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -142,6 +142,9 @@ pub struct PositionedGlyph { /// Font units → font units: `xf * unturned` places the glyph as it would be placed without /// its Character Rotation. The identity for a glyph without one. pub unturned: Affine, + /// Font units: `xf * pivot` is the point its Character Rotation turns it about, its pen + /// position on the baseline moved by its baseline shift. + pub pivot: Point, } /// How a glyph on a path is bent along it: a point of its pen space (x along its advance from its diff --git a/crates/text/src/tests/bidi.rs b/crates/text/src/tests/bidi.rs index a48d2c020d..7e49312979 100644 --- a/crates/text/src/tests/bidi.rs +++ b/crates/text/src/tests/bidi.rs @@ -164,6 +164,7 @@ fn lines_of_clusters(lines: &[&[(usize, usize, f64)]], rtl: bool) -> TextLayout colour: None, bend: None, unturned: Affine::IDENTITY, + pivot: Point::new(x, baseline), }); x += advance; } diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 389fb985d1..6a15896e81 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -1430,6 +1430,51 @@ fn restyling_one_character_keeps_its_kerning_with_its_neighbors() { assert!((l.lines[1].baseline - l.lines[0].baseline - 60.0).abs() < 1e-9, "{:?}", l.lines); } +/// Baseline shift moves a rotated character up from its line by the shift, at any rotation, in +/// point type and on a slanted path, and leaves its neighbors where they are. It turns about its +/// pen position moved by the shift (`xf * pivot`), and `xf * unturned` still places the shifted +/// glyph without its rotation. +#[test] +fn baseline_shift_moves_a_rotated_character_across_its_line() { + let slanted = vectorcraft_geom::PathData::from_bezpath(&kurbo::Line::new((0.0, 0.0), (300.0, -300.0)).to_path(1e-3)); + for on_path in [false, true] { + for rotation in [0.0, 45.0, 85.0, 90.0, 95.0, -90.0] { + let at = |shift: f64| { + let mut t = avav(1, |s| { + s.rotation = rotation; + s.baseline_shift = shift; + }); + if on_path { + t.kind = TextKind::OnPath { path: slanted.clone(), start: 0.0, end: None }; + } + layout(db(), &t) + }; + let (plain, shifted) = (at(0.0), at(10.0)); + let pen = |l: &TextLayout, byte: usize| l.glyphs.iter().find(|g| g.byte == byte).map(|g| g.xf * Point::ZERO).unwrap(); + let v = plain.glyphs.iter().find(|g| g.byte == 1).unwrap(); + let up = kurbo::Vec2::new(v.angle.sin(), -v.angle.cos()); + let moved = pen(&shifted, 1) - pen(&plain, 1); + assert!((moved - up * 10.0).hypot() < 1e-6, "on a path {on_path}, {rotation}°: {moved:?}, up {up:?}"); + for byte in [0, 2, 3] { + assert!((pen(&shifted, byte) - pen(&plain, byte)).hypot() < 1e-6, "on a path {on_path}, {rotation}°: byte {byte} moved"); + } + let g = shifted.glyphs.iter().find(|g| g.byte == 1).unwrap(); + let turn_at = g.xf * g.pivot; + assert!((turn_at - (v.origin + up * 10.0)).hypot() < 1e-6, "on a path {on_path}, {rotation}°: turns about {turn_at:?}"); + let unrotated = layout(db(), &{ + let mut t = avav(1, |s| s.baseline_shift = 10.0); + if on_path { + t.kind = TextKind::OnPath { path: slanted.clone(), start: 0.0, end: None }; + } + t + }); + let u = unrotated.glyphs.iter().find(|g| g.byte == 1).unwrap(); + let (a, b) = ((g.xf * g.unturned).as_coeffs(), u.xf.as_coeffs()); + assert!(a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-6), "on a path {on_path}, {rotation}°: {a:?} vs {b:?}"); + } + } +} + #[test] fn tracking_or_kerning_on_one_character_keeps_the_kerning_before_it() { let plain = pens(&TextObject::point(Point::ZERO, "AVAV", style(40.0))); diff --git a/crates/tools/src/touchtype.rs b/crates/tools/src/touchtype.rs index 356142035b..7f8e06ea2d 100644 --- a/crates/tools/src/touchtype.rs +++ b/crates/tools/src/touchtype.rs @@ -53,12 +53,14 @@ struct CharBox { quad: [Point; 4], /// The glyph's origin on its shifted baseline, which the scale handles measure from. pen: Point, - /// Its pen position on the line's baseline, which character rotation turns it about. + /// The point character rotation turns it about: its pen position on the line's baseline, + /// moved by its baseline shift. pivot: Point, /// A unit vector along its line in reading order. along: Vec2, - /// The glyph's own x axis and its up axis (with its rotation, which baseline shift moves it - /// along), unit vectors. + /// A unit vector up from its line, without its rotation: the way baseline shift moves it. + up: Vec2, + /// The glyph's own x axis and its up axis (with its rotation), unit vectors. ex: Vec2, ey: Vec2, /// Whether the tool moves it along its line by kerning: a character comes before it on its @@ -177,8 +179,9 @@ fn char_box(t: &TextObject, lay: &TextLayout, gi: usize) -> Option<CharBox> { start: g.byte, quad, pen, - pivot: g.origin, + pivot: m * g.pivot, along: if g.rtl { -d } else { d }, + up: unit(linear(m * g.unturned, Vec2::new(0.0, -1.0))), ex, ey, kerned: !g.rtl && lay.glyphs.iter().any(|h| h.line == g.line && h.len > 0 && h.byte + h.len == g.byte), @@ -239,20 +242,21 @@ impl TouchTypeTool { } /// Document-space move for a character box (`b` of `t`): kerning along the line and baseline - /// shift along the character's up axis. + /// shift up from it, whatever the character's rotation. The move (text space) is split into + /// its parts along the line and up from it; a character that is not kerned only moves up or + /// down. When the two axes are parallel, the params hold no move. fn move_params(id: NodeId, t: &TextObject, b: &CharBox, moved: Vec2) -> Value { let doc_len = |v: Vec2| linear(t.xf, v).hypot(); - let det = b.along.cross(b.ey); - let (along, rise) = if !b.kerned { - (0.0, moved.dot(b.ey)) - } else if det.abs() > 0.1 { - (moved.cross(b.ey) / det, b.along.cross(moved) / det) + let det = b.along.cross(b.up); + let (along, rise) = if det.abs() <= 1e-9 || !det.is_finite() { + (0.0, 0.0) } else { - (moved.dot(b.along), 0.0) + let (along, rise) = (moved.cross(b.up) / det, b.along.cross(moved) / det); + if b.kerned { (along, rise) } else { (0.0, rise) } }; let mut out = json!({"id": id.0, "start": b.start}); let dx = along * doc_len(b.along); - let dy = rise * doc_len(b.ey); + let dy = rise * doc_len(b.up); if dx != 0.0 { out["dx"] = json!(dx); } diff --git a/crates/tools/src/touchtype/tests.rs b/crates/tools/src/touchtype/tests.rs index 252ede4ff2..5556efda02 100644 --- a/crates/tools/src/touchtype/tests.rs +++ b/crates/tools/src/touchtype/tests.rs @@ -140,6 +140,89 @@ fn dragging_the_box_moves_the_character_along_its_line_and_up() { assert!(close(p3.get("dx").and_then(|v| v.as_f64()).unwrap_or(0.0), 0.0) && close(p3["dy"].as_f64().unwrap(), 4.0), "{p3}"); } +/// 40 pt point type "Type" at (100, 200) whose "y" is rotated by `rotation` degrees, selected. +fn doc_with_rotated_y(rotation: f64) -> (Document, NodeId, Selection) { + let (mut d, id, s) = doc_with_type(); + if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) { + edit::style_range(&mut t.runs, 1, 2, |st| st.rotation = rotation); + } + (d, id, s) +} + +/// Near and at a quarter turn, a drag still splits into kerning along the line and baseline shift +/// across it: right 10 pt and up 4 pt is `dx` 10 and `dy` 4 at every rotation, and a drag straight +/// across the line is all `dy`. Arrow keys nudge the same way. +#[test] +fn a_character_rotated_near_a_quarter_turn_moves_across_its_line() { + for rotation in [45.0, 85.0, 90.0, 95.0, -90.0] { + let (d, id, s) = doc_with_rotated_y(rotation); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = TouchTypeTool { target: Some((id, 1)), ..Default::default() }; + let q = quad(&t, &cx); + let at = q[0].midpoint(q[2]); + let acts = drag(&mut t, &cx, at, at + Vec2::new(10.0, -4.0)); + let p1 = preview(&acts[1]); + assert!(close(p1["dx"].as_f64().unwrap(), 10.0) && close(p1["dy"].as_f64().unwrap(), 4.0), "{rotation}°: {p1}"); + let acts = drag(&mut t, &cx, at, at + Vec2::new(0.0, -6.0)); + let p2 = preview(&acts[1]); + assert!(p2.get("dx").is_none_or(|v| close(v.as_f64().unwrap(), 0.0)) && close(p2["dy"].as_f64().unwrap(), 6.0), "{rotation}°: {p2}"); + let acts = t.key(&cx, ToolKey::Up, Mods::default()); + let p3 = match &acts[0] { + Action::Exec(c, v) if c == "text.touchType" => v, + other => panic!("{other:?}"), + }; + assert!(close(p3["dy"].as_f64().unwrap(), 1.0) && p3.get("dx").is_none_or(|v| close(v.as_f64().unwrap(), 0.0)), "{rotation}°: {p3}"); + } +} + +/// In type scaled unevenly, a drag's parts are measured in document points: right 10 pt and up 4 +/// pt of a quarter-turned character is `dx` 10 and `dy` 4. +#[test] +fn a_quarter_turned_character_in_unevenly_scaled_type_follows_the_pointer() { + let (mut d, id, s) = doc_with_rotated_y(90.0); + if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) { + t.xf = Affine::scale_non_uniform(2.0, 0.5) * t.xf; + } + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = TouchTypeTool { target: Some((id, 1)), ..Default::default() }; + let q = quad(&t, &cx); + let at = q[0].midpoint(q[2]); + let acts = drag(&mut t, &cx, at, at + Vec2::new(10.0, -4.0)); + let p1 = preview(&acts[1]); + assert!(close(p1["dx"].as_f64().unwrap(), 10.0) && close(p1["dy"].as_f64().unwrap(), 4.0), "{p1}"); +} + +/// A character with a baseline shift turns about its pen position moved up by the shift, rotated +/// or not, and the rotate handle measures its turn about that point. +#[test] +fn a_shifted_character_turns_about_its_shifted_pen_position() { + for rotation in [0.0, 30.0, 90.0] { + let (mut d, id, s) = doc_with_rotated_y(rotation); + if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) { + edit::style_range(&mut t.runs, 1, 2, |st| st.baseline_shift = 10.0); + } + let p = paint(); + let cx = cx(&d, &s, &p); + let t = TouchTypeTool { target: Some((id, 1)), ..Default::default() }; + let (_, text, b) = t.current(&cx).expect("a character is selected"); + let lay = vectorcraft_text::layout(FontDb::global(), text); + let y = lay.glyphs.iter().find(|g| g.byte == 1).unwrap(); + let want = y.origin + Vec2::new(0.0, -10.0); + assert!((b.pivot - want).hypot() < 1e-6, "{rotation}°: {:?}, want {want:?}", b.pivot); + // The rotate handle turned a quarter turn about that point is a quarter turn more. + let mut t = t; + let top = text.xf * b.handle(Part::Rotate); + let centre = text.xf * want; + let r = top - centre; + let acts = drag(&mut t, &cx, top, centre + Vec2::new(r.y, -r.x)); + let ps = preview(&acts[1]); + let turned = (ps["rotation"].as_f64().unwrap() - rotation - 90.0).rem_euclid(360.0); + assert!(turned.min(360.0 - turned) < 1e-6, "{rotation}°: {ps}"); + } +} + #[test] fn arrow_keys_nudge_the_selected_character() { let (d, id, s) = doc_with_type(); diff --git a/docs/mcp.md b/docs/mcp.md index 8f0b9b7fff..322778d7ff 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5168,9 +5168,10 @@ offset of the character; a ligature (one glyph for several characters) changes a `end` give its bytes. `dx` (document points, in reading order) changes the kerning of the character before it on its line and its own kerning, so the character moves by `dx` and the characters after it stay where they are. The first character of a line and a right-to-left character take no `dx`, and `dx` is limited to what kerning from -1000 to 10000 (1/1000 em) on the two -characters can give. `dy` raises it by baseline shift, which moves a rotated character along its own up axis. The tool -splits a drag of a character rotated by up to about 84 degrees between kerning and baseline shift, so the character -follows the pointer; nearer a quarter turn, a drag moves it only along its line. `hScale`, `vScale` +characters can give. `dy` raises it by baseline shift, which moves the character up from its line at any rotation, a quarter +turn included; a character rotated with a baseline shift turns about its shifted pen position. The tool splits a drag +into its part along the line (kerning) and its part up from the line (baseline shift), so the character follows the +pointer at any rotation; the first character of a line and a right-to-left character follow it only up and down. `hScale`, `vScale` and `rotation` set its scales and rotation as `text.setRangeStyle` does. Where the font kerned the character with its neighbors, the kerning of the two characters keeps it and the characters after it where they were along the line; a wider or narrower character moves the characters after it by the change in its width. Touch Type gives the character diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3c5f07c836..f29d2c013b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -739,6 +739,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur While a Type tool edits type, a click that lands on no type ends the editing without making new type, and that tool stays active; the next click makes new type (#2871, #2854). Duplicate Artboards, the Artboard tool's Alt-drag and Paste give the new artboard an id that no other artboard has, also when an artboard's id is the largest possible value (#1718). Deleting the copy or the original then leaves the other's guides. - **Touch Type:** a click with the Touch Type tool (Shift+T) selects one character and shows a box around it. Dragging the box or its lower-left handle moves the character. The upper-left handle scales it vertically, the lower-right handle scales it horizontally, the upper-right handle scales it proportionally, and the upper-middle handle rotates it. Each drag is one undo step that sets the character's kerning, baseline shift, scales or rotation, and the type stays editable (`text.touchType`; behavior reference: [Touch Type tool](https://web.archive.org/web/20261007185617/https://helpx.adobe.com/illustrator/using/tool-techniques/touch-type-tool.html), [Add text with the Type, Area Type, and Touch Type tools](https://web.archive.org/web/20260926095922/https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/add-text-illustrator-text-tools.html)). + A character rotated near or at a quarter turn follows a Touch Type drag across its line as well as along it: baseline shift moves a character up from its line at any rotation, and the character turns about its shifted pen position. - **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool. Space held while the Zoom tool drags a marquee moves the marquee and keeps its size ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). When Space is let go, the drag sizes the marquee again from where it moved to. A Space+Shift drag rotates the view whatever the tool, as a Rotate View tool drag does, and Shift does not round the angle to 15°. From ff036557fb13db915e7e71f64180a8762f0f092d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 1 Nov 2026 11:09:03 +0700 Subject: [PATCH 254/260] Symbols: Edit Symbol opens the symbol in its own editing mode, and every instance follows each edit Squashed from #5064 onto main. --- crates/doc/src/document.rs | 3 + crates/doc/src/document_ext.rs | 14 +- crates/doc/src/lib.rs | 6 +- crates/doc/src/records.rs | 25 +- crates/engine/src/cmd.rs | 13 +- crates/engine/src/cmd/brushsym.rs | 21 +- crates/engine/src/cmd/brushsym/symbols.rs | 68 ++- crates/engine/src/cmd/edit.rs | 4 + crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/object/arrange.rs | 18 +- crates/engine/src/cmd/patterncmds.rs | 15 +- crates/engine/src/cmd/shaper.rs | 5 +- crates/engine/src/cmd/symboledit.rs | 445 +++++++++++++++++++ crates/engine/src/command_sets.rs | 17 +- crates/engine/src/doc_state.rs | 3 + crates/engine/src/session/edit.rs | 23 +- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/brushsym.rs | 5 +- crates/engine/src/tests/dynamic_symbols.rs | 10 +- crates/engine/src/tests/symboledit.rs | 491 +++++++++++++++++++++ crates/tools/src/select.rs | 5 + crates/tools/src/select/tests.rs | 34 ++ crates/ui-egui/src/app/commands.rs | 28 +- crates/ui-egui/src/chrome/control_bar.rs | 15 +- crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/bs.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/panels/symbols.rs | 62 ++- docs/mcp.md | 11 +- docs/target-app-parity.md | 1 + 53 files changed, 1353 insertions(+), 71 deletions(-) create mode 100644 crates/engine/src/cmd/symboledit.rs create mode 100644 crates/engine/src/tests/symboledit.rs diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 478e54ca81..976d48485f 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -47,6 +47,7 @@ impl Document { patterns, pattern_edit, mask_edit, + symbol_edit, next_id: _, unknown, page_isolate, @@ -113,6 +114,7 @@ impl Document { (a, b) => a.is_none() && b.is_none(), } && *mask_edit == other.mask_edit + && *symbol_edit == other.symbol_edit && *unknown == other.unknown && *page_isolate == other.page_isolate && *page_knockout == other.page_knockout @@ -221,6 +223,7 @@ impl Document { patterns: vec![], pattern_edit: None, mask_edit: None, + symbol_edit: None, next_id: 1, unknown: Default::default(), page_isolate: false, diff --git a/crates/doc/src/document_ext.rs b/crates/doc/src/document_ext.rs index c0c85b124e..b52e850c76 100644 --- a/crates/doc/src/document_ext.rs +++ b/crates/doc/src/document_ext.rs @@ -98,18 +98,22 @@ impl Document { self.views = kept; } - /// Leave opacity-mask editing: drop the temporary editing layer, a working copy of art the - /// mask already holds (the engine syncs it after every edit). + /// Leave opacity-mask editing and symbol editing: drop the temporary editing layer, a working + /// copy of art the mask or the symbol already holds (the engine syncs it after every edit). pub fn drop_edit_modes(&mut self) { if let Some(me) = self.mask_edit.take() { self.layers.retain(|l| l.id != me.layer); } + if let Some(se) = self.symbol_edit.take() { + self.layers.retain(|l| l.id != se.layer); + } } - /// The document as saved and exported: without the opacity-mask editing layer. Borrowed when - /// no mask is being edited. (Pattern editing is saved: its tile layer holds unapplied edits.) + /// The document as saved and exported: without the opacity-mask or symbol editing layer. + /// Borrowed when neither mode is on. (Pattern editing is saved: its tile layer holds unapplied + /// edits.) pub fn without_edit_modes(&self) -> std::borrow::Cow<'_, Document> { - if self.mask_edit.is_none() { + if self.mask_edit.is_none() && self.symbol_edit.is_none() { return std::borrow::Cow::Borrowed(self); } let mut d = self.clone(); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 8d3b2a8833..b742a1dd75 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -142,7 +142,7 @@ pub use guides::{GridPrefs, Guide, RulerMode}; #[cfg(test)] use limits::MAX_NEXT_ID; pub use limits::{DocError, FORMAT_VERSION, MAX_COORD}; -pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, Symbol}; +pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, Symbol, SymbolEdit}; pub use units::{ColorMode, Unit, parse_number}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -222,6 +222,10 @@ pub struct Document { /// still read so files saved mid-edit by older versions load without the editing layer. #[serde(default, skip_serializing)] pub mask_edit: Option<MaskEdit>, + /// Symbol editing mode, while active. Never saved (see [`Document::without_edit_modes`]): the + /// symbol already holds the art of its editing layer. + #[serde(default, skip_serializing)] + pub symbol_edit: Option<SymbolEdit>, next_id: u64, /// Foreign data preserved on round-trip. #[serde(default, skip_serializing_if = "skip::is_empty_map")] diff --git a/crates/doc/src/records.rs b/crates/doc/src/records.rs index 434a85a8fa..a6988f5020 100644 --- a/crates/doc/src/records.rs +++ b/crates/doc/src/records.rs @@ -1,4 +1,4 @@ -use super::{Arc, Deserialize, Node, NodeId, Point, Serialize}; +use super::{Affine, Arc, Deserialize, Node, NodeId, Point, Serialize}; /// New art on a locked artboard ([`Document::new_art`]). Setting it changes the document in /// place, so a selection change that sets it doesn't replace the document. @@ -44,6 +44,29 @@ pub struct MaskEdit { pub layer: NodeId, } +/// Symbol editing mode: the art of symbol `symbol` lives on the temporary `layer` while editing, +/// placed by `xf` (from the symbol's coordinates to the document's), and goes back into the symbol +/// after each edit, so every instance follows it. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct SymbolEdit { + pub symbol: String, + pub layer: NodeId, + /// The instance editing was entered from (a double-click on it), selected again on leaving after an edit; + /// `None` when it was entered from the Symbols panel. + pub instance: Option<NodeId>, + pub xf: Affine, + /// The symbol's art is a group whose members are on the layer: the group takes them back. + pub group: bool, + /// An edit changed the art since editing was entered. + pub changed: bool, + /// The isolated object from before editing was entered, isolated again on leaving. + #[serde(default)] + pub back_isolation: Option<NodeId>, + /// The current layer from before editing was entered, current again on leaving. + #[serde(default)] + pub back_layer: Option<NodeId>, +} + /// A saved view (View → New View…): zoom, centre and rotation, listed at the bottom of the View menu. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SavedView { diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 8758262628..31d0ca2cb2 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -84,6 +84,7 @@ mod style; pub mod stylelib; mod swatch; pub mod swatchlib; +pub(crate) mod symboledit; pub mod symbollib; pub(crate) mod tabs; mod textedit; @@ -183,11 +184,15 @@ pub fn has_multi(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; if st.selection.len() < 2 { Err("select at least two objects".into()) } else { Ok(()) } } -/// The isolated group, layer or object in isolation mode. Pattern editing mode and opacity mask -/// editing isolate their own layer, which does not count here; an object isolated inside them -/// counts. +/// The isolated group, layer or object in isolation mode. Pattern editing mode, opacity mask +/// editing and symbol editing mode isolate their own layer, which does not count here; an object +/// isolated inside them counts. pub(crate) fn ordinary_isolation(st: &crate::DocState) -> Option<vectorcraft_doc::NodeId> { - st.isolation.filter(|l| !st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l) && !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l)) + st.isolation.filter(|l| { + !st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l) + && !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l) + && !st.doc.symbol_edit.as_ref().is_some_and(|e| e.layer == *l) + }) } /// Objects are selected ([`has_selection`]), and in isolation mode ([`ordinary_isolation`]) at /// least one of them is inside the isolated object: Object › Lock's and Object › Hide's items. diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 7f78aa2465..a1f03b6a35 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -35,10 +35,10 @@ use brushes::{ }; use dynamic::{symbol_instance_reset, symbol_instance_set_appearance}; use symbols::selected_instances; -pub(crate) use symbols::{instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol}; +pub(crate) use symbols::{fit_instances_of, instance_in_place, instances_of, natural_size, normalize, place_xf, set_natural_size, store_symbol}; use symbols::{ - symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_edit, symbol_list, symbol_new, symbol_options, symbol_place, - symbol_replace, symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update, + symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_list, symbol_new, symbol_options, symbol_place, symbol_replace, + symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update, }; const SIZES_KEY: &str = vectorcraft_doc::SYMBOL_SIZES; @@ -210,9 +210,18 @@ pub fn specs() -> Vec<CommandSpec> { "Edit Symbol", [], None, - "{id?, ids?: [id…] (instead of id)} break the link of the selected instance so the symbol's art can be edited (without the instance's own appearance changes to a dynamic symbol); finish with symbol.update → {name, ids}", - has_selection, - symbol_edit + "{id?, ids?: [id…] (instead of id), name?, x?, y?, artboard?: index=0 (the active artboard; the app passes it), viewCenter?: [x, y] (the app passes the view's center)} edit a symbol's art in symbol editing mode: the instance `id` (default: the selected instances, which must share one symbol) where it shows the art, else the symbol `name` (default: the current symbol) centered on (x, y) (default: the center of artboard `artboard`, or of the first artboard when there is no such artboard; in a document without artboards, viewCenter, else (0, 0)); every instance follows each edit and the instance stays linked (symbol.breakLink expands one); refused while a pattern or an opacity mask is edited → {name, layer, id?}", + has_doc, + super::symboledit::enter + ), + cmd!( + "symbol.exitEditing", + "Exit Symbol Editing Mode", + [], + None, + "{} leave symbol editing mode; after an edit, select the instance it was entered from; leaving without having changed the art adds no undo step and restores the selection from before entry (object.exitIsolation also leaves it) → {name?}", + has_doc, + super::symboledit::leave ), cmd!( "symbol.update", diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 556926309e..0b69b7f8ac 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -95,7 +95,14 @@ pub(crate) fn normalize(mut art: Node) -> Result<(Node, (f64, f64), Point)> { Ok((art, (w, h), c)) } -fn instances_of(d: &Document, name: Option<&str>) -> Vec<NodeId> { +/// After the art of symbol `name` changed: each of its instances keeps its appearance changes to +/// the objects the art still has. +pub(crate) fn fit_instances_of(d: &mut Document, name: &str) { + let ids = instances_of(d, Some(name)); + fit_overrides(d, &ids); +} + +pub(crate) fn instances_of(d: &Document, name: Option<&str>) -> Vec<NodeId> { let mut v = vec![]; d.walk(|n| { if let NodeKind::SymbolInstance { symbol, .. } = &n.kind @@ -274,6 +281,14 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> { if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { d.unknown.insert(CURRENT_SYMBOL.into(), json!(n)); } + // Symbol editing mode follows the new name, and so does its layer. + if let Some(e) = d.symbol_edit.as_mut().filter(|e| e.symbol == name) { + e.symbol = n.clone(); + let layer = e.layer; + if let Some(l) = d.node_mut(layer) { + l.name = Some(n.clone()); + } + } } if let Some(r) = reg { d.set_symbol_registration(&final_name, r); @@ -398,34 +413,35 @@ pub(super) fn symbol_break_link(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "ids": ids_json(&out) })) } -pub(super) fn symbol_edit(s: &mut Session, p: &Value) -> Result<Value> { - let ids = selected_instances(s, p)?; - let first = *ids.first().ok_or_else(|| EngineError::Other("select a symbol instance".into()))?; - let name = match &s.doc()?.doc.node(first).map(|n| n.kind.clone()) { - Some(NodeKind::SymbolInstance { symbol, .. }) => symbol.clone(), - _ => return Err(EngineError::Other("select a symbol instance".into())), - }; - // The symbol's own art: one instance's appearance changes would become every instance's. - let out = s.edit("Edit Symbol", |d, sel| { - let out = break_links(d, &[first], false)?; - sel.set(out.iter().copied()); - Ok(out) - })?; - Ok(json!({ "name": name, "ids": ids_json(&out) })) -} - pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "symbol.update"; let name = name_param(p, C)?.to_string(); if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) { return Err(bad(C, format!("no symbol named `{name}`"))); } + // Redefining the symbol being edited leaves symbol editing mode in the same step. + let session = s.doc()?.doc.symbol_edit.clone().filter(|e| e.symbol == name); + if session.is_some() { + crate::cmd::settle_interaction(s)?; + s.end_text_edit(); + } let ids = roots(s, p)?; + // The art on the editing layer can't redefine it: the symbol would hold an instance of itself. + if let Some(se) = &session { + let d = &s.doc()?.doc; + if ids.iter().any(|i| d.ancestry(*i).is_some_and(|a| a.contains(&se.layer))) { + return Err(EngineError::Other("a symbol can't hold an instance of itself".into())); + } + } let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?; crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art); let (art, size, c) = normalize(art)?; let old = natural_size(&s.doc()?.doc, &name); + let editing = session.is_some(); let id = s.edit("Redefine Symbol", |d, sel| { + if editing { + crate::cmd::symboledit::finish(d, sel); + } let art = d.reid(&art); if let Some(sym) = d.symbols.iter_mut().find(|x| x.name == name) { sym.art = Arc::new(art); @@ -445,6 +461,9 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> { sel.set([id]); Ok(id) })?; + if let Some(se) = &session { + crate::cmd::symboledit::leave_editing(s, se)?; + } Ok(json!({ "name": name, "id": id.0 })) } @@ -476,8 +495,18 @@ pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result<Value> { return Err(bad(C, format!("no symbol named `{name}`"))); } let expand = switch_or(p, "expandInstances", true, C)?; + // Deleting the symbol being edited leaves symbol editing mode in the same step. + let session = s.doc()?.doc.symbol_edit.clone().filter(|e| names.contains(&e.symbol)); + let editing = session.is_some(); + if editing { + crate::cmd::settle_interaction(s)?; + s.end_text_edit(); + } let label = if names.len() == 1 { "Delete Symbol" } else { "Delete Symbols" }; - s.edit(label, |d, _| { + s.edit(label, |d, sel| { + if editing { + crate::cmd::symboledit::finish(d, sel); + } // Every instance goes before any definition, whatever the order of `names`: expanding an // instance of one symbol can bring out instances of another being deleted (nested in its // art), which expand in turn while their definitions are still there. Each round expands @@ -519,6 +548,9 @@ pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result<Value> { } Ok(()) })?; + if let Some(se) = &session { + crate::cmd::symboledit::leave_editing(s, se)?; + } ok() } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 3534d40ac5..a00f90952a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -481,6 +481,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> { let label = e.label.clone(); let costs = e.costs(); let editing = st.doc.mask_edit.map(|m| m.layer); + let editing_symbol = st.doc.symbol_edit.clone(); let doc = std::mem::replace(&mut st.doc, e.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); let selection = shared_selection(selection, st.history.redo.last()); @@ -494,6 +495,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> { crate::deselect_hidden(&menu, &st.doc, &mut st.selection); st.sync_new_art(); super::maskedit::follow_history(st, editing); + super::symboledit::follow_history(st, editing_symbol.as_ref()); leave_isolation_if_gone(st); super::globaledit::follow_history(st); Ok(json!({ "undone": label })) @@ -507,6 +509,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> { let label = e.label.clone(); let costs = e.costs(); let editing = st.doc.mask_edit.map(|m| m.layer); + let editing_symbol = st.doc.symbol_edit.clone(); let doc = std::mem::replace(&mut st.doc, e.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); let selection = shared_selection(selection, st.history.undo.last()); @@ -519,6 +522,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> { crate::deselect_hidden(&menu, &st.doc, &mut st.selection); st.sync_new_art(); super::maskedit::follow_history(st, editing); + super::symboledit::follow_history(st, editing_symbol.as_ref()); leave_isolation_if_gone(st); super::globaledit::follow_history(st); Ok(json!({ "redone": label })) diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 4588b58aaa..5c2374988e 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -90,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> { "Batch", [], None, - "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing or select.allOnArtboard step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", + "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", has_doc, batch::batch ), diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index 9cafae899a..69d2baa9c2 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -334,13 +334,27 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> { } pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> { - // Opacity mask editing and pattern editing isolate their editing layer. Leaving isolation mode - // then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's Done do. + // Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving + // isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's + // Done do. A group isolated inside the symbol's art goes back to the symbol's layer. let st = s.doc()?; + if let Some(layer) = st.doc.symbol_edit.as_ref().map(|e| e.layer) + && let Some(inner) = st.isolation.filter(|i| *i != layer) + { + crate::cmd::settle_interaction(s)?; + let st = s.doc_mut()?; + crate::cmd::distortcmds::finish_edit_text(st, inner); + st.isolation = Some(layer); + st.selection.set([inner]); + st.revision += 1; + return ok(); + } let leave_mode: Option<fn(&mut Session, &Value) -> Result<Value>> = if st.doc.mask_edit.is_some() { Some(crate::cmd::maskedit::leave) } else if st.doc.pattern_edit.is_some() { Some(crate::cmd::patterncmds::pattern_done) + } else if st.doc.symbol_edit.is_some() { + Some(crate::cmd::symboledit::leave) } else { None }; diff --git a/crates/engine/src/cmd/patterncmds.rs b/crates/engine/src/cmd/patterncmds.rs index aea1aeb58a..8f1e993203 100644 --- a/crates/engine/src/cmd/patterncmds.rs +++ b/crates/engine/src/cmd/patterncmds.rs @@ -161,12 +161,18 @@ fn in_pattern_edit(s: &Session) -> std::result::Result<(), String> { editing(s).map(|_| ()).ok_or_else(|| "not in pattern editing mode".into()) } -/// Make: a selection, and no opacity mask is being edited -/// ([`super::maskedit::outside_mask_editing`]), since the tile layer would replace the mask editing -/// layer as the isolated layer. +/// Make: a selection, and no opacity mask or symbol is being edited +/// ([`super::maskedit::outside_mask_editing`], [`outside_symbol_editing`]), since the tile layer +/// would replace that mode's editing layer as the isolated layer. fn can_make_pattern(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; - super::maskedit::outside_mask_editing(s) + super::maskedit::outside_mask_editing(s)?; + outside_symbol_editing(s) +} + +/// No symbol is being edited (symbol editing mode shows the symbol in isolation mode). +fn outside_symbol_editing(s: &Session) -> std::result::Result<(), String> { + if s.active().is_some_and(|st| st.doc.symbol_edit.is_some()) { Err("exit isolation mode first".into()) } else { Ok(()) } } fn can_edit_pattern(s: &Session) -> std::result::Result<(), String> { @@ -175,6 +181,7 @@ fn can_edit_pattern(s: &Session) -> std::result::Result<(), String> { return Err("already editing a pattern".into()); } super::maskedit::outside_mask_editing(s)?; + outside_symbol_editing(s)?; if s.active().is_some_and(|st| st.doc.patterns.is_empty()) { Err("the document has no patterns".into()) } else { Ok(()) } } diff --git a/crates/engine/src/cmd/shaper.rs b/crates/engine/src/cmd/shaper.rs index 9a952082a0..511e8ce4fb 100644 --- a/crates/engine/src/cmd/shaper.rs +++ b/crates/engine/src/cmd/shaper.rs @@ -773,9 +773,10 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> { } Ok(json!({"id": target.0})) } -/// The layer an opacity mask or a pattern is edited in, which stays isolated while that mode is on. +/// The layer an opacity mask, a pattern or a symbol is edited in, which stays isolated while that +/// mode is on. fn editing_layer(d: &Document) -> Option<NodeId> { - d.mask_edit.map(|m| m.layer).or_else(|| d.pattern_edit.as_ref().map(|e| e.layer)) + d.mask_edit.map(|m| m.layer).or_else(|| d.pattern_edit.as_ref().map(|e| e.layer)).or_else(|| d.symbol_edit.as_ref().map(|e| e.layer)) } /// Leave isolation mode, Construction mode included. While an opacity mask or a pattern is edited, /// its editing layer stays isolated. diff --git a/crates/engine/src/cmd/symboledit.rs b/crates/engine/src/cmd/symboledit.rs new file mode 100644 index 0000000000..a89fbe8d61 --- /dev/null +++ b/crates/engine/src/cmd/symboledit.rs @@ -0,0 +1,445 @@ +//! Symbol editing mode (Edit Symbol, a double-click on an instance or on a symbol in the Symbols +//! panel). +//! +//! The symbol's art moves onto a temporary isolated layer, placed where the instance it was +//! entered from shows it (from the panel: at the center of the active artboard, or of the view in a +//! document without artboards), where every tool and command can edit it while the rest of the +//! document is dimmed. After each edit [`sync`] writes the layer's art back into the symbol, so +//! every instance updates live. Leaving the mode +//! (`symbol.exitEditing`, Escape, the isolation bar's back button, a double-click outside the art) +//! removes the layer, and saving or exporting never writes it ([`Document::without_edit_modes`]). +//! Symbol editing is not entered while a pattern or an opacity mask is edited, and neither of those +//! is entered while a symbol is edited. + +use std::collections::HashSet; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection, SymbolEdit, SymbolRegistration}; +use vectorcraft_geom::{Affine, Point}; + +use super::brushsym::{natural_size, place_xf}; +use super::{EngineError, Result, Session, bad, id_param, number_or, ok, str_param}; + +/// The name of the undo step that enters symbol editing mode. +const ENTER: &str = "Edit Symbol"; + +/// The symbol instances among the selected objects, members of selected groups included. +fn selected_instances(st: &crate::DocState) -> Vec<NodeId> { + let mut out = vec![]; + for id in &st.selection.objects { + if let Some(n) = st.doc.node(*id) { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !out.contains(&c.id) { + out.push(c.id); + } + }); + } + } + out +} + +/// The symbol and transform of instance `id`. +fn instance_of(d: &Document, id: NodeId) -> Option<(String, Affine)> { + match &d.node(id)?.kind { + NodeKind::SymbolInstance { symbol, xf } => Some((symbol.clone(), *xf)), + _ => None, + } +} + +/// Where editing places the art: the instance's own transform, or for one that flattens the art, +/// a placement at the symbol's natural size around the same point. +fn editing_xf(d: &Document, name: &str, xf: Affine) -> Affine { + let det = xf.determinant(); + if det.is_finite() && det.abs() > 1e-12 { xf } else { place_xf(xf * Point::ZERO, natural_size(d, name), SymbolRegistration::CENTER) } +} + +/// Enter symbol editing mode (`symbol.edit`). +pub(crate) fn enter(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "symbol.edit"; + let st = s.doc()?; + if st.doc.mask_edit.is_some() { + return Err(bad(C, "stop editing the opacity mask first")); + } + if st.doc.pattern_edit.is_some() { + return Err(bad(C, "finish editing the pattern first")); + } + let given = id_param(p, "id").map(|i| vec![i]).or_else(|| super::ids_param(p, "ids").filter(|v| !v.is_empty())); + let (name, xf, instance) = match given { + Some(ids) => { + let symbols = ids.iter().map(|id| instance_of(&st.doc, *id)).collect::<Option<Vec<_>>>(); + let symbols = symbols.ok_or_else(|| bad(C, "select a symbol instance"))?; + let (name, xf) = symbols.first().cloned().ok_or_else(|| bad(C, "select a symbol instance"))?; + if symbols.iter().any(|(n, _)| *n != name) { + return Err(bad(C, "select instances of one symbol")); + } + let xf = editing_xf(&st.doc, &name, xf); + (name, xf, ids.first().copied()) + } + None => { + let picked = if str_param(p, "name").is_some() { vec![] } else { selected_instances(st) }; + let symbols: Vec<(String, Affine)> = picked.iter().filter_map(|id| instance_of(&st.doc, *id)).collect(); + match symbols.first() { + Some((first, xf)) => { + if symbols.iter().any(|(n, _)| n != first) { + return Err(bad(C, "select instances of one symbol")); + } + (first.clone(), editing_xf(&st.doc, first, *xf), picked.first().copied()) + } + None => { + let d = &st.doc; + let name = match str_param(p, "name") { + Some(n) if d.symbols.iter().any(|x| x.name == n) => n.to_string(), + Some(n) => return Err(bad(C, format!("no symbol named `{n}`"))), + None => d + .unknown + .get(super::brushsym::CURRENT_SYMBOL) + .and_then(Value::as_str) + .filter(|n| d.symbols.iter().any(|x| x.name == *n)) + .or_else(|| d.symbols.first().map(|x| x.name.as_str())) + .map(str::to_string) + .ok_or_else(|| EngineError::Other("the document has no symbols".into()))?, + }; + let artboard = p.get("artboard").and_then(Value::as_u64).map_or(0, super::index); + let center = match d.artboards.get(artboard).or(d.artboards.first()) { + Some(a) => a.rect.center(), + None => super::point_param(p, "viewCenter").unwrap_or(Point::ZERO), + }; + let at = Point::new(number_or(p, "x", center.x, C)?, number_or(p, "y", center.y, C)?); + (name.clone(), place_xf(at, natural_size(d, &name), SymbolRegistration::CENTER), None) + } + } + } + }; + // Editing another symbol (one from the Symbols panel, or through the API): the current edit + // ends first. + if st.doc.symbol_edit.is_some() { + if instance.is_some_and(|i| st.doc.symbol_edit.as_ref().is_some_and(|e| st.doc.ancestry(i).unwrap_or_default().contains(&e.layer))) { + return Err(bad(C, "exit isolation mode first")); + } + leave(s, &json!({}))?; + } + if let Some(i) = s.doc()?.isolation { + super::settle_interaction(s)?; + super::distortcmds::finish_edit_text(s.doc_mut()?, i); + } + s.end_text_edit(); + let st = s.doc()?; + let back = Return { redo: st.history.redo.clone(), before: Some(st.doc.clone()) }; + let (isolation, active_layer) = (st.isolation, st.active_layer); + let layer = s.edit(ENTER, |d, sel| { + let layer = begin(d, sel, &name, xf, instance)?; + if let Some(e) = d.symbol_edit.as_mut() { + e.back_isolation = isolation; + e.back_layer = active_layer; + } + Ok(layer) + })?; + s.doc_mut()?.symbol_edit_return = back; + show_editing(s, layer)?; + let mut out = json!({ "name": name, "layer": layer.0 }); + if let Some(i) = instance { + out["id"] = json!(i.0); + } + Ok(out) +} + +/// A group whose members editing spreads out on the layer: nothing of its own that they would lose +/// while they are edited. +fn spreads(art: &Node) -> bool { + matches!(art.kind, NodeKind::Group { clip: false, .. }) + && art.has_default_transparency() + && art.appearance.items.is_empty() + && art.appearance.effects.is_empty() +} + +/// Enter symbol editing for `name` inside an edit: copy its art, placed by `xf`, onto a new +/// editing layer and select it. Returns the layer. +fn begin(d: &mut Document, sel: &mut Selection, name: &str, xf: Affine, instance: Option<NodeId>) -> Result<NodeId> { + let art = + d.symbols.iter().find(|x| x.name == name).map(|x| x.art.clone()).ok_or_else(|| EngineError::Other(format!("no symbol named `{name}`")))?; + let group = spreads(&art); + let parts = match art.children() { + Some(ch) if group => ch.clone(), + _ => vec![art], + }; + let layer = d.add_layer(Some(name)); + let mut ids = Vec::with_capacity(parts.len()); + for part in &parts { + let mut copy = d.reid(part); + copy.transform(xf, false); + ids.push(d.insert(Some(layer), usize::MAX, copy)?); + } + // Copied type whose layout caches `reid` dropped has them again. + super::typecmd::refresh_bounds_of(d, &ids); + d.symbol_edit = Some(SymbolEdit { symbol: name.to_string(), layer, instance, xf, group, changed: false, back_isolation: None, back_layer: None }); + sel.set(ids); + Ok(layer) +} + +/// Leave symbol editing mode (`symbol.exitEditing`); a no-op outside it. `object.exitIsolation` runs +/// it too while a symbol is edited. Isolation and the current layer go back to what they were +/// before. When nothing changed the art since editing was entered, the entering step is taken back +/// instead of a step being added, so the document and its redo steps are as they were. +pub(crate) fn leave(s: &mut Session, _: &Value) -> Result<Value> { + let Some(se) = s.doc()?.doc.symbol_edit.clone() else { return ok() }; + super::settle_interaction(s)?; + super::distortcmds::finish_edit_text(s.doc_mut()?, se.layer); + s.end_text_edit(); + let st = s.doc_mut()?; + let unchanged = !st.doc.symbol_edit.as_ref().is_some_and(|e| e.changed); + let Return { redo, before } = std::mem::take(&mut st.symbol_edit_return); + // Saved while editing: the saved file holds no editing layer, so leaving keeps it saved. + let saved_here = st.saved_doc.symbol_edit.as_ref().is_some_and(|e| e.layer == se.layer); + let clean = !st.is_dirty(); + // Not after edits that were undone (their redo steps hold the editing layer), nor after a save + // (taking the entering step back would undo what the save changed). The last step is the + // entering step only when it starts from the document entering started from: a batch step + // that entered after other edits starts from before them. + if unchanged + && !saved_here + && st.history.redo.is_empty() + && let Some(entry) = st.history.undo.last() + && before.as_ref().is_some_and(|b| Arc::ptr_eq(b, &entry.doc)) + && let Some(entry) = st.history.undo.pop() + { + let now = std::mem::replace(&mut st.doc, entry.doc); + // What changed outside the undo history while editing (the current symbol and brush, the + // perspective grid's view, export settings, the grid preferences) stays as it is now. + if st.doc.unknown != now.unknown || st.doc.export_settings != now.export_settings || st.doc.grid != now.grid { + let d = Arc::make_mut(&mut st.doc); + d.unknown = now.unknown.clone(); + d.export_settings = now.export_settings.clone(); + d.grid = now.grid.clone(); + } + st.selection = Arc::unwrap_or_clone(entry.selection); + st.selection.prune(&st.doc); + st.history.redo = redo; + st.revision += 1; + } else { + s.edit("Exit Symbol Editing Mode", |d, sel| { + finish(d, sel); + Ok(()) + })?; + if saved_here && clean { + s.doc_mut()?.mark_saved(); + } + } + leave_editing(s, &se)?; + Ok(json!({ "name": se.symbol })) +} + +/// Leave symbol editing inside an edit (no-op when not editing): drop the editing layer and select +/// the instance editing was entered from. The symbol already holds the layer's art ([`sync`]). +pub(crate) fn finish(d: &mut Document, sel: &mut Selection) { + let Some(se) = d.symbol_edit.take() else { return }; + let _ = d.remove(se.layer); + match se.instance.filter(|i| d.node(*i).is_some()) { + Some(i) => sel.set([i]), + None => sel.clear(), + } +} + +/// The redo steps entering symbol editing mode cleared, which leaving without an edit gives back, +/// and the document entering started from, which tells the entering step apart from any other. +#[derive(Clone, Debug, Default)] +pub(crate) struct Return { + redo: Vec<crate::HistoryEntry>, + before: Option<Arc<Document>>, +} + +/// Isolate the editing layer `layer` and draw into it. +fn show_editing(s: &mut Session, layer: NodeId) -> Result<()> { + let st = s.doc_mut()?; + st.isolation = Some(layer); + st.active_layer = Some(layer); + st.revision += 1; + Ok(()) +} + +/// Return to the document after leaving the editing session `se`: to the isolation and current +/// layer from before it, while they are still there. +pub(crate) fn leave_editing(s: &mut Session, se: &SymbolEdit) -> Result<()> { + let st = s.doc_mut()?; + st.symbol_edit_return = Return::default(); + go_back(st, se); + st.revision += 1; + Ok(()) +} + +/// Out of the editing session `se`: the isolation and current layer from before it, else none and +/// the default layer. +pub(crate) fn go_back(st: &mut crate::DocState, se: &SymbolEdit) { + st.isolation = se.back_isolation.filter(|i| st.doc.node(*i).is_some()); + st.active_layer = se.back_layer.filter(|l| st.doc.node(*l).is_some_and(|n| n.is_layer())).or_else(|| st.doc.default_layer()); +} + +/// After undo or redo, isolation follows the restored document into or out of symbol editing +/// (`was` is the editing session before, if any), so it never names a layer that is gone. A group +/// isolated inside the symbol's art stays isolated while it is there. +pub(crate) fn follow_history(st: &mut crate::DocState, was: Option<&SymbolEdit>) { + match st.doc.symbol_edit.as_ref().map(|e| e.layer) { + Some(layer) => { + let inside = st.isolation.is_some_and(|i| i != layer && st.doc.ancestry(i).is_some_and(|a| a.contains(&layer))); + if !inside { + st.isolation = Some(layer); + } + st.active_layer = Some(layer); + } + None => { + // Out of the mode: isolation on the editing layer or inside it, and a current layer + // that is gone, go back to what they were before it. + let Some(was) = was else { return }; + let gone = |id: Option<NodeId>| id.is_some_and(|i| i == was.layer || st.doc.node(i).is_none()); + if gone(st.isolation) || gone(st.active_layer) { + go_back(st, was); + } + } + } +} + +/// Does `n` hold an instance of symbol `name`, directly or through the art of the symbols it holds +/// instances of? +fn holds_symbol(d: &Document, n: &Node, name: &str, seen: &mut HashSet<String>) -> bool { + let mut found = false; + let mut nested = vec![]; + n.walk(&mut |c| { + if let NodeKind::SymbolInstance { symbol, .. } = &c.kind { + if symbol == name { + found = true; + } else if !seen.contains(symbol) { + nested.push(symbol.clone()); + } + } + }); + if found { + return true; + } + for symbol in nested { + if seen.insert(symbol.clone()) + && let Some(art) = d.symbols.iter().find(|x| x.name == symbol).map(|x| x.art.clone()) + && holds_symbol(d, &art, name, seen) + { + return true; + } + } + false +} + +/// The object at `path` (child indices, paint order) among `nodes` and the groups they hold. +fn at_path<'a>(nodes: &'a [Arc<Node>], path: &[u32]) -> Option<&'a Node> { + let (first, rest) = path.split_first()?; + let mut n: &Node = nodes.get(*first as usize)?; + for i in rest { + n = n.children()?.get(*i as usize)?; + } + Some(n) +} + +/// The path of object `id` among `nodes` and the groups they hold, at most `depth` levels down. +fn path_of(nodes: &[Arc<Node>], id: NodeId, depth: usize) -> Option<Vec<u32>> { + if depth == 0 { + return None; + } + for (i, n) in nodes.iter().enumerate() { + let i = u32::try_from(i).ok()?; + if n.id == id { + return Some(vec![i]); + } + if let Some(mut p) = n.children().and_then(|ch| path_of(ch, id, depth - 1)) { + p.insert(0, i); + return Some(p); + } + } + None +} + +/// Each instance's appearance changes to objects of symbol `name`'s art follow those objects +/// through an edit of the editing layer: `old` and `new` are the layer's objects before and after +/// with whether the symbol's art is a group of them (else it is the one object). A change to an +/// object the edit removed names no object afterwards. +fn follow_objects(d: &mut Document, name: &str, old: (&[Arc<Node>], bool), new: (&[Arc<Node>], bool)) { + let depth = vectorcraft_doc::symbol_overrides::MAX_PATH_DEPTH + 1; + for id in super::brushsym::instances_of(d, Some(name)) { + let Some(n) = d.node_mut(id) else { continue }; + if n.extras().symbol_overrides.is_empty() { + continue; + } + let mut e = n.extras_mut(); + e.symbol_overrides.retain_mut(|o| { + // The art's own group stays the art's root. + if old.1 && o.path.is_empty() { + return true; + } + let on_layer: Vec<u32> = if old.1 { o.path.clone() } else { std::iter::once(0).chain(o.path.iter().copied()).collect() }; + let moved = at_path(old.0, &on_layer).and_then(|obj| path_of(new.0, obj.id, depth)).and_then(|p| match new.1 { + true => Some(p), + false => p.split_first().filter(|(first, _)| **first == 0).map(|(_, rest)| rest.to_vec()), + }); + match moved { + Some(p) => { + o.path = p; + true + } + None => false, + } + }); + } +} + +/// Write the editing layer's art back into the symbol (called after every edit, with the document +/// as it was before); each instance of a dynamic symbol keeps its appearance changes to the objects +/// the art still has. Leaves the mode when the symbol or the layer is gone. Refuses art that holds +/// an instance of the symbol itself. +pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> { + let Some(se) = d.symbol_edit.clone() else { return Ok(()) }; + let art: Option<Vec<Arc<Node>>> = d.node(se.layer).and_then(|l| l.children().cloned()); + let (Some(art), Some(index)) = (art, d.symbols.iter().position(|x| x.name == se.symbol)) else { + d.symbol_edit = None; + let _ = d.remove(se.layer); + return Ok(()); + }; + // Entering, and edits that left the layer's art alone, write nothing. + let same = |b: &[Arc<Node>]| b.len() == art.len() && b.iter().zip(&art).all(|(a, b)| Arc::ptr_eq(a, b)); + let (old, old_group) = match before.symbol_edit.as_ref().filter(|b| b.layer == se.layer) { + None => return Ok(()), + Some(_) if before.node(se.layer).and_then(|l| l.children()).is_some_and(|b| same(b)) => return Ok(()), + Some(b) => (before.node(se.layer).and_then(|l| l.children().cloned()).unwrap_or_default(), b.group), + }; + if art.iter().any(|n| holds_symbol(d, n, &se.symbol, &mut HashSet::new())) { + return Err(EngineError::Other("a symbol can't hold an instance of itself".into())); + } + let inv = se.xf.inverse(); + let parts: Vec<Arc<Node>> = art + .iter() + .map(|n| { + let mut n = (**n).clone(); + n.transform(inv, false); + Arc::new(n) + }) + .collect(); + // Once the layer's objects make a group, later edits give that group its members. + let (new_art, group) = if se.group { + let mut g = (*d.symbols[index].art).clone(); + if let Some(ch) = g.children_mut() { + *ch = parts; + } + (g, true) + } else { + match <[Arc<Node>; 1]>::try_from(parts) { + Ok([one]) => (Arc::unwrap_or_clone(one), false), + Err(parts) => { + let id = d.alloc_id(); + (Node::group(id, parts), true) + } + } + }; + d.symbols[index].art = Arc::new(new_art); + follow_objects(d, &se.symbol, (&old, old_group), (&art, group)); + super::brushsym::fit_instances_of(d, &se.symbol); + if let Some(e) = d.symbol_edit.as_mut() { + e.changed = true; + e.group = group; + } + Ok(()) +} diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 2c3d66ee63..4a628d6ef3 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -2,10 +2,10 @@ use super::{NodeId, Value, cmd}; /// The commands that act on the active artboard (#693), which the app passes as their `artboard`: /// Paste in Place, in Front and in Back paste onto it, Align to Artboard aligns to it, Distribute -/// Objects and Distribute Spacing with Align to Artboard distribute objects across it, and All on -/// Active Artboard selects on it. A `command.batch` given `artboard` passes it on to each of their -/// steps that names none. -pub const ON_ACTIVE_ARTBOARD: [&str; 7] = [ +/// Objects and Distribute Spacing with Align to Artboard distribute objects across it, All on +/// Active Artboard selects on it, and Edit Symbol from the Symbols panel centers the symbol's art +/// on it. A `command.batch` given `artboard` passes it on to each of their steps that names none. +pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [ "edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack", @@ -13,6 +13,7 @@ pub const ON_ACTIVE_ARTBOARD: [&str; 7] = [ "object.distribute", "object.distributeSpacing", "select.allOnArtboard", + "symbol.edit", ]; /// The commands that resize the artboards the app passes (Object › Artboards): the app passes the @@ -23,9 +24,9 @@ pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitTo /// `(command, param)` pairs the journal records only so a replay reproduces the original run /// (dates from the clock: `cmd::clock_date`; the artboards the app passes to the -/// [`ON_ACTIVE_ARTBOARD`] and [`FIT_ACTIVE_ARTBOARD`] commands and to a batch); an action leaves -/// them out ([`Session::journal_for_action`]). -const REPLAY_ONLY: [(&str, &str); 14] = [ +/// [`ON_ACTIVE_ARTBOARD`] and [`FIT_ACTIVE_ARTBOARD`] commands and to a batch; the view's center +/// the app passes to Edit Symbol); an action leaves them out ([`Session::journal_for_action`]). +const REPLAY_ONLY: [(&str, &str); 16] = [ ("file.new", "created"), ("document.save", "modified"), ("file.saveAs", "modified"), @@ -39,6 +40,8 @@ const REPLAY_ONLY: [(&str, &str); 14] = [ ("artboard.fitToArt", "indices"), ("artboard.fitToSelection", "index"), ("select.allOnArtboard", "artboard"), + ("symbol.edit", "artboard"), + ("symbol.edit", "viewCenter"), ("command.batch", "artboard"), ]; diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 299f2f0004..30cf1e7e8d 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -34,6 +34,8 @@ pub struct DocState { /// Select › Start Global Edit: the objects edited together until Stop Global Edit or Escape /// ([`cmd::globaledit`]). Editing state: not saved, not undoable. pub global_edit: Option<cmd::globaledit::GlobalEdit>, + /// What leaving symbol editing mode goes back to ([`cmd::symboledit`]). + pub(crate) symbol_edit_return: cmd::symboledit::Return, pub interaction: Option<Interaction>, /// Edits made while this is open are one undo step (a scrubbed numeric field). pub undo_group: Option<UndoGroup>, @@ -246,6 +248,7 @@ impl DocState { variables_highlight: None, isolation: None, global_edit: None, + symbol_edit_return: Default::default(), interaction: None, undo_group: None, last_transform: None, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index df707de3a2..fd2de6ec5b 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -37,6 +37,10 @@ impl Session { if shaper_changed || dim_changed { cmd::objects_on_path::refresh(&before, Arc::make_mut(&mut st.doc)); } + // Symbol editing: the symbol follows its art on the editing layer, before + // inline graphics follow their symbols. + let symbol_synced = + if st.doc.symbol_edit.is_some() { cmd::symboledit::sync(&before, Arc::make_mut(&mut st.doc)) } else { Ok(()) }; // Inline graphics in text follow their symbols. cmd::inline::refresh(&before, Arc::make_mut(&mut st.doc)); // Text Wrap: area type follows its wrap objects; then threads re-flow. @@ -60,7 +64,9 @@ impl Session { if !st.doc.variables.bindings.is_empty() { Arc::make_mut(&mut st.doc).prune_variable_bindings(); } - if st.doc.too_deep(Some(&before)) { + if let Err(e) = symbol_synced { + Err(e) + } else if st.doc.too_deep(Some(&before)) { // Deeper trees overflow the stack of what walks them. Err(EngineError::Other(TOO_DEEP.into())) } else if doc_sane(&st.doc, &st.selection) && objects_in_range(&st.doc, &spread) { @@ -82,6 +88,21 @@ impl Session { // The art on a locked artboard can't stay selected, however it got there, except // the new art this edit made and new art still selected. st.protect_locked_artboards(&before_sel.objects, &before_sel.new_art, Some(&*before)); + // Symbol or opacity mask editing ended because the edit deleted its layer: + // isolation on the layer or inside it leaves too, out of symbol editing to what it + // was before. + let mode_layer = before.symbol_edit.as_ref().map(|e| e.layer).or(before.mask_edit.map(|m| m.layer)); + if let Some(layer) = mode_layer + && st.doc.node(layer).is_none() + && st.isolation.is_some_and(|i| i == layer || st.doc.node(i).is_none()) + { + if let Some(se) = &before.symbol_edit { + cmd::symboledit::go_back(st, se); + } else { + st.isolation = None; + st.active_layer = st.doc.default_layer(); + } + } st.revision += 1; if st.interaction.is_none() { let selection = match st.history.undo.last() { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c5baf054d1..2aab6da7df 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -158,6 +158,7 @@ mod swatchcmds; mod swatches; mod swatchlib; mod symbolbounds; +mod symboledit; mod symbollib; mod targeting; mod textcombos; diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 90da1f7f8b..cd50516a76 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1117,13 +1117,12 @@ fn place_and_break_link_round_trip_geometry() { } #[test] -fn edit_then_update_redefines_all_instances() { +fn break_link_then_update_redefines_all_instances() { let mut s = session(); let (inst, name, _) = make_symbol(&mut s); let other = NodeId(s.execute("symbol.place", &json!({"x": 300, "y": 200})).unwrap()["id"].as_u64().unwrap()); select(&mut s, &[inst]); - let r = s.execute("symbol.edit", &json!({})).unwrap(); - assert_eq!(r["name"], name); + let r = s.execute("symbol.breakLink", &json!({})).unwrap(); let art = NodeId(r["ids"][0].as_u64().unwrap()); // Make the art twice as wide, then redefine. s.execute("object.transform", &json!({"ids": [art.0], "matrix": [2, 0, 0, 1, -140, 0]})).ok(); diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index a580106d3c..aff7690c1d 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -144,8 +144,14 @@ fn break_link_bakes_the_changes_and_edit_symbol_shows_the_symbols_own_art() { }; let art = NodeId(s.execute("symbol.breakLink", &json!({"ids": [inst.0]})).unwrap()["ids"][0].as_u64().unwrap()); assert_eq!(fills(&s, art), ["#0000ff", "#ff0000"]); - let art = NodeId(s.execute("symbol.edit", &json!({"ids": [other.0]})).unwrap()["ids"][0].as_u64().unwrap()); - assert_eq!(fills(&s, art), ["#0000ff", "#0000ff"], "the symbol's art, without this instance's changes"); + // Symbol editing mode shows the symbol's art, without this instance's changes. + s.execute("symbol.edit", &json!({"ids": [other.0]})).unwrap(); + let st = s.doc().unwrap(); + let layer = st.doc.symbol_edit.as_ref().unwrap().layer; + let parts: Vec<String> = + st.doc.node(layer).unwrap().children().unwrap().iter().map(|c| c.appearance.fill_paint().color().unwrap().to_hex()).collect(); + assert_eq!(parts, ["#0000ff", "#0000ff"], "the symbol's art, without this instance's changes"); + assert_eq!(overrides(&s, other), 1, "the instance keeps its changes"); } #[test] diff --git a/crates/engine/src/tests/symboledit.rs b/crates/engine/src/tests/symboledit.rs new file mode 100644 index 0000000000..491d6cd830 --- /dev/null +++ b/crates/engine/src/tests/symboledit.rs @@ -0,0 +1,491 @@ +//! Symbol editing mode (`symbol.edit`, `symbol.exitEditing`). + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeKind; +use vectorcraft_geom::Rect; + +use crate::*; + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +fn id(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().expect("an id")) +} + +/// A 400 × 300 document with the 80 × 40 symbol "Box" made from a rectangle at (100, 50), its +/// instance there and a second instance centered on (300, 200). +fn two_instances() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 400, "height": 300})); + run(&mut s, "shape.rectangle", json!({"x": 100, "y": 50, "width": 80, "height": 40})); + let first = id(&run(&mut s, "symbol.new", json!({"name": "Box"}))); + let second = id(&run(&mut s, "symbol.place", json!({"name": "Box", "x": 300, "y": 200}))); + (s, first, second) +} + +/// The bounds of `id` as the document measures them: an instance's by its symbol's art. +fn bounds(s: &Session, id: NodeId) -> Rect { + s.doc().unwrap().doc.bounds_of(&[id], false).expect("bounds") +} + +fn close(a: Rect, b: Rect) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() < 1e-6) +} + +fn is_instance(s: &Session, id: NodeId) -> bool { + s.doc().unwrap().doc.node(id).is_some_and(|n| matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Box")) +} + +/// The objects on the editing layer. +fn layer_art(s: &Session) -> Vec<NodeId> { + let st = s.doc().unwrap(); + let layer = st.doc.symbol_edit.as_ref().expect("editing a symbol").layer; + st.doc.node(layer).and_then(|l| l.children()).map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default() +} + +#[test] +fn edit_symbol_edits_the_art_where_the_instance_shows_it_and_every_instance_follows() { + let (mut s, first, second) = two_instances(); + run(&mut s, "select.set", json!({"ids": [first.0]})); + let r = run(&mut s, "symbol.edit", json!({})); + assert_eq!((r["name"].as_str(), r["id"].as_u64()), (Some("Box"), Some(first.0))); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let st = s.doc().unwrap(); + assert_eq!(st.isolation, Some(layer)); + assert_eq!(st.active_layer, Some(layer)); + // The instance stays linked: editing the symbol doesn't expand it. + assert!(is_instance(&s, first) && is_instance(&s, second)); + let art = layer_art(&s); + assert_eq!(art.len(), 1); + assert!(close(bounds(&s, art[0]), Rect::new(100.0, 50.0, 180.0, 90.0)), "{:?}", bounds(&s, art[0])); + assert_eq!(s.doc().unwrap().selection.objects, art); + // An edit of the art reaches both instances at once, each at its own place. + run(&mut s, "object.move", json!({"dx": 10, "dy": 0})); + assert!(close(bounds(&s, first), Rect::new(110.0, 50.0, 190.0, 90.0)), "{:?}", bounds(&s, first)); + assert!(close(bounds(&s, second), Rect::new(270.0, 180.0, 350.0, 220.0)), "{:?}", bounds(&s, second)); + // New art goes into the symbol. + run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 10, "height": 10})); + assert_eq!(layer_art(&s).len(), 2); + assert!(close(bounds(&s, second), Rect::new(260.0, 180.0, 350.0, 240.0)), "{:?}", bounds(&s, second)); + let r = run(&mut s, "symbol.exitEditing", json!({})); + assert_eq!(r["name"], "Box"); + let st = s.doc().unwrap(); + assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none()); + assert!(st.doc.node(layer).is_none(), "the editing layer is gone"); + assert_eq!(st.selection.objects, vec![first]); + assert!(is_instance(&s, first)); + assert!(close(bounds(&s, second), Rect::new(260.0, 180.0, 350.0, 240.0)), "{:?}", bounds(&s, second)); +} + +#[test] +fn an_instance_transform_places_the_art_and_edits_go_back_through_it() { + let (mut s, first, second) = two_instances(); + // The second instance twice as large: a 20 pt move there is a 10 pt move of the symbol's art. + run(&mut s, "select.set", json!({"ids": [second.0]})); + run(&mut s, "object.scale", json!({"sx": 200, "sy": 200, "origin": [300, 200]})); + let big = bounds(&s, second); + assert!(close(big, Rect::new(220.0, 160.0, 380.0, 240.0)), "{big:?}"); + run(&mut s, "symbol.edit", json!({"id": second.0})); + let art = layer_art(&s); + assert!(close(bounds(&s, art[0]), big), "{:?}", bounds(&s, art[0])); + run(&mut s, "object.move", json!({"dx": 20, "dy": 0})); + assert!(close(bounds(&s, second), Rect::new(240.0, 160.0, 400.0, 240.0)), "{:?}", bounds(&s, second)); + assert!(close(bounds(&s, first), Rect::new(110.0, 50.0, 190.0, 90.0)), "{:?}", bounds(&s, first)); +} + +#[test] +fn the_symbols_panel_edits_a_symbol_without_an_instance_at_the_artboard_center() { + let (mut s, first, second) = two_instances(); + run(&mut s, "edit.clear", json!({"ids": [first.0, second.0]})); + run(&mut s, "select.none", json!({})); + let r = run(&mut s, "symbol.edit", json!({"name": "Box"})); + assert!(r.get("id").is_none()); + let art = layer_art(&s); + assert!(close(bounds(&s, art[0]), Rect::new(160.0, 130.0, 240.0, 170.0)), "{:?}", bounds(&s, art[0])); + run(&mut s, "object.move", json!({"dx": 0, "dy": 5})); + run(&mut s, "symbol.exitEditing", json!({})); + // No instance was added, and a new one shows the edited art. + let mut instances = 0; + s.doc().unwrap().doc.walk(|n| instances += usize::from(matches!(n.kind, NodeKind::SymbolInstance { .. }))); + assert_eq!(instances, 0); + let placed = id(&run(&mut s, "symbol.place", json!({"name": "Box", "x": 200, "y": 150}))); + assert!(close(bounds(&s, placed), Rect::new(160.0, 135.0, 240.0, 175.0)), "{:?}", bounds(&s, placed)); + assert!(s.execute("symbol.edit", &json!({"name": "Nope"})).is_err()); +} + +#[test] +fn the_symbols_panel_edits_a_symbol_at_the_center_of_the_active_artboard_or_the_view() { + let (mut s, _, _) = two_instances(); + run(&mut s, "artboard.new", json!({"x": 500, "y": 0, "width": 200, "height": 100})); + run(&mut s, "select.none", json!({})); + run(&mut s, "symbol.edit", json!({"name": "Box", "artboard": 1})); + let art = layer_art(&s); + assert!(close(bounds(&s, art[0]), Rect::new(560.0, 30.0, 640.0, 70.0)), "{:?}", bounds(&s, art[0])); + run(&mut s, "symbol.exitEditing", json!({})); + // An artboard the document doesn't have: the first one. + run(&mut s, "symbol.edit", json!({"name": "Box", "artboard": 7, "viewCenter": [1000, 1000]})); + let art = layer_art(&s); + assert!(close(bounds(&s, art[0]), Rect::new(160.0, 130.0, 240.0, 170.0)), "{:?}", bounds(&s, art[0])); + run(&mut s, "symbol.exitEditing", json!({})); + // Without artboards, the view's center. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.clear(); + run(&mut s, "symbol.edit", json!({"name": "Box", "viewCenter": [1000, 1000]})); + let art = layer_art(&s); + assert!(close(bounds(&s, art[0]), Rect::new(960.0, 980.0, 1040.0, 1020.0)), "{:?}", bounds(&s, art[0])); +} + +#[test] +fn leaving_without_an_edit_leaves_the_document_and_its_history_as_they_were() { + let (mut s, first, _) = two_instances(); + let steps = s.doc().unwrap().history.undo.len(); + let art = s.doc().unwrap().doc.symbols[0].art.clone(); + run(&mut s, "symbol.edit", json!({"id": first.0})); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + run(&mut s, "object.exitIsolation", json!({})); + let st = s.doc().unwrap(); + assert_eq!(st.history.undo.len(), steps); + assert!(std::sync::Arc::ptr_eq(&st.doc.symbols[0].art, &art)); + assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none()); + // Outside the mode, leaving it does nothing. + run(&mut s, "symbol.exitEditing", json!({})); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + // A step undone before editing can still be redone after leaving without an edit. + run(&mut s, "shape.rectangle", json!({"x": 300, "y": 20, "width": 10, "height": 10})); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "symbol.edit", json!({"id": first.0})); + assert!(s.doc().unwrap().history.redo.is_empty()); + run(&mut s, "symbol.exitEditing", json!({})); + assert_eq!(s.doc().unwrap().history.redo.len(), 1); + run(&mut s, "edit.redo", json!({})); + // Leaving after an edit that was undone adds a step, keeping the redo step that holds the + // editing layer apart from the document outside the mode. + run(&mut s, "symbol.edit", json!({"id": first.0})); + run(&mut s, "object.move", json!({"dx": 10, "dy": 0})); + run(&mut s, "edit.undo", json!({})); + let steps = s.doc().unwrap().history.undo.len(); + run(&mut s, "symbol.exitEditing", json!({})); + let st = s.doc().unwrap(); + assert_eq!(st.history.undo.len(), steps + 1); + assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none()); +} + +#[test] +fn leaving_without_an_edit_keeps_the_current_symbol_picked_while_editing() { + let (mut s, first, _) = two_instances(); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})); + run(&mut s, "symbol.new", json!({"name": "Small"})); + run(&mut s, "symbol.setCurrent", json!({"name": "Box"})); + let steps = s.doc().unwrap().history.undo.len(); + run(&mut s, "symbol.edit", json!({"id": first.0})); + // A click in the Symbols panel while editing: not an undo step. + run(&mut s, "symbol.setCurrent", json!({"name": "Small"})); + run(&mut s, "symbol.exitEditing", json!({})); + let st = s.doc().unwrap(); + assert_eq!(st.history.undo.len(), steps); + assert_eq!(st.doc.unknown.get("currentSymbol").and_then(Value::as_str), Some("Small")); +} + +#[test] +fn leaving_right_after_a_batch_that_only_entered_takes_its_step_back() { + let (mut s, first, _) = two_instances(); + let steps = s.doc().unwrap().history.undo.len(); + run(&mut s, "command.batch", json!({"commands": [{"command": "symbol.edit", "params": {"id": first.0}}]})); + assert!(s.doc().unwrap().doc.symbol_edit.is_some()); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + run(&mut s, "symbol.exitEditing", json!({})); + let st = s.doc().unwrap(); + assert_eq!(st.history.undo.len(), steps); + assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none()); +} + +#[test] +fn leaving_right_after_a_batch_that_edited_and_entered_keeps_its_edits() { + let (mut s, first, second) = two_instances(); + let steps = s.doc().unwrap().history.undo.len(); + // A batch named like the entering step that moves an instance before entering: leaving keeps + // the move and adds a step of its own. + let moved = Rect::new(310.0, 180.0, 390.0, 220.0); + let commands = json!([ + {"command": "select.set", "params": {"ids": [second.0]}}, + {"command": "object.move", "params": {"dx": 50, "dy": 0}}, + {"command": "symbol.edit", "params": {"id": first.0}}, + ]); + run(&mut s, "command.batch", json!({"label": "Edit Symbol", "commands": commands})); + assert!(close(bounds(&s, second), moved), "{:?}", bounds(&s, second)); + run(&mut s, "symbol.exitEditing", json!({})); + let st = s.doc().unwrap(); + assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none()); + assert_eq!(st.history.undo.len(), steps + 2); + assert!(close(bounds(&s, second), moved), "{:?}", bounds(&s, second)); + // Undo takes back the exit, then the batch's move and entry together. + run(&mut s, "edit.undo", json!({})); + assert!(s.doc().unwrap().doc.symbol_edit.is_some()); + run(&mut s, "edit.undo", json!({})); + let st = s.doc().unwrap(); + assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none()); + assert!(close(bounds(&s, second), Rect::new(260.0, 180.0, 340.0, 220.0)), "{:?}", bounds(&s, second)); +} + +#[test] +fn redefining_the_symbol_being_edited_leaves_symbol_editing_mode_in_the_same_step() { + let (mut s, first, second) = two_instances(); + let other = id(&run(&mut s, "shape.rectangle", json!({"x": 10, "y": 200, "width": 30, "height": 30}))); + let layer = NodeId(run(&mut s, "symbol.edit", json!({"id": first.0}))["layer"].as_u64().unwrap()); + // The art on the editing layer can't redefine the symbol. + let e = s.execute("symbol.update", &json!({"name": "Box"})).unwrap_err().to_string(); + assert!(e.contains("can't hold an instance of itself"), "{e}"); + let steps = s.doc().unwrap().history.undo.len(); + run(&mut s, "symbol.update", json!({"name": "Box", "ids": [other.0]})); + let st = s.doc().unwrap(); + assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none() && st.doc.node(layer).is_none()); + assert_eq!(st.history.undo.len(), steps + 1); + // Every instance shows the new 30 × 30 art, and a later edit can't bring the old art back. + assert!(close(bounds(&s, second), Rect::new(285.0, 185.0, 315.0, 215.0)), "{:?}", bounds(&s, second)); + run(&mut s, "shape.rectangle", json!({"x": 300, "y": 10, "width": 10, "height": 10})); + assert!(close(bounds(&s, second), Rect::new(285.0, 185.0, 315.0, 215.0)), "{:?}", bounds(&s, second)); + // Undo goes back into the edit as it was. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + let st = s.doc().unwrap(); + assert_eq!(st.isolation, Some(layer)); + assert!(st.doc.symbol_edit.is_some()); +} + +#[test] +fn leaving_goes_back_to_the_isolation_before_and_undo_keeps_a_group_isolated_inside() { + let (mut s, first, _) = two_instances(); + // The instance in an isolated group. + let other = id(&run(&mut s, "shape.rectangle", json!({"x": 10, "y": 200, "width": 20, "height": 20}))); + run(&mut s, "select.set", json!({"ids": [first.0, other.0]})); + let group = id(&run(&mut s, "object.group", json!({}))); + run(&mut s, "object.isolate", json!({"id": group.0})); + run(&mut s, "symbol.edit", json!({"id": first.0})); + run(&mut s, "symbol.exitEditing", json!({})); + assert_eq!(s.doc().unwrap().isolation, Some(group)); + // A group isolated inside the symbol's art stays isolated through an undo. + let layer = NodeId(run(&mut s, "symbol.edit", json!({"id": first.0}))["layer"].as_u64().unwrap()); + run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 10, "height": 10})); + let art: Vec<u64> = layer_art(&s).iter().map(|i| i.0).collect(); + run(&mut s, "select.set", json!({ "ids": art })); + let inner = id(&run(&mut s, "object.group", json!({}))); + run(&mut s, "object.isolate", json!({"id": inner.0})); + run(&mut s, "select.all", json!({})); + run(&mut s, "object.move", json!({"dx": 5, "dy": 0})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc().unwrap().isolation, Some(inner)); + run(&mut s, "object.exitIsolation", json!({})); + assert_eq!(s.doc().unwrap().isolation, Some(layer)); + run(&mut s, "object.exitIsolation", json!({})); + assert_eq!(s.doc().unwrap().isolation, Some(group)); + // Deleting the editing layer goes back there too. + let layer = NodeId(run(&mut s, "symbol.edit", json!({"id": first.0}))["layer"].as_u64().unwrap()); + run(&mut s, "layer.delete", json!({"ids": [layer.0]})); + assert_eq!(s.doc().unwrap().isolation, Some(group)); +} + +#[test] +fn leaving_after_a_save_keeps_the_document_saved() { + let (mut s, first, _) = two_instances(); + for edit in [false, true] { + run(&mut s, "symbol.edit", json!({"id": first.0})); + if edit { + run(&mut s, "object.move", json!({"dx": 10, "dy": 0})); + } + // The save leaves the editing layer out of the file. + s.doc_mut().unwrap().mark_saved(); + run(&mut s, "symbol.exitEditing", json!({})); + let st = s.doc().unwrap(); + assert!(!st.is_dirty(), "edit: {edit}"); + assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none(), "edit: {edit}"); + } +} + +#[test] +fn deleting_the_editing_layer_leaves_symbol_editing_mode() { + let (mut s, first, _) = two_instances(); + let layer = NodeId(run(&mut s, "symbol.edit", json!({"id": first.0}))["layer"].as_u64().unwrap()); + run(&mut s, "layer.delete", json!({"ids": [layer.0]})); + let st = s.doc().unwrap(); + assert!(st.doc.symbol_edit.is_none() && st.doc.node(layer).is_none()); + assert_eq!(st.isolation, None); + assert!(st.active_layer.is_some_and(|l| st.doc.node(l).is_some())); + assert!(is_instance(&s, first)); +} + +#[test] +fn undo_and_redo_restore_the_art_every_instance_shows_and_the_mode() { + let (mut s, first, second) = two_instances(); + run(&mut s, "symbol.edit", json!({"id": first.0})); + let layer = s.doc().unwrap().doc.symbol_edit.as_ref().unwrap().layer; + run(&mut s, "object.move", json!({"dx": 10, "dy": 0})); + run(&mut s, "symbol.exitEditing", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc().unwrap().isolation, Some(layer), "back in symbol editing mode"); + run(&mut s, "edit.undo", json!({})); + assert!(close(bounds(&s, second), Rect::new(260.0, 180.0, 340.0, 220.0)), "{:?}", bounds(&s, second)); + assert_eq!(s.doc().unwrap().isolation, Some(layer)); + run(&mut s, "edit.undo", json!({})); + let st = s.doc().unwrap(); + assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none()); + run(&mut s, "edit.redo", json!({})); + run(&mut s, "edit.redo", json!({})); + assert!(close(bounds(&s, second), Rect::new(270.0, 180.0, 350.0, 220.0)), "{:?}", bounds(&s, second)); + assert_eq!(s.doc().unwrap().isolation, Some(layer)); +} + +#[test] +fn instances_of_one_symbol_only_and_no_instance_of_itself() { + let (mut s, first, _) = two_instances(); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})); + let other = id(&run(&mut s, "symbol.new", json!({"name": "Small"}))); + run(&mut s, "select.set", json!({"ids": [first.0, other.0]})); + let e = s.execute("symbol.edit", &json!({})).unwrap_err().to_string(); + assert!(e.contains("select instances of one symbol"), "{e}"); + let e = s.execute("symbol.edit", &json!({"ids": [first.0, other.0]})).unwrap_err().to_string(); + assert!(e.contains("select instances of one symbol"), "{e}"); + assert!(s.execute("symbol.edit", &json!({"ids": [first.0, 999_999]})).is_err()); + assert!(s.doc().unwrap().doc.symbol_edit.is_none()); + run(&mut s, "symbol.edit", json!({"id": first.0})); + let e = s.execute("symbol.place", &json!({"name": "Box"})).unwrap_err().to_string(); + assert!(e.contains("can't hold an instance of itself"), "{e}"); + assert_eq!(layer_art(&s).len(), 1); + // An instance of another symbol may go in. + run(&mut s, "symbol.place", json!({"name": "Small"})); + assert_eq!(layer_art(&s).len(), 2); +} + +#[test] +fn other_editing_modes_and_symbol_editing_do_not_overlap() { + let (mut s, first, second) = two_instances(); + run(&mut s, "symbol.edit", json!({"id": first.0})); + assert!(s.execute("object.pattern.make", &json!({})).is_err()); + assert!(s.execute("transparency.editOpacityMask", &json!({})).is_err()); + // Editing another symbol from the panel ends this edit first. + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})); + run(&mut s, "symbol.exitEditing", json!({})); + run(&mut s, "select.set", json!({"ids": [second.0]})); + run(&mut s, "symbol.edit", json!({})); + run(&mut s, "symbol.edit", json!({"name": "Box", "x": 50, "y": 50})); + assert_eq!(s.doc().unwrap().doc.symbol_edit.as_ref().unwrap().instance, None); + assert_eq!(s.doc().unwrap().doc.layers.iter().filter(|l| l.name.as_deref() == Some("Box")).count(), 1); +} + +#[test] +fn renaming_deleting_and_saving_while_a_symbol_is_edited() { + let (mut s, first, _) = two_instances(); + run(&mut s, "symbol.edit", json!({"id": first.0})); + run(&mut s, "object.move", json!({"dx": 10, "dy": 0})); + let layer = s.doc().unwrap().doc.symbol_edit.as_ref().unwrap().layer; + // Saving leaves the editing layer out; the symbol already holds the edit. + let saved = s.doc().unwrap().doc.without_edit_modes().into_owned(); + assert!(saved.symbol_edit.is_none() && saved.node(layer).is_none()); + assert!(saved.symbols[0].art.geometric_bounds().is_some()); + run(&mut s, "symbol.options", json!({"name": "Box", "newName": "Crate"})); + let st = s.doc().unwrap(); + assert_eq!(st.doc.symbol_edit.as_ref().unwrap().symbol, "Crate"); + assert_eq!(st.doc.node(layer).and_then(|l| l.name.clone()).as_deref(), Some("Crate")); + run(&mut s, "object.move", json!({"dx": 10, "dy": 0})); + // Deleting the symbol being edited leaves the mode in the same step. + run(&mut s, "symbol.delete", json!({"name": "Crate"})); + let st = s.doc().unwrap(); + assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none() && st.doc.node(layer).is_none()); + assert!(st.doc.symbols.is_empty()); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc().unwrap().isolation, Some(layer)); +} + +/// Deleting several symbols, the one being edited among them, leaves the mode in the same step. +#[test] +fn deleting_several_symbols_with_the_edited_one_leaves_the_mode() { + let (mut s, first, _) = two_instances(); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 200, "width": 20, "height": 20})); + run(&mut s, "symbol.new", json!({"name": "Dot"})); + run(&mut s, "symbol.edit", json!({"id": first.0})); + let layer = s.doc().unwrap().doc.symbol_edit.as_ref().unwrap().layer; + run(&mut s, "symbol.delete", json!({"names": ["Dot", "Box"]})); + let st = s.doc().unwrap(); + assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none() && st.doc.node(layer).is_none()); + assert!(st.doc.symbols.is_empty()); +} + +/// Editing a dynamic symbol keeps each instance's appearance changes to the objects its art still +/// has, and drops the changes to an object the edit deleted. +#[test] +fn editing_a_dynamic_symbol_keeps_the_instances_changes_to_the_objects_still_there() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 400, "height": 300})); + let a = id(&run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40}))); + let b = id(&run(&mut s, "shape.rectangle", json!({"x": 60, "y": 10, "width": 40, "height": 40}))); + let inst = id(&run(&mut s, "symbol.new", json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"}))); + run(&mut s, "symbol.instance.setAppearance", json!({"id": inst.0, "path": [0], "fill": "#00ff00"})); + run(&mut s, "symbol.instance.setAppearance", json!({"id": inst.0, "path": [1], "fill": "#ff0000"})); + // Each change by the path it names and the color it paints. + let changes = |s: &Session| -> Vec<(Vec<u32>, String)> { + let n = s.doc().unwrap().doc.node(inst).unwrap().clone(); + n.extras().symbol_overrides.iter().map(|o| (o.path.clone(), o.fill.as_ref().and_then(|p| p.color()).unwrap().to_hex())).collect() + }; + let other = id(&run(&mut s, "symbol.place", json!({"name": "Pair", "x": 200, "y": 200}))); + run(&mut s, "symbol.edit", json!({"id": other.0})); + let art = layer_art(&s); + assert_eq!(art.len(), 2); + // Deleting the first object: the change to the second follows it to the first place. + run(&mut s, "select.set", json!({"ids": [art[0].0]})); + run(&mut s, "edit.clear", json!({})); + assert_eq!(changes(&s), vec![(vec![0], "#ff0000".to_string())], "the change to the deleted object goes"); + run(&mut s, "symbol.exitEditing", json!({})); + assert_eq!(changes(&s), vec![(vec![0], "#ff0000".to_string())]); + assert!(s.doc().unwrap().doc.node(inst).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }))); +} + +#[test] +fn undo_back_into_an_earlier_edit_leaves_it_to_its_own_isolation() { + let (mut s, first, second) = two_instances(); + let other = id(&run(&mut s, "shape.rectangle", json!({"x": 10, "y": 200, "width": 20, "height": 20}))); + run(&mut s, "select.set", json!({"ids": [second.0, other.0]})); + let group = id(&run(&mut s, "object.group", json!({}))); + // The first edit is entered with nothing isolated. + run(&mut s, "symbol.edit", json!({"id": first.0})); + run(&mut s, "object.move", json!({"dx": 10, "dy": 0})); + run(&mut s, "symbol.exitEditing", json!({})); + assert_eq!(s.doc().unwrap().isolation, None); + // The second edit is entered with the group isolated. + run(&mut s, "object.isolate", json!({"id": group.0})); + run(&mut s, "symbol.edit", json!({"id": second.0})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc().unwrap().isolation, Some(group)); + // Back in the first edit, leaving it goes back to what it was entered from. + run(&mut s, "edit.undo", json!({})); + assert!(s.doc().unwrap().doc.symbol_edit.is_some()); + run(&mut s, "symbol.exitEditing", json!({})); + assert_eq!(s.doc().unwrap().isolation, None); +} + +#[test] +fn undoing_entry_with_a_group_isolated_inside_the_art_goes_back_to_before() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 400, "height": 300})); + let a = id(&run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))); + let b = id(&run(&mut s, "shape.rectangle", json!({"x": 40, "y": 10, "width": 20, "height": 20}))); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let inner = id(&run(&mut s, "object.group", json!({}))); + let c = id(&run(&mut s, "shape.rectangle", json!({"x": 10, "y": 40, "width": 20, "height": 20}))); + run(&mut s, "select.set", json!({"ids": [inner.0, c.0]})); + let instance = id(&run(&mut s, "symbol.new", json!({"name": "Pair"}))); + let before = s.doc().unwrap().active_layer; + assert!(before.is_some()); + run(&mut s, "symbol.edit", json!({"id": instance.0})); + let layer = s.doc().unwrap().doc.symbol_edit.as_ref().unwrap().layer; + let group = { + let st = s.doc().unwrap(); + layer_art(&s).into_iter().find(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. }))).expect("a group") + }; + run(&mut s, "object.isolate", json!({"id": group.0})); + assert_eq!(s.doc().unwrap().isolation, Some(group)); + run(&mut s, "edit.undo", json!({})); + let st = s.doc().unwrap(); + assert!(st.doc.symbol_edit.is_none() && st.doc.node(layer).is_none()); + assert_eq!(st.isolation, None); + assert_eq!(st.active_layer, before); +} diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index bcbce02eeb..737a29f676 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -1170,6 +1170,11 @@ impl SelectionTool { if cx.doc.node(top).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Text(_))) { return vec![Action::SwitchTool("type".into())]; } + // A symbol instance: its symbol is edited in symbol editing mode, except one inside + // the art of a symbol already being edited. + if cx.doc.node(top).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. })) { + return if cx.doc.symbol_edit.is_some() { vec![] } else { vec![Action::Exec("symbol.edit".into(), json!({ "id": top.0 }))] }; + } // An object that [`isolates`], not the one already isolated. if cx.double_click_isolate && cx.doc.node(top).is_some_and(|n| isolates(&n.kind)) && cx.isolation != Some(top) { return vec![Action::Exec("object.isolate".into(), json!({ "id": top.0 }))]; diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 8e949e4d15..4b41a8592a 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -1964,3 +1964,37 @@ fn the_preview_memo_measures_once_per_revision_selection_and_preview_bounds() { let c = cx(&moved, &s, &p); assert_eq!(selection_bounds(&c).map(|r| r.x1), Some(250.0)); } + +/// A double-click on a symbol instance edits its symbol in symbol editing mode (`symbol.edit`), and +/// one outside the symbol's art in that mode leaves it, as it leaves isolation mode. An instance +/// inside the art of the symbol being edited is not entered. +#[test] +fn a_double_click_on_a_symbol_instance_edits_its_symbol() { + use vectorcraft_doc::{Appearance, Node, NodeKind, Symbol, SymbolEdit}; + let (mut d, rect) = doc_with_rect(); + let art = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), Appearance::default_art()); + d.symbols.push(Symbol { dynamic: false, name: "Dot".into(), art: std::sync::Arc::new(art) }); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let xf = Affine::translate((300.0, 300.0)) * Affine::scale(2.0); + d.insert(Some(l), usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: "Dot".into(), xf })).unwrap(); + let (s, p) = (Selection::default(), paint()); + let double = |d: &vectorcraft_doc::Document, isolation: Option<NodeId>, x: f64, y: f64| { + let c = ToolContext { isolation, ..cx(d, &s, &p) }; + SelectionTool::default().pointer(&c, &ev(PointerKind::DoubleClick, x, y)) + }; + assert_eq!(double(&d, None, 300.0, 300.0), vec![Action::Exec("symbol.edit".into(), json!({"id": id.0}))]); + assert_eq!(double(&d, None, 150.0, 150.0), vec![Action::Exec("object.isolate".into(), json!({"id": rect.0}))]); + // In symbol editing mode, with the instance on the editing layer. + d.symbol_edit = Some(SymbolEdit { + symbol: "Other".into(), + layer: l, + instance: None, + xf: Affine::IDENTITY, + group: false, + changed: false, + back_isolation: None, + back_layer: None, + }); + assert_eq!(double(&d, Some(l), 300.0, 300.0), vec![]); + assert_eq!(double(&d, Some(l), 450.0, 50.0), vec![Action::Exec("object.exitIsolation".into(), json!({}))]); +} diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 8ca150101a..e08b108cca 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -38,8 +38,9 @@ impl VectorcraftApp { } let mut params = params; // Paste in place, in front and in back (#693), Select › All on Active Artboard (#1006), and Align, - // Distribute Objects and Distribute Spacing with Align to Artboard act on the active artboard, the - // view's, which the app passes as `artboard`. A batch passes it on to those steps. + // Distribute Objects and Distribute Spacing with Align to Artboard, and Edit Symbol from the Symbols + // panel act on the active artboard, the view's, which the app passes as `artboard`. A batch passes + // it on to those steps. if (vectorcraft_engine::ON_ACTIVE_ARTBOARD.contains(&id) || id == "command.batch") && params.get("artboard").is_none() && self.view().is_some() @@ -48,6 +49,29 @@ impl VectorcraftApp { { p.insert("artboard".into(), serde_json::json!(panels::artboards::selected(self, n))); } + // Edit Symbol from the Symbols panel in a document without artboards centers the symbol's + // art in the view, whose center the app passes as `viewCenter`, to a batch's symbol.edit + // steps too. + if matches!(id, "symbol.edit" | "command.batch") + && let Some(c) = self.view().map(|v| v.center) + { + let fill = |p: &mut serde_json::Value| { + if let Some(p) = p.as_object_mut() { + p.entry("viewCenter").or_insert(serde_json::json!([c.x, c.y])); + } + }; + if id == "symbol.edit" { + fill(&mut params); + } else if let Some(serde_json::Value::Array(steps)) = params.get_mut("commands") { + for step in steps { + if step.get("command").and_then(serde_json::Value::as_str) == Some("symbol.edit") + && let Some(step) = step.as_object_mut() + { + fill(step.entry("params").or_insert_with(|| serde_json::json!({}))); + } + } + } + } // Object › Artboards › Fit to Artwork Bounds resizes the selected artboards (the Artboard // tool's, else the active one), which the app passes as its `indices`, and Fit to Selected // Art resizes the active artboard, which the app passes as its `index`. diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 79b6b54675..924a644067 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -104,17 +104,22 @@ fn snapping_menu(app: &mut VectorcraftApp, ui: &mut Ui) { } /// The Control bar's isolation button. In isolation mode it is Exit Isolation Mode, except while a -/// pattern is edited (the isolation bar's Done and Cancel end that). Otherwise, with one object -/// selected that [`vectorcraft_tools::select::isolates`], it is Isolate Selected Object, which -/// also isolates a path inside a group that Direct Selection selected. An envelope's contents -/// get no button: the envelope's Edit Envelope and Edit Contents buttons show instead. +/// pattern is edited (the isolation bar's Done and Cancel end that), and Exit Symbol Editing Mode +/// while a symbol's art is the isolated layer. Otherwise, with one object selected that +/// [`vectorcraft_tools::select::isolates`], it is Isolate Selected Object, which also isolates a +/// path inside a group that Direct Selection selected. An envelope's contents get no button: the +/// envelope's Edit Envelope and Edit Contents buttons show instead. fn isolation_button(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(st) = app.session.active() else { return }; let (icon, tip, id) = if st.isolation.is_some() { if st.doc.pattern_edit.is_some() { return; } - ("chevron-left", tl!("Exit Isolation Mode"), "object.exitIsolation") + if st.doc.symbol_edit.as_ref().is_some_and(|e| st.isolation == Some(e.layer)) { + ("chevron-left", tl!("Exit Symbol Editing Mode"), "symbol.exitEditing") + } else { + ("chevron-left", tl!("Exit Isolation Mode"), "object.exitIsolation") + } } else if let [one] = st.selection.objects[..] && st.doc.node(one).is_some_and(|n| vectorcraft_tools::select::isolates(&n.kind)) && vectorcraft_doc::live::envelope_of(&st.doc, one).is_none() diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 904c220bab..ee71fa0f61 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -910,6 +910,7 @@ font-technology Variable Променливи Edit Selection Редактиране на селекцията Edit Selection… Редактиране на селекцията… Edit Symbol Редактиране на символ + Exit Symbol Editing Mode Изход от режим на редактиране на символ Edit Text Редактиране на текст Edit the applied effect, or add another one? Да се редактира ли приведеният ефект или да се добави друг? Edit the point Редактиране на точката @@ -4221,6 +4222,8 @@ axis Both И двете @msg select an Intertwine group изберете група за преплитане (Intertwine) @msg select a stroke with a variable width изберете щрих с променлива дебелина @msg select a symbol instance изберете екземпляр на символ +@msg select instances of one symbol изберете екземпляри на един символ +@msg a symbol can't hold an instance of itself символ не може да съдържа свой собствен екземпляр @msg select an Image Trace object изберете обект за трасиране на изображение (Image Trace) @msg could not decode image: {0} изображението не може да бъде декодирано: {0} @msg image is empty изображението е празно diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d9e96915f4..69b53b2d11 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3088,6 +3088,7 @@ theme Appearance Izgled Duplicate Brush Dupliciraj četkicu Duplicate Symbol Dupliciraj simbol Edit Symbol Uredi simbol + Exit Symbol Editing Mode Izađi iz načina uređivanja simbola Expand Brush Strokes Proširi poteze četkicom New Brush… Nova četkica… New Brush Nova četkica @@ -4619,6 +4620,8 @@ imageTrace Outline Obris @msg a clipping path can't be attached to a path putanja isijecanja ne može se priložiti putanji @msg select a stroke with a variable width odaberite potez s promjenjivom širinom @msg select a symbol instance odaberite instancu simbola +@msg select instances of one symbol odaberite instance jednog simbola +@msg a symbol can't hold an instance of itself simbol ne može sadržavati instancu samog sebe @msg select an Image Trace object odaberite objekat praćenja slike @msg could not decode image: {0} nije moguće dekodirati sliku: {0} @msg image is empty slika je prazna diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 5cbf470f69..ced6fdc32e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1313,6 +1313,7 @@ Edit Selection Edita la selecció Edit Selection… Edita la selecció… Edit Symbol Edita el símbol + Exit Symbol Editing Mode Surt del mode d’edició de símbols Edit Text Edita el text Edit the applied effect, or add another one? Vols editar l’efecte aplicat o afegir-ne un altre? Edit the point Edita el punt @@ -5377,6 +5378,9 @@ digits Malayalam Malaiàlam @msg select a repeat selecciona una repetició @msg select a stroke with a variable width selecciona un traç amb amplada variable @msg select a symbol instance selecciona una instància de símbol +@msg select instances of one symbol selecciona instàncies d’un sol símbol +@msg a symbol can't hold an instance of itself un símbol no pot contenir una instància de si mateix +@msg exit isolation mode first surt primer del mode d’aïllament @msg select an envelope selecciona un embolcall @msg select an image selecciona una imatge @msg select an Image Trace object selecciona un objecte d’Image Trace diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 86c2c2ef43..c7626cc9f6 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3119,6 +3119,7 @@ theme Appearance Motiv Duplicate Brush Duplikovat štětec Duplicate Symbol Duplikovat symbol Edit Symbol Upravit symbol + Exit Symbol Editing Mode Ukončit režim úprav symbolu Expand Brush Strokes Rozložit tahy štětcem New Brush… Nový štětec… New Brush Nový štětec @@ -4659,6 +4660,8 @@ imageTrace Outline Obrys @msg a clipping path can't be attached to a path ořezovou cestu nelze připojit na cestu @msg select a stroke with a variable width vyberte tah s proměnnou šířkou @msg select a symbol instance vyberte instanci symbolu +@msg select instances of one symbol vyberte instance jediného symbolu +@msg a symbol can't hold an instance of itself symbol nemůže obsahovat instanci sebe sama @msg select an Image Trace object vyberte objekt vektorizace obrazu @msg could not decode image: {0} obraz nelze dekódovat: {0} @msg image is empty obraz je prázdný diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index bee5e72703..d66fe03333 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2872,6 +2872,7 @@ theme Appearance Udseende Duplicate Brush Duplikér pensel Duplicate Symbol Duplikér symbol Edit Symbol Redigér symbol + Exit Symbol Editing Mode Afslut symbolredigeringstilstand Expand Brush Strokes Udvid penselstrøg New Brush… Ny pensel… New Brush Ny pensel @@ -4323,6 +4324,8 @@ imageTrace Outline Kontur @msg select a repeat markér en gentagelse @msg select a stroke with a variable width markér en streg med variabel bredde @msg select a symbol instance markér en symbolforekomst +@msg select instances of one symbol markér forekomster af ét symbol +@msg a symbol can't hold an instance of itself et symbol kan ikke indeholde en forekomst af sig selv @msg select an Image Trace object markér et Image Trace-objekt @msg could not decode image: {0} kunne ikke afkode billedet: {0} @msg image is empty billedet er tomt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 92ca0c2399..2a787c528f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -904,6 +904,7 @@ font-technology Variable Variabel Edit Selection Auswahl bearbeiten Edit Selection… Auswahl bearbeiten… Edit Symbol Symbol bearbeiten + Exit Symbol Editing Mode Symbolbearbeitungsmodus beenden Edit Text Text bearbeiten Edit the applied effect, or add another one? Den angewendeten Effekt bearbeiten oder einen weiteren hinzufügen? Edit the point Punkt bearbeiten @@ -4268,6 +4269,8 @@ theme Appearance Erscheinungsbild @msg a clipping path can't be attached to a path ein Schnittpfad kann nicht an einen Pfad angehängt werden @msg select a stroke with a variable width wählen Sie eine Kontur mit variabler Breite aus @msg select a symbol instance wählen Sie eine Symbolinstanz aus +@msg select instances of one symbol wählen Sie Instanzen eines einzigen Symbols aus +@msg a symbol can't hold an instance of itself ein Symbol kann keine Instanz von sich selbst enthalten @msg select an Image Trace object wählen Sie ein Bildnachzeichner-Objekt aus @msg could not decode image: {0} das Bild konnte nicht dekodiert werden: {0} @msg image is empty das Bild ist leer diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 30ab097ecd..335d01af63 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -880,6 +880,7 @@ font-technology Variable Μεταβλητές Edit Selection Επεξεργασία επιλογής Edit Selection… Επεξεργασία επιλογής… Edit Symbol Επεξεργασία συμβόλου + Exit Symbol Editing Mode Έξοδος από τη λειτουργία επεξεργασίας συμβόλου Edit Text Επεξεργασία κειμένου Edit the applied effect, or add another one? Επεξεργασία του εφαρμοσμένου εφέ ή προσθήκη άλλου; Edit the point Επεξεργασία σημείου @@ -4301,6 +4302,8 @@ digits Malayalam Μαλαγιάλαμ @msg select a repeat επιλέξτε επανάληψη @msg select a stroke with a variable width επιλέξτε περίγραμμα μεταβλητού πλάτους @msg select a symbol instance επιλέξτε στιγμιότυπο συμβόλου +@msg select instances of one symbol επιλέξτε στιγμιότυπα ενός μόνο συμβόλου +@msg a symbol can't hold an instance of itself ένα σύμβολο δεν μπορεί να περιέχει στιγμιότυπο του εαυτού του @msg select an Image Trace object επιλέξτε αντικείμενο διανυσματοποίησης εικόνας @msg could not decode image: {0} δεν ήταν δυνατή η αποκωδικοποίηση εικόνας: {0} @msg image is empty η εικόνα είναι κενή diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 48797306ca..0b7a0cfaa6 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -925,6 +925,7 @@ font-technology Variable Variables Edit Selection Editar selección Edit Selection… Editar selección… Edit Symbol Editar símbolo + Exit Symbol Editing Mode Salir del modo de edición de símbolos Edit Text Editar texto Edit the applied effect, or add another one? ¿Editar el efecto aplicado o agregar otro? Edit the point Editar el punto @@ -4353,6 +4354,8 @@ axis Both Ambos @msg a clipping path can't be attached to a path un trazado de recorte no se puede adjuntar a un trazado @msg select a stroke with a variable width selecciona un trazo con anchura variable @msg select a symbol instance selecciona una instancia de símbolo +@msg select instances of one symbol selecciona instancias de un solo símbolo +@msg a symbol can't hold an instance of itself un símbolo no puede contener una instancia de sí mismo @msg select an Image Trace object selecciona un objeto de calco de imagen @msg could not decode image: {0} no se pudo decodificar la imagen: {0} @msg image is empty la imagen está vacía diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1f7de4be19..c733d6143a 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3058,6 +3058,7 @@ theme Appearance Ulkoasu Duplicate Brush Monista sivellin Duplicate Symbol Monista symboli Edit Symbol Muokkaa symbolia + Exit Symbol Editing Mode Poistu symbolin muokkaustilasta Expand Brush Strokes Laajenna sivellinviivat New Brush… Uusi sivellin… New Brush Uusi sivellin @@ -4561,6 +4562,8 @@ imageTrace Outline Ääriviiva @msg select a repeat valitse toisto @msg select a stroke with a variable width valitse viiva, jolla on vaihteleva leveys @msg select a symbol instance valitse symboli-ilmentymä +@msg select instances of one symbol valitse yhden symbolin ilmentymiä +@msg a symbol can't hold an instance of itself symboli ei voi sisältää omaa ilmentymäänsä @msg select an Image Trace object valitse kuvan jäljitys -objekti @msg could not decode image: {0} kuvaa ei voitu purkaa: {0} @msg image is empty kuva on tyhjä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 523c06bb54..737acaf423 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -928,6 +928,7 @@ font-technology Variable Variables Edit Selection Modifier la sélection Edit Selection… Modifier la sélection… Edit Symbol Modifier le symbole + Exit Symbol Editing Mode Quitter le mode Modification de symbole Edit Text Modifier le texte Edit the applied effect, or add another one? Modifier l’effet appliqué ou en ajouter un autre ? Edit the point Modifier le point @@ -4343,6 +4344,8 @@ axis Both Les deux @msg a clipping path can't be attached to a path un tracé d’écrêtage ne peut pas être attaché à un tracé @msg select a stroke with a variable width sélectionnez un contour de largeur variable @msg select a symbol instance sélectionnez une instance de symbole +@msg select instances of one symbol sélectionnez des instances d’un seul symbole +@msg a symbol can't hold an instance of itself un symbole ne peut pas contenir une instance de lui-même @msg select an Image Trace object sélectionnez un objet de vectorisation de l’image @msg could not decode image: {0} impossible de décoder l’image : {0} @msg image is empty l’image est vide diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index af31ed39cb..9c7cc7f8fc 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1193,6 +1193,7 @@ font-technology Variable Változó Edit Selection Kijelölés szerkesztése Edit Selection… Kijelölés szerkesztése… Edit Symbol Szimbólum szerkesztése + Exit Symbol Editing Mode Kilépés a szimbólumszerkesztési módból Edit Text Szöveg szerkesztése Edit the applied effect, or add another one? Szerkeszted az alkalmazott effektust, vagy újat adsz hozzá? Edit the point Pont szerkesztése @@ -5076,6 +5077,8 @@ imageTrace Outline Körvonal @msg a clipping path can't be attached to a path vágóútvonal nem csatolható útvonalhoz @msg select a stroke with a variable width jelölj ki egy változó szélességű körvonalat @msg select a symbol instance jelölj ki egy szimbólumpéldányt +@msg select instances of one symbol egyetlen szimbólum példányait jelöld ki +@msg a symbol can't hold an instance of itself egy szimbólum nem tartalmazhatja a saját példányát @msg select an envelope jelölj ki egy burkolót @msg select an image jelölj ki egy képet @msg select an Image Trace object jelölj ki egy képvektorizálási objektumot diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index a15105ef92..8cd5905e90 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2872,6 +2872,7 @@ theme Appearance Tampilan Duplicate Brush Duplikatkan kuas Duplicate Symbol Duplikatkan simbol Edit Symbol Edit simbol + Exit Symbol Editing Mode Keluar dari mode edit simbol Expand Brush Strokes Perluas guratan kuas New Brush… Kuas baru… New Brush Kuas baru @@ -4323,6 +4324,8 @@ imageTrace Outline Kontur @msg select a repeat pilih pengulangan @msg select a stroke with a variable width pilih goresan dengan lebar variabel @msg select a symbol instance pilih instans simbol +@msg select instances of one symbol pilih instans dari satu simbol saja +@msg a symbol can't hold an instance of itself simbol tidak dapat memuat instans dirinya sendiri @msg select an Image Trace object pilih objek Image Trace @msg could not decode image: {0} tidak dapat mendekode gambar: {0} @msg image is empty gambar kosong diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index e94ffaf0b1..aa17ab6748 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -925,6 +925,7 @@ font-technology Variable Variabili Edit Selection Modifica selezione Edit Selection… Modifica selezione… Edit Symbol Modifica simbolo + Exit Symbol Editing Mode Esci dalla modalità modifica simbolo Edit Text Modifica testo Edit the applied effect, or add another one? Modificare l'effetto applicato o aggiungerne un altro? Edit the point Modifica il punto @@ -4394,6 +4395,8 @@ axis Both Entrambi @msg a clipping path can't be attached to a path un tracciato di ritaglio non può essere agganciato a un tracciato @msg select a stroke with a variable width seleziona una traccia con larghezza variabile @msg select a symbol instance seleziona un'istanza di simbolo +@msg select instances of one symbol seleziona istanze di un solo simbolo +@msg a symbol can't hold an instance of itself un simbolo non può contenere un'istanza di sé stesso @msg select an Image Trace object seleziona un oggetto di ricalco immagine @msg could not decode image: {0} impossibile decodificare l'immagine: {0} @msg image is empty l'immagine è vuota diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 902df6a9dd..62f6526f54 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1440,6 +1440,7 @@ digits Malayalam マラヤーラム数字 Edit PDF Preset PDF プリセットを編集 Edit Print Preset プリントプリセットを編集 Edit Symbol シンボルを編集 + Exit Symbol Editing Mode シンボル編集モードを終了 Edit Theme テーマを編集 Edit selected paths within: 選択したパスを次の距離以内で編集: Edit or Apply Color Group カラーグループを編集または適用 @@ -4034,6 +4035,8 @@ swatch Bright Violet ビビッドバイオレット @msg brushes move only within their type ブラシは同じ種類の中でのみ移動できます @msg no symbol instances selected シンボルインスタンスが選択されていません @msg select a symbol instance シンボルインスタンスを選択してください +@msg select instances of one symbol 1 つのシンボルのインスタンスを選択してください +@msg a symbol can't hold an instance of itself シンボルにそれ自体のインスタンスを含めることはできません @msg the art has no bounds アートに境界がありません @msg Image Trace: the traced image is missing 画像トレース: トレース元の画像が見つかりません @msg Live Paint Merge: select a Live Paint group and the paths to add ライブペイントの結合: ライブペイントグループと、追加するパスを選択してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d6dcb9e033..c8cc2bd053 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2685,6 +2685,7 @@ theme Appearance იერსახე Duplicate Brush ფუნჯის დუბლირება Duplicate Symbol სიმბოლოს დუბლირება Edit Symbol სიმბოლოს რედაქტირება + Exit Symbol Editing Mode სიმბოლოს რედაქტირების რეჟიმიდან გამოსვლა Expand Brush Strokes ფუნჯის შტრიხების გაშლა New Brush… ახალი ფუნჯი… New Brush ახალი ფუნჯი @@ -4108,6 +4109,8 @@ font-technology Variable ცვლადი @msg select a repeat მონიშნეთ გამეორება @msg select a stroke with a variable width მონიშნეთ ცვლადი სიგანის კონტური @msg select a symbol instance მონიშნეთ სიმბოლოს ეგზემპლარი +@msg select instances of one symbol მონიშნეთ ერთი სიმბოლოს ეგზემპლარები +@msg a symbol can't hold an instance of itself სიმბოლო ვერ შეიცავს საკუთარ ეგზემპლარს @msg select an Image Trace object მონიშნეთ გამოსახულების ვექტორიზაციის ობიექტი @msg could not decode image: {0} გამოსახულების დეკოდირება ვერ მოხერხდა: {0} @msg image is empty გამოსახულება ცარიელია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e2da7c92af..e38285e6d6 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1430,6 +1430,7 @@ digits Malayalam 말라얄람어 Edit PDF Preset PDF 프리셋 편집 Edit Print Preset 인쇄 프리셋 편집 Edit Symbol 심볼 편집 + Exit Symbol Editing Mode 심볼 편집 모드 종료 Edit Theme 테마 편집 Edit selected paths within: 다음 범위 안의 선택한 패스 편집: Edit or Apply Color Group 색상 그룹 편집 또는 적용 @@ -3961,6 +3962,8 @@ theme Appearance 외관 @msg brushes move only within their type 브러시는 같은 유형 안에서만 이동할 수 있습니다 @msg no symbol instances selected 선택한 심볼 인스턴스가 없습니다 @msg select a symbol instance 심볼 인스턴스를 선택하세요 +@msg select instances of one symbol 한 심볼의 인스턴스를 선택하세요 +@msg a symbol can't hold an instance of itself 심볼에는 자기 자신의 인스턴스를 넣을 수 없습니다 @msg the art has no bounds 아트웍에 경계가 없습니다 @msg Image Trace: the traced image is missing 이미지 추적: 추적한 이미지가 없습니다 @msg Live Paint Merge: select a Live Paint group and the paths to add 라이브 페인트 병합: 라이브 페인트 그룹과 추가할 패스를 선택하세요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 9d3d2c7c80..02694f7157 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2886,6 +2886,7 @@ theme Appearance Vormgeving Duplicate Brush Kwast dupliceren Duplicate Symbol Symbool dupliceren Edit Symbol Symbool bewerken + Exit Symbol Editing Mode Symboolbewerkingsmodus verlaten Expand Brush Strokes Penseelstreken omzetten New Brush… Nieuw penseel… New Brush Nieuw penseel @@ -4335,6 +4336,8 @@ imageTrace Outline Contour @msg select a repeat selecteer een herhaling @msg select a stroke with a variable width selecteer een lijn met een variabele breedte @msg select a symbol instance selecteer een symboolinstantie +@msg select instances of one symbol selecteer instanties van één symbool +@msg a symbol can't hold an instance of itself een symbool kan geen instantie van zichzelf bevatten @msg select an Image Trace object selecteer een Image Trace-object @msg could not decode image: {0} afbeelding kon niet worden gedecodeerd: {0} @msg image is empty afbeelding is leeg diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 24c3685b3b..a40dc3bf74 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2998,6 +2998,7 @@ theme Appearance Wygląd Duplicate Brush Powiel pędzel Duplicate Symbol Powiel symbol Edit Symbol Edytuj symbol + Exit Symbol Editing Mode Wyjdź z trybu edycji symbolu Expand Brush Strokes Rozszerz pociągnięcia pędzla New Brush… Nowy pędzel… New Brush Nowy pędzel @@ -4484,6 +4485,8 @@ imageTrace Outline Kontur @msg a clipping path can't be attached to a path ścieżki przycinającej nie można dołączyć do ścieżki @msg select a stroke with a variable width zaznacz obrys o zmiennej szerokości @msg select a symbol instance zaznacz wystąpienie symbolu +@msg select instances of one symbol zaznacz wystąpienia jednego symbolu +@msg a symbol can't hold an instance of itself symbol nie może zawierać wystąpienia samego siebie @msg select an Image Trace object zaznacz obiekt obrysu obrazu @msg could not decode image: {0} nie udało się zdekodować obrazu: {0} @msg image is empty obraz jest pusty diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 152cb4b41b..fff027e8bf 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -815,6 +815,7 @@ Edit selected paths within: Editar caminhos selecionados a menos de: Edit Selection… Editar Seleção… Edit Symbol Editar Símbolo + Exit Symbol Editing Mode Sair do Modo de Edição de Símbolo Edit Text Editar Texto Edit Theme Editar Tema Edit Views… Editar Visualizações… @@ -3925,6 +3926,8 @@ axis Both Ambos @msg a clipping path can't be attached to a path um caminho de recorte não pode ser anexado a um caminho @msg select a stroke with a variable width selecione um traço com largura variável @msg select a symbol instance selecione uma instância de símbolo +@msg select instances of one symbol selecione instâncias de um único símbolo +@msg a symbol can't hold an instance of itself um símbolo não pode conter uma instância de si mesmo @msg select an Image Trace object selecione um objeto de Vetorização de imagem @msg could not decode image: {0} não foi possível decodificar a imagem: {0} @msg image is empty a imagem está vazia diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f60e17a755..bfe567e5e7 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -923,6 +923,7 @@ font-technology Variable Вариативные Edit Selection Редактировать выделение Edit Selection… Редактировать выделение… Edit Symbol Редактировать символ + Exit Symbol Editing Mode Выйти из режима редактирования символа Edit Text Редактировать текст Edit the applied effect, or add another one? Редактировать применённый эффект или добавить другой? Edit the point Редактировать точку @@ -4389,6 +4390,8 @@ axis Both Оба @msg a clipping path can't be attached to a path контур обрезки нельзя прикрепить к контуру @msg select a stroke with a variable width выделите обводку с переменной шириной @msg select a symbol instance выделите экземпляр символа +@msg select instances of one symbol выделите экземпляры одного символа +@msg a symbol can't hold an instance of itself символ не может содержать собственный экземпляр @msg select an Image Trace object выделите объект трассировки изображения @msg could not decode image: {0} не удалось декодировать изображение: {0} @msg image is empty изображение пусто diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 91595dfa2f..96598b23bc 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -912,6 +912,7 @@ font-technology Variable Variabla Edit Selection Redigera markering Edit Selection… Redigera markering… Edit Symbol Redigera symbol + Exit Symbol Editing Mode Avsluta symbolredigeringsläge Edit Text Redigera text Edit the applied effect, or add another one? Vill du redigera den använda effekten eller lägga till en till? Edit the point Redigera punkten @@ -4252,6 +4253,8 @@ axis Both Båda @msg select a repeat markera en upprepning @msg select a stroke with a variable width markera en kontur med variabel bredd @msg select a symbol instance markera en symbolinstans +@msg select instances of one symbol markera instanser av en och samma symbol +@msg a symbol can't hold an instance of itself en symbol kan inte innehålla en instans av sig själv @msg select an Image Trace object markera ett bildspårningsobjekt @msg could not decode image: {0} kunde inte avkoda bilden: {0} @msg image is empty bilden är tom diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 18449679b8..bd09496235 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -904,6 +904,7 @@ font-technology Variable Değişken Edit Selection Seçimi Düzenle Edit Selection… Seçimi Düzenle… Edit Symbol Sembolü Düzenle + Exit Symbol Editing Mode Sembol Düzenleme Modundan Çık Edit Text Metni Düzenle Edit the applied effect, or add another one? Uygulanan efekti düzenlemek veya başka bir efekt eklemek mi istiyorsunuz? Edit the point Noktayı düzenle @@ -4105,6 +4106,8 @@ axis Both Her İkisi @msg select an Intertwine group bir Intertwine grubu seçin @msg select a stroke with a variable width değişken genişliğe sahip bir kontur seçin @msg select a symbol instance bir sembol örneği seçin +@msg select instances of one symbol tek bir sembolün örneklerini seçin +@msg a symbol can't hold an instance of itself bir sembol kendi örneğini içeremez @msg select an Image Trace object bir Görüntü İzleme nesnesi seçin @msg could not decode image: {0} görüntünün kodu çözülemedi: {0} @msg image is empty resim boş diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index ba2ae98bc9..89f55871f0 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -919,6 +919,7 @@ font-technology Variable Варіативні Edit Selection Редагувати виділення Edit Selection… Редагувати виділення… Edit Symbol Редагувати символ + Exit Symbol Editing Mode Вийти з режиму редагування символу Edit Text Редагувати текст Edit the applied effect, or add another one? Редагувати застосований ефект або додати інший? Edit the point Редагувати точку @@ -4378,6 +4379,8 @@ axis Both Обидві @msg a clipping path can't be attached to a path відсічний контур не можна прикріпити до контуру @msg select a stroke with a variable width виділіть обведення зі змінною шириною @msg select a symbol instance виділіть екземпляр символу +@msg select instances of one symbol виділіть екземпляри одного символу +@msg a symbol can't hold an instance of itself символ не може містити власний екземпляр @msg select an Image Trace object виділіть об’єкт трасування зображення @msg could not decode image: {0} не вдалося декодувати зображення: {0} @msg image is empty зображення порожнє diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index e215bb2ebf..3fbcdf3169 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1075,6 +1075,7 @@ font-technology Variable Biến thiên Edit Selection Chỉnh sửa vùng chọn Edit Selection… Chỉnh sửa vùng chọn… Edit Symbol Chỉnh sửa ký hiệu + Exit Symbol Editing Mode Thoát chế độ chỉnh sửa ký hiệu Edit Text Chỉnh sửa văn bản Edit the applied effect, or add another one? Chỉnh sửa hiệu ứng đã áp dụng, hay thêm hiệu ứng mới? Edit the point Chỉnh sửa điểm @@ -4730,6 +4731,8 @@ theme Appearance Giao diện @msg a clipping path can't be attached to a path không thể gắn đường dẫn cắt lên đường dẫn @msg select a stroke with a variable width hãy chọn nét có chiều rộng biến đổi @msg select a symbol instance hãy chọn đối tượng ký hiệu +@msg select instances of one symbol hãy chọn các đối tượng của cùng một ký hiệu +@msg a symbol can't hold an instance of itself ký hiệu không thể chứa đối tượng của chính nó @msg select an envelope hãy chọn một Envelope @msg select an image hãy chọn ảnh @msg select an Image Trace object hãy chọn đối tượng vector hóa ảnh diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index acdfaf1b1c..046fdde3c5 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -865,6 +865,7 @@ Edit selected paths within: 在以下范围内编辑所选路径: Edit Selection… 编辑所选对象… Edit Symbol 编辑符号 + Exit Symbol Editing Mode 退出符号编辑模式 Edit Text 编辑文字 Edit the applied effect, or add another one? 编辑已应用的效果,还是再添加一个? Edit the point 编辑点 @@ -3771,6 +3772,8 @@ imageTrace Outline 轮廓 @msg brushes move only within their type 画笔只能在同一类型内移动 @msg no symbol instances selected 未选择符号实例 @msg select a symbol instance 请选择一个符号实例 +@msg select instances of one symbol 请选择同一符号的实例 +@msg a symbol can't hold an instance of itself 符号不能包含自身的实例 @msg the art has no bounds 图稿没有边界 @msg Image Trace: the traced image is missing 图像描摹:缺少所描摹的图像 @msg Live Paint Merge: select a Live Paint group and the paths to add 实时上色合并:请选择一个实时上色组以及要添加的路径 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 460926d92b..f414e61b6f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -887,6 +887,7 @@ font-technology Variable 可變 Edit Selection 編輯選取範圍 Edit Selection… 編輯選取範圍… Edit Symbol 編輯符號 + Exit Symbol Editing Mode 結束符號編輯模式 Edit Text 編輯文字 Edit the applied effect, or add another one? 要編輯已套用的效果,還是新增另一個? Edit the point 編輯點 @@ -1696,6 +1697,8 @@ file-filter Templates 範本 @msg brushes move only within their type 筆刷只能在同一類型內移動 @msg no symbol instances selected 未選取符號實體 @msg select a symbol instance 請選取符號實體 +@msg select instances of one symbol 請選取同一符號的實體 +@msg a symbol can't hold an instance of itself 符號不能包含自身的實體 @msg the art has no bounds 圖稿沒有邊界 @msg Image Trace: the traced image is missing 影像描圖:找不到描圖的影像 @msg Live Paint Merge: select a Live Paint group and the paths to add 即時上色合併:請選取即時上色群組和要加入的路徑 diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 968e7a1a36..291257e972 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -184,6 +184,13 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(st) = app.session.active() else { return }; let names: Vec<String> = st.doc.symbols.iter().map(|s| s.name.clone()).collect(); let shared = symbols.first().filter(|first| symbols.iter().all(|s| s == *first)).cloned().unwrap_or_default(); + // Edit Symbol: the instances' symbol in symbol editing mode, when they share one. + if !shared.is_empty() + && widgets::icon_button(ui, "dc-place-symbol", tl!("Edit Symbol"), false, 24.0).clicked() + && let Err(e) = app.run("symbol.edit", json!({})) + { + app.status(e); + } ui.label(egui::RichText::new(tl!("Replace:")).size(12.0).color(Tokens::get(ui.ctx()).text)); let options: Vec<&str> = names.iter().map(String::as_str).collect(); if let Some(name) = widgets::dropdown_names(ui, "cb-symbol-replace", &shared, &options, 140.0).and_then(|i| names.get(i)) @@ -261,12 +268,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } - if let Some((n, place)) = clicked { + // A double-click edits the symbol in symbol editing mode. + if let Some((n, edit)) = clicked { // A click picks one symbol again. set_pstate(ui.ctx(), MARKED, (uid, Vec::<String>::new())); app.run("symbol.setCurrent", json!({"name": n})).ok(); - if place { - app.run("symbol.place", json!({"name": n})).ok(); + if edit && let Err(e) = app.run("symbol.edit", json!({"name": n})) { + app.status(e); } } let has_sel = app.session.active().is_some_and(|d| !d.selection.is_empty()); @@ -322,7 +330,8 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } let items: [(&str, bool, &str, Value); 7] = [ (tl!("Symbol Options…"), sel.is_some(), "ui.symbolOptions", json!({"edit": true, "name": sel})), - (tl!("Edit Symbol"), inst, "symbol.edit", json!({})), + // The selected instance, else the symbol selected in the panel. + (tl!("Edit Symbol"), inst || sel.is_some(), "symbol.edit", if inst { json!({}) } else { name.clone() }), (tl!("Place Symbol Instance"), sel.is_some(), "symbol.place", name.clone()), (tl!("Replace Symbol"), inst && sel.is_some(), "symbol.replace", name.clone()), (tl!("Break Link to Symbol"), inst, "symbol.breakLink", json!({})), @@ -925,6 +934,51 @@ mod tests { (instances, paths) } + /// The bounds of the art on the symbol editing layer, rounded to 0.001 pt. + fn editing_art(app: &VectorcraftApp) -> Option<[f64; 4]> { + let d = &app.session.active()?.doc; + let layer = d.node(d.symbol_edit.as_ref()?.layer)?; + let ids: Vec<NodeId> = layer.children()?.iter().map(|n| n.id).collect(); + let r = d.bounds_of(&ids, false)?; + Some([r.x0, r.y0, r.x1, r.y1].map(|v| (v * 1000.0).round() / 1000.0)) + } + + /// Edit Symbol without an instance centers the symbol's art on the active artboard, and in a + /// document without artboards on the view's center, in a batch too. + #[test] + fn edit_symbol_from_the_panel_centers_the_art_on_the_active_artboard_or_the_view() { + let mut app = leaf_and_dot(); + app.run("artboard.new", json!({"x": 500, "y": 0, "width": 200, "height": 100})).unwrap(); + app.run("select.none", json!({})).unwrap(); + crate::panels::artboards::select(&mut app, 1); + app.run("symbol.edit", json!({"name": "Dot"})).unwrap(); + assert_eq!(editing_art(&app), Some([585.0, 35.0, 615.0, 65.0])); + app.run("symbol.exitEditing", json!({})).unwrap(); + std::sync::Arc::make_mut(&mut app.session.active_mut().unwrap().doc).artboards.clear(); + // A view with no artboard to fit to is never fitted. + if let Some(v) = app.view_mut() { + (v.fitted, v.center) = (false, vectorcraft_geom::Point::new(1000.0, 1000.0)); + } + app.run("symbol.edit", json!({"name": "Dot"})).unwrap(); + assert_eq!(editing_art(&app), Some([985.0, 985.0, 1015.0, 1015.0])); + // A coordinate the call gives stays; the other is the view's. + app.run("symbol.exitEditing", json!({})).unwrap(); + app.run("symbol.edit", json!({"name": "Dot", "x": 2000})).unwrap(); + assert_eq!(editing_art(&app), Some([1985.0, 985.0, 2015.0, 1015.0])); + // A batch's symbol.edit step gets the view's center as well. + app.run("symbol.exitEditing", json!({})).unwrap(); + app.run("command.batch", json!({"commands": [{"command": "symbol.edit", "params": {"name": "Dot"}}]})).unwrap(); + assert_eq!(editing_art(&app), Some([985.0, 985.0, 1015.0, 1015.0])); + // An artboard an earlier step makes is there when the symbol.edit step runs. + app.run("symbol.exitEditing", json!({})).unwrap(); + let steps = json!([ + {"command": "artboard.new", "params": {"x": 500, "y": 0, "width": 200, "height": 100}}, + {"command": "symbol.edit", "params": {"name": "Dot"}}, + ]); + app.run("command.batch", json!({ "commands": steps })).unwrap(); + assert_eq!(editing_art(&app), Some([585.0, 35.0, 615.0, 65.0])); + } + fn dialog_kind(app: &VectorcraftApp) -> Option<&str> { app.ui.dialog.as_ref().map(|d| d.kind.as_str()) } diff --git a/docs/mcp.md b/docs/mcp.md index 322778d7ff..05f8a22fd9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1568,7 +1568,12 @@ already walks Image Trace. Short agent entry points: 9-slice guides on or off; `nineSliceGuides` is `[left, top, right, bottom]`, fractions 0..1 of the symbol size; rows of `symbol.list` carry `nineSlice`: the guides or `null`; `type` is Symbol Type, `static` by default for the command and `dynamic` by default in the Symbol Options dialog), - `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}`, `symbol.replace`, `symbol.edit`, `symbol.duplicate`, + `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}`, `symbol.replace`, + `symbol.edit {id?, name?, x?, y?, artboard?, viewCenter?}` (symbol editing mode: the symbol's art on a temporary + isolated layer, where the instance `id` shows it or centered on (x, y), by default on the center of artboard + `artboard`, the active one the app passes, or in a document without artboards on `viewCenter`, the view's center the + app passes; every instance follows each edit and stays linked), `symbol.exitEditing` + (leaves the mode; without an edit it adds no undo step), `symbol.duplicate`, `symbol.selectInstances {name}`, `symbol.delete {name | names, expandInstances?}` (`names` deletes several in one undo step). `symbol.new` and `symbol.duplicate {name, newName?}` trim the white space around the name they are given, as `symbol.options` trims `newName`; a blank one gives "New Symbol" or "<name> copy". @@ -1580,8 +1585,8 @@ already walks Image Trace. Short agent entry points: 0..100 and `blend` a blend mode name; `null` gives one back to the symbol. It is refused for a static symbol and for a path that names no object. `symbol.instance.reset {ids?}` drops the selected instances' changes (the Properties panel's Reset). Redefining the symbol (`symbol.update`) reshapes every instance and keeps each change whose path the - new art still has; `symbol.breakLink` bakes the changes into the expanded art; `symbol.edit` expands the symbol's own - art; making the symbol static drops them. + new art still has; `symbol.breakLink` bakes the changes into the expanded art; `symbol.edit` edits the symbol's own + art, and each edit there keeps the changes whose path the art still has; making the symbol static drops them. ```json {"name":"run_command","arguments":{"command":"symbol.instance.setAppearance","params":{"id":42,"path":[1],"fill":"#d0021b","opacity":80}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f29d2c013b..be374ae92f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -606,6 +606,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - macOS: Finder opens every format File › Open reads with VectorCraft (double-click, Open With, a drop on the Dock icon, `open -a`), at launch or while it runs; the release and `cargo xtask bundle` apps share one `Info.plist` that declares those document types, owning only VectorCraft's own formats. The DMG opens on a designed Finder window, VectorCraft.app beside the `Applications` link over a background with the app icon (#493). - Swatch and graphic style libraries, Libraries panel files, presets and plug-ins open wherever they are dropped on the window, as File › Open opens them. - **Symbol libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own, as swatch and graphic style libraries do. The built-in library, Basic Shapes, is original art generated in code (`crates/engine/src/cmd/symbollib.rs`). A click on a symbol adds it to the document's Symbols as one undo step, with its Symbol Options (size, registration, export type, 9-slice guides) and every resource it uses (the symbols it nests, patterns, swatches, brushes, graphic styles, images), and makes it the current symbol; a symbol the document already has is not added again and another symbol of the same name keeps its name, the library's comes in numbered. Thumbnails, in the library panels and the Symbols panel, draw a symbol with the symbols it nests and the patterns and images it uses. Dragging a library symbol onto the canvas also places an instance there, in the same step ([placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)). Save Symbols (the library menu) and Save Symbol Library… (the Symbols panel menu) write the document's symbols as a `.vectorcraft` document holding only them, into the user library folder (listed under User Defined) or a file; Other Library… reads the symbols of any document VectorCraft opens; a file it can't read is an error and opens no panel. Tests: `crates/engine/src/tests/symbollib.rs`, `crates/ui-egui/src/panels/tests_symbol_libraries.rs`, `panels::symbols::tests::thumbnails_show_the_symbols_a_symbol_nests`, `canvas::tests::a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step`. + - **Symbol editing mode** ([Edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): a double-click on a symbol instance, the Control bar's Edit Symbol button, a double-click on a symbol in the Symbols panel and the panel menu's Edit Symbol (`symbol.edit`) open the symbol's art on a temporary isolated layer, where the instance shows it (from the panel: centered on the active artboard, or in the view in a document without artboards), with the rest of the document dimmed. Each edit there changes every instance at once; the instances keep their own transforms and stay linked (Break Link to Symbol still expands one), and a dynamic symbol's instances keep their appearance changes to the objects the art still has. Escape, the isolation bar's back button, the Control bar's Exit Symbol Editing Mode and a double-click outside the art leave the mode (`symbol.exitEditing`); leaving without an edit adds no undo step. Saving leaves the editing layer out. Tests: `crates/engine/src/tests/symboledit.rs`, `select::tests::a_double_click_on_a_symbol_instance_edits_its_symbol`, `panels::symbols::tests::edit_symbol_from_the_panel_centers_the_art_on_the_active_artboard_or_the_view`. - **Delete Symbol asks first** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Alt-click Delete](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): the Symbols panel's Delete Symbol button and menu item ask "Delete the selected symbol?" with Yes and No for a symbol no instance uses. For a symbol with placed instances they ask with Expand Instances (the instances become ordinary art), Delete Instances and Cancel; either Instances button deletes the symbol in one undo step. Alt-click on the button deletes an unused symbol without asking and still asks about one with instances. A question left open while another document became active deletes nothing. `symbol.delete` itself does not ask. Tests: `panels::symbols::tests::delete_symbol_asks_first_and_alt_click_deletes_an_unused_symbol_at_once`, `the_in_use_question_expands_or_deletes_the_instances`, `a_stale_delete_symbol_question_deletes_nothing`, `the_delete_symbol_questions_show_their_buttons`. - **Symbols › Select All Unused** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), #4918): the Symbols panel menu's Select All Unused shows the symbols nothing places selected (`symbol.unused`): instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. Delete Symbol, the button or the menu item, then asks "Delete the selected symbols?" once and deletes those still unused in one undo step (`symbol.delete {names}`); Alt-click on the button deletes them without asking, and a click on a symbol picks just it again. Tests: `tests::brushsym::symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several`, `panels::symbols::tests::select_all_unused_picks_the_unused_symbols_and_delete_deletes_them`, `dialogs::symbol_delete::tests::several_symbols_get_the_plural_question`. - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol. A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. From 7e5e099f8e5587de4ca31d3d42ea7c12fd642524 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 1 Nov 2026 11:09:08 +0700 Subject: [PATCH 255/260] Export for Screens: a second file with a taken name is numbered instead of skipped Squashed from #5028 onto main. --- crates/engine/src/cmd/fileio.rs | 2 +- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/export_names.rs | 10 ++- crates/engine/src/cmd/fileio/screens.rs | 64 ++++++++++---- crates/engine/src/cmd/fileio/tests_screens.rs | 88 ++++++++++++++++++- docs/mcp.md | 7 +- docs/target-app-parity.md | 1 + 7 files changed, 147 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 4079b42301..fb9419052e 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -121,7 +121,7 @@ use access::{may_read, may_write}; pub use commands::specs; pub use export_names::artboard_file_names; pub(crate) use export_names::{default_name, merge, unique_file_names, with_black_output, write_or_return}; -use export_names::{distinct_names, write_encoded}; +use export_names::{distinct_names_by, write_encoded}; use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, writable}; pub use formats::{ DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, export_extensions, extension, diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 5c2374988e..f80302eee3 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export for Screens", ["File", "Export"], None, - "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)", + "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)", has_doc, screens::export_for_screens ), diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 66bd6d3954..af0e49563c 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -20,6 +20,12 @@ pub(crate) fn unique_file_names<'a>(names: impl IntoIterator<Item = (&'a str, St /// `names` with `-2`, `-3`… after a name already used (compared without case). pub(super) fn distinct_names(names: impl IntoIterator<Item = String>) -> Vec<String> { + distinct_names_by(names, str::to_lowercase) +} + +/// `names` with `-2`, `-3`… after a name already used, two names matching when `key` gives the same +/// key for them. +pub(super) fn distinct_names_by(names: impl IntoIterator<Item = String>, key: impl Fn(&str) -> String) -> Vec<String> { let mut taken = std::collections::HashSet::new(); // The next number to try for each base: a name repeated many times doesn't search the numbers // taken before it. @@ -28,8 +34,8 @@ pub(super) fn distinct_names(names: impl IntoIterator<Item = String>) -> Vec<Str .into_iter() .map(|base| { let mut name = base.clone(); - while !taken.insert(name.to_lowercase()) { - let n = next.entry(base.to_lowercase()).or_insert(1); + while !taken.insert(key(&name)) { + let n = next.entry(key(&base)).or_insert(1); *n += 1; name = format!("{base}-{n}"); } diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 966038b35e..74848038be 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -21,7 +21,7 @@ use super::encode::single_artboard; use super::export::{export_crop, isolated, selected_artwork, without_artboards}; use super::naming::{self, NameParts}; use super::{ - ARTBOARD_PARAMS, ArtboardPick, Format, artboard_file_names, create_dir, distinct_names, encode_with_warnings, merge, unique_file_names, + ARTBOARD_PARAMS, ArtboardPick, Format, artboard_file_names, create_dir, distinct_names_by, encode_with_warnings, merge, unique_file_names, with_black_output, writable, write_file, }; @@ -490,13 +490,31 @@ pub(crate) fn check_settings(s: &Session, p: &Value) -> Result<()> { rows_of(s, p, ScreenParams::of(p)?.preset.as_deref()).map(|_| ()) } +/// `name` the way a case-insensitive file system compares names: lower-cased, then each character +/// upper-cased where its upper case is one character. Names with the same lower case give the +/// same key, and so do `ΟΣ`, `ος` and `οσ` (`ΟΣ`); `ᾈ` and `ᾀ` give `ᾀ`, and `ß` stays `ß`. +fn fold(name: &str) -> String { + name.to_lowercase() + .chars() + .map(|c| { + let mut upper = c.to_uppercase(); + match (upper.next(), upper.next()) { + (Some(u), None) => u, + _ => c, + } + }) + .collect() +} + /// The file names (and bytes) an export wrote, or the files it returns. #[derive(Default)] struct Output { - /// Lower-case relative names already used, with what wrote each (two identical rows write - /// one file; different files that would share a name get `-2`, `-3`…). + /// Relative names already used, by their [`fold`]ed spelling, with what wrote each (two + /// identical rows write one file; different files that would share a name get `-2`, `-3`…). taken: std::collections::HashMap<String, String>, - /// Sub-folders already made. + /// Each sub-folder as the first file in it spells it, by its [`fold`]ed name. + folders: std::collections::HashMap<String, String>, + /// Sub-folders already made, by their [`fold`]ed names. made: HashSet<String>, /// `(relative name, bytes)` kept to return or zip (empty when written to a folder). kept: Vec<(String, Vec<u8>)>, @@ -505,12 +523,19 @@ struct Output { } impl Output { - /// The name the file `key` writes as `name` takes: `name`, else (with `number`) `name-2`, - /// `name-3`… when another file has it; `None` when the same file (`key`) was written as `name` - /// already, or, without `number`, when any file was (the first row wins, as Export for Screens - /// always did when no name pattern is given). - fn claim(&mut self, name: &str, key: &str, number: bool) -> Option<String> { - let (base, ext) = name.rsplit_once('.').map_or((name, ""), |(b, e)| (b, e)); + /// The name the file `key` writes as `name` takes: `name`, else `name-2`, `name-3`… when + /// another file has it, with or without a name pattern; `None` when the same file (`key`) was + /// written as `name` already. Names are compared without case, and a sub-folder keeps the + /// spelling of the first file put in it. + fn claim(&mut self, name: &str, key: &str) -> Option<String> { + let name = match name.rsplit_once('/') { + Some((dir, file)) => { + let dir = self.folders.entry(fold(dir)).or_insert_with(|| dir.to_string()); + format!("{dir}/{file}") + } + None => name.to_string(), + }; + let (base, ext) = name.rsplit_once('.').map_or((name.as_str(), ""), |(b, e)| (b, e)); for n in 1.. { let candidate = if n == 1 { name.to_string() @@ -519,11 +544,11 @@ impl Output { } else { format!("{base}-{n}.{ext}") }; - match self.taken.get(&candidate.to_lowercase()) { - Some(k) if k == key || !number => return None, + match self.taken.get(&fold(&candidate)) { + Some(k) if k == key => return None, Some(_) => continue, None => { - self.taken.insert(candidate.to_lowercase(), key.to_string()); + self.taken.insert(fold(&candidate), key.to_string()); return Some(candidate); } } @@ -543,7 +568,7 @@ impl Output { match folder { Some(dir) if !keep => { if let Some((sub, _)) = name.rsplit_once('/') - && self.made.insert(sub.to_lowercase()) + && self.made.insert(fold(sub)) { create_dir(&format!("{dir}/{sub}"))?; } @@ -686,8 +711,8 @@ pub(super) fn presets_delete(s: &mut Session, p: &Value) -> Result<Value> { /// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF /// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard, /// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and -/// so do different files the `name` pattern gives one name. The reply's `warnings` lists every -/// warning the encoders give for the files, each once. +/// so do different files that would share a name, with or without the `name` pattern. The reply's +/// `warnings` lists every warning the encoders give for the files, each once. pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> { let o = ScreenParams::of(p)?; let rows = rows_of(s, p, o.preset.as_deref())?; @@ -818,7 +843,7 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> }); let (sub, file) = naming.file(document.as_ref().unwrap_or(item), index, files, r); let name = sub.map_or_else(|| file.clone(), |d| format!("{d}/{file}")); - let Some(name) = out.claim(&name, &format!("{}|{}", item.stem, r.key), o.name.is_some()) else { continue }; + let Some(name) = out.claim(&name, &format!("{}|{}", item.stem, r.key)) else { continue }; let bytes = if let Some(boards) = single { let mut options = r.options.clone(); options["range"] = json!(boards.iter().map(|b| (b + 1).to_string()).collect::<Vec<_>>().join(", ")); @@ -938,8 +963,9 @@ fn items( } isolated(doc, &doc.paint_order(ids.iter().copied()), name).map(|(d, r)| (Arc::new(d), r)) }; - // Each item's stem follows Windows' file-naming rules, and no two items share one. - let safe = |stems: Vec<String>| distinct_names(stems.iter().map(|s| safe_file_name(s))); + // Each item's stem follows Windows' file-naming rules, and no two items share one, compared as + // the item folders are (`fold`). + let safe = |stems: Vec<String>| distinct_names_by(stems.iter().map(|s| safe_file_name(s)), fold); let named = |pieces: Vec<(String, Arc<Document>, Option<usize>, Rect)>, fallback: &str| -> Vec<Item> { let stems = safe(unique_file_names(pieces.iter().map(|(n, ..)| (n.as_str(), fallback.to_string())))); pieces diff --git a/crates/engine/src/cmd/fileio/tests_screens.rs b/crates/engine/src/cmd/fileio/tests_screens.rs index bb4e356259..2f9e80cfca 100644 --- a/crates/engine/src/cmd/fileio/tests_screens.rs +++ b/crates/engine/src/cmd/fileio/tests_screens.rs @@ -533,13 +533,97 @@ fn png_8_rows_write_indexed_colour() { let f = files(&r); // The IHDR colour type: 3 (indexed) for PNG 8, 6 (RGBA) for PNG; both are .png, the PNG 8 row // written first. - assert_eq!(names(&r), ["Artboard-1.png"], "the same file name: the first row wins"); - assert_eq!(f[0].1[25], 3); + assert_eq!(names(&r), ["Artboard-1.png", "Artboard-1-2.png"], "the same file name: the second row's file is numbered"); + assert_eq!((f[0].1[25], f[1].1[25]), (3, 6)); let r = export(&mut s, json!({"formats": [{"format": "png8", "suffix": "-8"}, {"format": "png"}]})); let f = files(&r); assert_eq!((f[0].1[25], f[1].1[25]), (3, 6)); } +/// Without a name pattern, a row that writes a different file under a name another row's file +/// already has gets `-2`, `-3`… as a name pattern's files do, compared without case; the first +/// file keeps its name, and two identical rows still write one file. +#[test] +fn a_second_file_with_a_taken_name_is_numbered() { + let mut s = session(1); + let px = |png: &[u8]| image::load_from_memory(png).unwrap().to_rgba8().get_pixel(1, 1).0; + let rows = json!([{"format": "png", "background": "black"}, {"format": "png", "background": "white"}, {"format": "png", "background": "black"}]); + let r = export(&mut s, json!({ "formats": rows })); + assert_eq!(names(&r), ["Artboard-1.png", "Artboard-1-2.png"]); + let f = files(&r); + assert_eq!((px(&f[0].1), px(&f[1].1)), ([0, 0, 0, 255], [255, 255, 255, 255])); + // Row folders that differ only in case are one folder, spelled as the first row spells it. + let rows = json!([{"format": "png", "folder": "Print"}, {"format": "png", "folder": "print", "scale": 2, "suffix": ""}, {"format": "svg", "folder": "PRINT"}]); + let r = export(&mut s, json!({"subfolders": true, "formats": rows})); + assert_eq!(names(&r), ["Print/Artboard-1.png", "Print/Artboard-1-2.png", "Print/Artboard-1.svg"]); + assert_eq!(size(&files(&r)[1].1), (80, 60)); +} + +/// Names and folders that differ only in case match when a letter's lower case depends on where +/// it stands: Greek `ΟΣ` lower-cases to `ος`, which a case-insensitive file system treats as `οσ`. +#[test] +fn names_that_differ_only_in_greek_sigmas_are_numbered() { + let mut s = session(2); + s.execute("artboard.setProps", &json!({"index": 0, "name": "ΟΣ"})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "name": "οσ"})).unwrap(); + let r = export(&mut s, json!({"name": "<name>", "formats": [{"format": "svg"}]})); + assert_eq!(names(&r), ["ΟΣ.svg", "οσ-2.svg"]); + let rows = json!([{"format": "png", "folder": "ΟΣ"}, {"format": "svg", "folder": "οσ"}]); + let r = export(&mut s, json!({"range": "1", "subfolders": true, "formats": rows})); + assert_eq!(names(&r), ["ΟΣ/ΟΣ.png", "ΟΣ/ΟΣ.svg"]); + // Each item still gets a folder of its own. + let r = export(&mut s, json!({"folders": "item", "formats": [{"format": "svg"}]})); + assert_eq!(names(&r), ["ΟΣ/ΟΣ.svg", "οσ-2/οσ-2.svg"]); + // Letters whose full upper case is two characters still match their other case. + s.execute("artboard.setProps", &json!({"index": 0, "name": "ᾀ"})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "name": "ᾈ"})).unwrap(); + let r = export(&mut s, json!({"name": "<name>", "formats": [{"format": "svg"}]})); + assert_eq!(names(&r), ["ᾀ.svg", "ᾈ-2.svg"]); + // So do names whose lower case is longer than the name: `İ` lower-cases to `i̇`. + s.execute("artboard.setProps", &json!({"index": 0, "name": "İ"})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "name": "i\u{307}"})).unwrap(); + let r = export(&mut s, json!({"name": "<name>", "formats": [{"format": "svg"}]})); + assert_eq!(names(&r), ["İ.svg", "i\u{307}-2.svg"]); +} + +/// A fresh folder for one test, emptied first and removed when dropped (also when an assertion +/// fails). +#[cfg(not(target_arch = "wasm32"))] +struct Folder(std::path::PathBuf); + +#[cfg(not(target_arch = "wasm32"))] +impl Folder { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir().join(format!("vc-screens-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + Self(dir) + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for Folder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// The numbered file is written beside the first one, and the reply lists both paths. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_numbered_file_is_written_into_the_first_rows_folder() { + let mut s = session(1); + let tmp = Folder::new("taken"); + let dir = &tmp.0; + let folder = dir.to_string_lossy().replace('\\', "/"); + let rows = json!([{"format": "png", "folder": "Print"}, {"format": "png", "folder": "print", "background": "white"}]); + let r = export(&mut s, json!({"folder": folder, "subfolders": true, "formats": rows})); + let written: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect(); + assert_eq!(written, [format!("{folder}/Print/Artboard-1.png"), format!("{folder}/Print/Artboard-1-2.png")]); + let entries: Vec<String> = std::fs::read_dir(dir.join("Print")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(entries.len(), 2, "{entries:?}"); + assert_eq!(std::fs::read_dir(dir).unwrap().count(), 1, "one sub-folder"); +} + #[test] fn format_settings_apply_to_their_rows_and_rows_win() { let mut s = session(1); diff --git a/docs/mcp.md b/docs/mcp.md index 05f8a22fd9..dcfe46e532 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4106,8 +4106,11 @@ sub-folders) replaces the rows, and `settings: {png: {…}, jpg: {…}, svg: { format its options. On every platform, `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters from a prefix, a suffix, a name pattern or an item's name become `-` in file and folder names, a folder name ends without periods or spaces, and a Windows device name (`CON`, `PRN`, `AUX`, `NUL`, `COM1` to `COM9`, `LPT1` to `LPT9`) that -is the whole name or comes before its first period gets a `-` after it (`CON-.png`). The document remembers the last -params: `document.exportSettings`. As in `document.export`, +is the whole name or comes before its first period gets a `-` after it (`CON-.png`). When a row's file would take a +name another row's file already has, compared without case (two PNG rows with different backgrounds and no suffix), +the later file is written as `-2`, `-3`… (`Artboard-1-2.png`) and listed under that name in `files`; two identical +rows write one file, and row folders that differ only in case (`Print`, `print`) are one folder, spelled as the first +row spells it. The document remembers the last params: `document.exportSettings`. As in `document.export`, the reply's `warnings` lists the notes of every file exported (an image that couldn't be decoded, type written in the fallback font…), each note once; the export still writes or returns every file. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index be374ae92f..c3273bc73b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -555,6 +555,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Export for Screens is laid out as the reference app's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Include Artboard Fill, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`. - Save for Web: Preview in Browser writes each preview's page and images to a folder of its own inside `VectorCraft Save for Web` in the system's temporary folder. A later preview, from the same app or another one running, does not overwrite an earlier one. Each preview first removes the preview folders there that are an hour old or older and, on Linux, macOS and FreeBSD, belong to the current user; it leaves other files and folders alone. The folders a preview makes there are open to their owner only on those systems. When `VectorCraft Save for Web` is a link or is not a folder, or on those systems belongs to another user or can be written by other users, the preview goes to a new folder of its own in the temporary folder, which a later preview removes once it is an hour old (`file.saveForWeb.browser`). - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). + - Export for Screens numbers distinct row files whose names collide, compared without case, as `-2`, `-3`… instead of leaving them out; identical rows still write one file. It puts row folders that differ only in case into one folder (`document.exportForScreens`). - Variables (data merge): text, visibility and image variables bound to objects (an object may carry several), dataset rows applied in one undo step (`variable.*`, `dataset.*`) from a Variables panel and Window › Variables, with dialogs to define, bind and edit, Make Text/Visibility/Image Dynamic, Capture/Update Data Set, CSV import/export (`dataset.import` / `dataset.export`), and a row in italics when an edit leaves the art not matching it; an image dataset value is a file path and apply keeps the object's bounds; bindings let go of deleted art and locked art is left alone; every command, like the rest, is drivable over MCP and the CLI. - Variables: Import Data Sets… (`dataset.import`) reads tab-separated files as well as comma-separated ones, and files without a `name` column, whose rows take the first free names Data Set 1, Data Set 2 and so on. An import error about a row's values or name gives the file line the row starts on. - Variables: Import Data Sets… (`dataset.import`) defines the variables a file's header names that the document lacks, unbound. `#Shown` defines a visibility variable, `@Photo` defines an image variable, and a header without a prefix defines a text variable. A header that is a variable's exact name keeps naming it, and any other `%` header (graph data files) is refused. From 38bb213917be0628a85ab99adc5f3c9013b0ae06 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 31 Oct 2026 19:07:57 -0700 Subject: [PATCH 256/260] PDF export: a Perceptual gradient that mixes spot and process inks keeps its inks A Perceptual linear or radial gradient that mixes spot colors with each other or with CMYK or gray stops was written as an image in process colors. It is now written as a DeviceN shading of its inks, with the stops on its Perceptual curve: at each one, the inks of the two stops on either side are mixed at the weight where the two colors mixed in display RGB have the OKLab lightness of the color on the curve. - Gradient::ink_mixes gives the curve's stops as weights between stops, under the same 4,096-stop limit as ink_tints. - Perceptual gradients that mix a spot color with RGB or Lab stops, dithered fills and freeform gradients stay images, and the warning now names those cases. --- crates/color/src/gradient.rs | 81 ++++++++++++++++++++----- crates/color/src/gradient/tests.rs | 37 +++++++++++ crates/engine/src/cmd/gradient.rs | 2 +- crates/engine/src/tests/linked_stops.rs | 32 +++++++++- crates/pdf/src/export/nodes.rs | 4 +- crates/pdf/src/export/paint.rs | 51 +++++++++++++--- docs/target-app-parity.md | 2 +- 7 files changed, 180 insertions(+), 29 deletions(-) diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index bde5fc8099..e44b0be9ea 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -108,6 +108,30 @@ fn perceptual_steps(a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out: } } +/// The mix positions (`v`, 0..1) of the stops a Perceptual gradient's curve has between stops `a` +/// and `b`, in order: [`perceptual_steps`] on either side of the midpoint, and the midpoint (½). +fn perceptual_mixes(a: &GradientStop, b: &GradientStop) -> Vec<f32> { + let mut vs = Vec::new(); + perceptual_steps(&a.color, &b.color, (0.0, 0.5), 1, &mut vs); + vs.push(0.5); + perceptual_steps(&a.color, &b.color, (0.5, 1.0), 1, &mut vs); + vs +} + +/// The offset of mix position `v` between stops `a` and `b`, placed through `a`'s midpoint +/// (`v` = ½ at the midpoint) as [`Gradient::sample`] maps it. +fn curve_offset(a: &GradientStop, b: &GradientStop, v: f32) -> f32 { + let m = a.midpoint.clamp(0.01, 0.99); + let u = if v == 0.5 { + a.midpoint + } else if v < 0.5 { + 2.0 * v * m + } else { + m + (v - 0.5) * 2.0 * (1.0 - m) + }; + a.offset + (b.offset - a.offset) * u +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GradientStop { /// 0..=1 along the gradient. @@ -270,21 +294,9 @@ impl Gradient { // Perceptual: stops along the mix (`v`) where a straight line would stray from it, the // midpoint (v = ½) among them, placed through the midpoint as [`Self::sample`] maps them. let perceptual = next.filter(|_| !self.method.is_classic()).map(|n| { - let mut vs = Vec::new(); - perceptual_steps(&s.color, &n.color, (0.0, 0.5), 1, &mut vs); - vs.push(0.5); - perceptual_steps(&s.color, &n.color, (0.5, 1.0), 1, &mut vs); - let m = s.midpoint.clamp(0.01, 0.99); - vs.into_iter().map(move |v| { + perceptual_mixes(s, n).into_iter().map(move |v| { let mid = v == 0.5; - let u = if mid { - s.midpoint - } else if v < 0.5 { - 2.0 * v * m - } else { - m + (v - 0.5) * 2.0 * (1.0 - m) - }; - let t = s.offset + (n.offset - s.offset) * u; + let t = curve_offset(s, n, v); let o = s.opacity + (n.opacity - s.opacity) * v; (t, self.method.mix(&s.color, &n.color, v), o, (mid && off_centre).then_some(s.midpoint)) }) @@ -329,6 +341,47 @@ impl Gradient { pub fn fits_ink_tints(&self) -> bool { self.expanded().nth(MAX_INK_TINTS).is_none() } + /// A Perceptual gradient's curve ([`Self::expanded_stops`]) as mixes of its stops' inks: + /// (offset, `i`, weight, opacity) at each stop on it, where the inks there are those of stop + /// `i` and stop `i + 1` mixed linearly at the weight (0..1; 0 on the gradient's own stops). + /// The weight is the one at which the two stops' colors mixed in display RGB have the OKLab + /// lightness of the color on the curve there, found to [`TINT_STEPS`] halvings, or the mix + /// position itself when the two colors' lightness differs by less than + /// [`MIN_INK_LIGHTNESS_SPAN`]. `None` for a Classic gradient, and when the curve has more than + /// [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]). + pub fn ink_mixes(&self) -> Option<Vec<(f32, usize, f32, f32)>> { + use crate::libraries::srgb_to_oklab; + if self.method.is_classic() || !self.fits_ink_tints() { + return None; + } + let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0]; + let mut out = Vec::new(); + for (i, s) in self.stops.iter().enumerate() { + out.push((s.offset, i, 0.0, s.opacity)); + let Some(n) = self.stops.get(i + 1) else { continue }; + let (l0, l1) = (lightness(&s.color), lightness(&n.color)); + for v in perceptual_mixes(s, n) { + let weight = if (l1 - l0).abs() < MIN_INK_LIGHTNESS_SPAN { + v + } else { + let want = lightness(&self.method.mix(&s.color, &n.color, v)); + let (mut lo, mut hi) = (0.0f32, 1.0f32); + for _ in 0..TINT_STEPS { + let mid = (lo + hi) / 2.0; + // The mix at `mid` has not yet gone from stop `i`'s lightness to the wanted one. + if (lightness(&GradientMethod::Classic.mix(&s.color, &n.color, mid)) - want) * (l1 - l0) < 0.0 { + lo = mid; + } else { + hi = mid; + } + } + (lo + hi) / 2.0 + }; + out.push((curve_offset(s, n, v), i, weight, s.opacity + (n.opacity - s.opacity) * v)); + } + } + Some(out) + } /// The same ramp the other way round: the stops in reverse order at mirrored offsets, each /// segment's midpoint mirrored with it. pub fn reverse(&mut self) { diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index c2d7d23d74..ab195b347c 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -486,3 +486,40 @@ fn ink_tints_follow_the_perceptual_curve() { assert_eq!(g.ink_tints(&ink), None); assert!(!g.fits_ink_tints()); } + +/// A Perceptual gradient's curve as mixes of its stops' inks: the stops on the curve at their +/// offsets, each weighted so the two stops' colors mixed in display RGB have the lightness of +/// the color on the curve there. +#[test] +fn ink_mixes_follow_the_perceptual_curve() { + use crate::libraries::srgb_to_oklab; + let (magenta, yellow) = (Color::cmyk(0.0, 1.0, 0.0, 0.0), Color::cmyk(0.0, 0.0, 0.6, 0.0)); + let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, magenta), GradientStop::new(1.0, yellow)]); + g.stops[0].midpoint = 0.3; + assert_eq!(g.ink_mixes(), None, "a Classic gradient"); + g.method = GradientMethod::Perceptual; + let mixes = g.ink_mixes().expect("a Perceptual gradient's curve"); + let curve = g.expanded_stops(); + assert_eq!(mixes.len(), curve.len(), "a mix for each stop on the curve"); + assert_eq!((mixes[0], mixes[mixes.len() - 1]), ((0.0, 0, 0.0, 1.0), (1.0, 1, 0.0, 1.0)), "the gradient's own stops"); + let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0]; + for ((t, i, w, _), (ct, c, _)) in mixes.iter().zip(&curve) { + assert!((t - ct).abs() < 1e-6, "{t} on the curve at {ct}"); + if *i == 0 && *t > 0.0 { + let mixed = GradientMethod::Classic.mix(&magenta, &yellow, *w); + assert!((lightness(&mixed) - lightness(c)).abs() < 1e-3, "at {t}: weight {w}"); + } + } + let mid = mixes.iter().find(|m| (m.0 - 0.3).abs() < 1e-6).expect("the midpoint"); + assert!((mid.2 - 0.5).abs() > 0.01, "not halfway at the midpoint: {mid:?}"); + assert!(mixes.windows(2).all(|w| w[0].0 <= w[1].0), "in order: {mixes:?}"); + // Two colors of one lightness: the weights are the mix positions. + g.stops[1].color = magenta; + let mixes = g.ink_mixes().expect("the curve"); + let mid = mixes.iter().find(|m| (m.0 - 0.3).abs() < 1e-6).expect("the midpoint"); + assert!((mid.2 - 0.5).abs() < 1e-6, "{mid:?}"); + // More stops on the curve than MAX_INK_TINTS: no mixes. + let n = MAX_INK_TINTS + 1; + g.stops = (0..n).map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { magenta } else { Color::WHITE })).collect(); + assert_eq!(g.ink_mixes(), None); +} diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index ccaf3eeee0..b506c18f83 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even, which SVG and PDF exports draw as an image, except that PDF writes one made of tints of one spot color in that ink; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even, which SVG and PDF exports draw as an image, except that PDF writes one with spot color stops in its inks when every other stop is paper white, CMYK or gray; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", has_doc, edit_gradient ), diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index 5adffe77cf..666d317fe3 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -236,11 +236,39 @@ fn perceptual_spot_gradients_export_as_separation_shadings() { assert!(pdf.contains("/C0[1]") && pdf.contains("/C1[0.4"), "white ink at 100% to 40%: {}", &pdf[at..(at + 200).min(pdf.len())]); } +#[test] +fn perceptual_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() { + let (mut s, _) = setup(); + run(&mut s, "swatch.new", json!({"name": "Leaf", "color": {"c": 1, "m": 0, "y": 1, "k": 0}, "spot": true})); + let ink_to_cyan = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": {"c": 1, "m": 0, "y": 0, "k": 0}}]}); + let ink_to_leaf = json!({"stops": [{"offset": 0, "swatch": "Ink", "midpoint": 30}, {"offset": 1, "swatch": "Leaf", "tint": 50}]}); + for (what, edit, space) in [ + ("Ink → cyan", with(ink_to_cyan.clone(), json!({"method": "perceptual"})), "/DeviceN[/Cyan/Ink]/DeviceCMYK"), + ("Ink → Leaf 50 %", with(ink_to_leaf, json!({"method": "perceptual"})), "/DeviceN[/Ink/Leaf]/DeviceCMYK"), + ] { + run(&mut s, "paint.editGradient", edit); + let (pdf, warnings) = pdf_of(&s); + assert!(!pdf.contains("/Subtype/Image"), "{what}: no image"); + assert!(pdf.contains("/ShadingType 2") && pdf.contains(space), "{what}: a DeviceN shading"); + // The curve's stops: a stitching function of more than the two ends. + assert!(pdf.contains("/FunctionType 3"), "{what}: inks on the curve"); + assert!(!warnings.iter().any(|w| w.contains("spot")), "{what}: {warnings:?}"); + } + // The curve starts at the first stop's inks: no cyan, Ink at 100 %. + run(&mut s, "paint.editGradient", with(ink_to_cyan.clone(), json!({"method": "perceptual"}))); + let (pdf, _) = pdf_of(&s); + assert!(pdf.contains("/C0[0 1]"), "the first stop's inks"); + // A radial one too. + run(&mut s, "paint.editGradient", with(ink_to_cyan, json!({"method": "perceptual", "kind": "radial"}))); + let (pdf, _) = pdf_of(&s); + assert!(!pdf.contains("/Subtype/Image") && pdf.contains("/ShadingType 3") && pdf.contains("/DeviceN[/Cyan/Ink]/DeviceCMYK"), "radial"); +} + #[test] fn spot_gradients_drawn_as_images_warn() { let (mut s, _) = setup(); let spot_warning = |w: &[String]| w.iter().any(|w| w.contains("spot colors in gradients exported as images")); - let ink_to_cyan = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": {"c": 1, "m": 0, "y": 0, "k": 0}}]}); + let ink_to_green = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#00ff00"}]}); // More stops than the export finds tints for: an image, as before. let n = 4097; let stops: Vec<Value> = (0..n) @@ -250,7 +278,7 @@ fn spot_gradients_drawn_as_images_warn() { }) .collect(); for (what, edit) in [ - ("Perceptual Ink → cyan", with(ink_to_cyan, json!({"method": "perceptual"}))), + ("Perceptual Ink → RGB green", with(ink_to_green, json!({"method": "perceptual"}))), ("dithered Classic Ink → paper", with(ink_to_white(100.0), json!({"dither": true, "method": "classic"}))), ("dithered Perceptual Ink → paper", with(ink_to_white(100.0), json!({"dither": true, "method": "perceptual"}))), ("Perceptual Ink and paper, 4,097 stops", json!({"stops": stops, "dither": false, "method": "perceptual"})), diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 5dc0a73af7..8367bef11d 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -348,8 +348,8 @@ impl Exporter<'_> { /// Is `p` a paint PDF has no paint for when it paints a fill (`fill`) or a stroke, which /// [`Self::area`] draws as art: a pattern swatch or a gradient drawn as pixels - /// ([`vectorcraft_color::GradientPaint::draws_as_pixels`]), but not a Perceptual one of tints - /// of one spot ink ([`Self::perceptual_spot`])? + /// ([`vectorcraft_color::GradientPaint::draws_as_pixels`]), but not a Perceptual one of spot + /// inks ([`Self::perceptual_spot`])? pub(super) fn area_paint(&self, p: &Paint, fill: bool) -> bool { match p { Paint::Pattern { pattern, .. } => self.doc.pattern(pattern).is_some(), diff --git a/crates/pdf/src/export/paint.rs b/crates/pdf/src/export/paint.rs index dc2b3b5500..665efe272d 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -100,9 +100,10 @@ impl Exporter<'_> { /// The stops of a gradient that mixes spot inks with process colors or with each other, in /// a DeviceN space of the process inks the stops use (in CMYK order) and the spot inks (in /// the order the stops name them), with midpoints as explicit stops (the tints and opacity - /// there are halfway). Paper white adds no ink. `None`, with a warning, when a stop is - /// written in RGB or Lab or the spot inks can't share a DeviceN space; the gradient is then - /// written in the colors of its stops. + /// there are halfway), or for a Perceptual gradient the stops on its curve + /// ([`vectorcraft_color::Gradient::ink_mixes`]). Paper white adds no ink. `None`, with a + /// warning, when a stop is written in RGB or Lab or the spot inks can't share a DeviceN space; + /// the gradient is then written in the colors of its stops. fn device_n_stops(&mut self, g: &vectorcraft_color::Gradient) -> Option<Vec<(f32, krilla::color::Color, f32)>> { use krilla::color::device_n::{Color as DnColor, Colorant, DeviceNSpace, Process}; let paper = |c: &Color| c.to_rgba8(1.0)[..3] == [255; 3]; @@ -151,6 +152,17 @@ impl Exporter<'_> { let tints = process.iter().map(|&i| q(v[i])).chain(v[4..].iter().map(|&t| q(t))).collect(); Some(DnColor::new(tints, space.clone())?.into()) }; + // A Perceptual gradient: the stops on its curve, each a mix of two stops' inks. + if let Some(curve) = g.ink_mixes() { + return curve + .into_iter() + .map(|(o, i, w, opacity)| { + let next = inks.get(i + 1).unwrap_or(&inks[i]); + let mixed: Vec<f32> = inks[i].iter().zip(next).map(|(a, b)| a + (b - a) * w).collect(); + Some((o, color(&mixed)?, opacity)) + }) + .collect(); + } let mut out = vec![]; for (i, s) in g.stops.iter().enumerate() { out.push((s.offset, color(&inks[i])?, s.opacity)); @@ -345,13 +357,32 @@ impl Exporter<'_> { g.stops.iter().all(|s| spot(s) == Some(ink) || paper(s)).then_some(ink) } - /// Is `g` a Perceptual linear or radial gradient of tints of one spot ink that paints a fill - /// (`fill`) without dither or a stroke, with a curve short enough for - /// [`vectorcraft_color::Gradient::fits_ink_tints`], which [`Self::perceptual_spot_stops`] - /// writes as a Separation shading rather than an image? + /// Can every stop of `g` be inks of a DeviceN space ([`Self::device_n_stops`]): is a stop + /// linked to a spot swatch, and is every other stop paper white, unlinked, or written in CMYK + /// or gray? + fn device_n_inks_only(&self, g: &vectorcraft_color::Gradient) -> bool { + let doc = self.doc; + let cmyk_doc = doc.color_mode == vectorcraft_doc::ColorMode::Cmyk; + let spot = |s: &vectorcraft_color::GradientStop| s.swatch.as_deref().is_some_and(|n| doc.swatch(n).is_some_and(|w| w.spot)); + let inks = |s: &vectorcraft_color::GradientStop| { + (s.swatch.is_none() && s.color.to_rgba8(1.0)[..3] == [255; 3]) + || matches!(self.out.color(&s.color, self.intent, cmyk_doc, self.convert), Color::Cmyk { .. } | Color::Gray { .. }) + }; + g.stops.iter().any(spot) && g.stops.iter().all(|s| spot(s) || inks(s)) + } + + /// Is `g` a Perceptual linear or radial gradient of spot inks, alone or mixed with process + /// inks, that paints a fill (`fill`) without dither or a stroke, with a curve short enough for + /// [`vectorcraft_color::Gradient::fits_ink_tints`]: one that [`Self::perceptual_spot_stops`] + /// writes as a Separation shading, or [`Self::device_n_stops`] as a DeviceN shading, rather + /// than an image? pub(super) fn perceptual_spot(&self, g: &vectorcraft_color::GradientPaint, fill: bool) -> bool { let gr = &g.gradient; - !gr.method.is_classic() && gr.kind != GradientKind::Freeform && !(fill && gr.dither) && self.one_spot_ink(gr).is_some() && gr.fits_ink_tints() + !gr.method.is_classic() + && gr.kind != GradientKind::Freeform + && !(fill && gr.dither) + && (self.one_spot_ink(gr).is_some() || self.device_n_inks_only(gr)) + && gr.fits_ink_tints() } /// The stops of a Perceptual gradient of tints of one spot ink (or paper white, 0% of it) as @@ -376,7 +407,9 @@ impl Exporter<'_> { let doc = self.doc; let from_stops = g.gradient.kind != GradientKind::Freeform || g.freeform.is_none(); if from_stops && g.gradient.stops.iter().any(|s| s.swatch.as_deref().is_some_and(|n| doc.swatch(n).is_some_and(|w| w.spot))) { - self.warn("spot colors in gradients exported as images (freeform, dithered or Perceptual gradients that mix inks) are written in process colors"); + self.warn( + "spot colors in gradients exported as images (freeform or dithered gradients, and Perceptual ones with RGB or Lab stops or too many stops) are written in process colors", + ); } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c3273bc73b..9bfa5a1af3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1278,7 +1278,7 @@ applies to fills). Tests: `color::gradient::tests` (perceptual midpoint, expansi `pdf::tests::dithered_perceptual_gradients_export_as_images_with_noise_on_the_fill` and the Gradient panel's `the_method_menu_makes_the_gradient_perceptual`. Scores and hours unchanged. -PDF export writes a Perceptual linear or radial gradient whose stops are tints of one spot color (and paper white) as a Separation shading in that ink instead of an image, so the ink keeps its plate ([swatches](https://helpx.adobe.com/illustrator/using/using-creating-swatches.html): "Gradient colors can be assigned as CMYK process colors, RGB colors, or a Spot color."; [separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html): "a separate plate is created for each spot color"). Its tints follow the curve's stops, each the tint with the OKLab lightness of the color there (VectorCraft's own rule). Dithered fills, freeform gradients and Perceptual gradients that mix a spot color with other colors are still images, and the export warns that their spot colors are written in process colors. Tests: `color::gradient::tests::ink_tints_follow_the_perceptual_curve`, `engine::tests::linked_stops::perceptual_spot_gradients_export_as_separation_shadings` and `spot_gradients_drawn_as_images_warn`. +PDF export writes a Perceptual linear or radial gradient whose stops are tints of one spot color (and paper white) as a Separation shading in that ink instead of an image, so the ink keeps its plate ([swatches](https://helpx.adobe.com/illustrator/using/using-creating-swatches.html): "Gradient colors can be assigned as CMYK process colors, RGB colors, or a Spot color."; [separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html): "a separate plate is created for each spot color"). Its tints follow the curve's stops, each the tint with the OKLab lightness of the color there (VectorCraft's own rule). A Perceptual gradient that mixes spot colors with each other or with CMYK or gray stops is written as a DeviceN shading of its inks: at each stop on the curve, the inks of the two stops on either side are mixed at the weight where the two colors mixed in display RGB have the OKLab lightness of the color there (VectorCraft's own rule). Dithered fills, freeform gradients and Perceptual gradients that mix a spot color with RGB or Lab stops are still images, and the export warns that their spot colors are written in process colors. Tests: `color::gradient::tests::ink_tints_follow_the_perceptual_curve` and `ink_mixes_follow_the_perceptual_curve`, `engine::tests::linked_stops::perceptual_spot_gradients_export_as_separation_shadings`, `perceptual_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings` and `spot_gradients_drawn_as_images_warn`. ## Artwork Cleanup add-on (2026-10-30) From c101576df3ea962e6f0bf950d96bbb0a569ebfcc Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sun, 1 Nov 2026 05:30:27 +0300 Subject: [PATCH 257/260] Fix #4920: one file per copy Each copy is saved with images embedded and artboards together, so a document last saved with linked SVG images writes no image files beside its copy; any other file a save reports is reserved for the copies still to come. --- crates/engine/src/cmd/addons/document.rs | 16 +++++++++++-- .../engine/src/cmd/addons/document/tests.rs | 23 +++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index faa02efc26..04609d3e6a 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export All Open Documents", ["Object", "Plug-ins", "Document Tools"], None, - "{folder, format?: vectorcraft|pdf|svg|svgz|ai|eps (default: pdf)} write a copy of every open document, in tab order, to `folder` as File › Save a Copy writes it, each named after its document (<name>.<ext>; -2, -3… added when that name is taken, so no file is replaced): every document keeps its path, title and modified state, and no undo step is made. A document that can't be written is listed in `failed` and the others are still written; the active document stays active → {files: [{title, path, warnings}], failed: [{title, error}], format}", + "{folder, format?: vectorcraft|pdf|svg|svgz|ai|eps (default: pdf)} write a copy of every open document, in tab order, to `folder` as File › Save a Copy writes it, each named after its document (<name>.<ext>; -2, -3… added when that name is taken, so no file is replaced), one file each (images embedded, artboards together): every document keeps its path, title and modified state, and no undo step is made. A document that can't be written is listed in `failed` and the others are still written; the active document stays active → {files: [{title, path, warnings}], failed: [{title, error}], format}", has_doc, export_all_open ), @@ -117,9 +117,21 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> { failed.push(json!({ "title": title, "error": "every numbered name for the copy is taken" })); continue; }; - match fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id })) { + // One file per document: the remembered options of a document saved before in this format + // (linked SVG images, separate artboard files) would write others beside it. Each format + // reads only the options it has. + let options = json!({ "images": "embed", "separateArtboards": false }); + match fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id, "options": options })) { Ok(r) => { written.push(path.clone()); + // Any other file the save wrote is taken for the copies still to come. + for key in ["files", "linked"] { + for f in r.get(key).and_then(Value::as_array).into_iter().flatten() { + if let Some(f) = f.as_str().or_else(|| f.get("path").and_then(Value::as_str)) { + written.push(f.to_string()); + } + } + } files.push(json!({ "title": title, "path": r.get("path").cloned().unwrap_or(json!(path)), "warnings": r.get("warnings").cloned().unwrap_or(json!([])) })); } Err(e) => failed.push(json!({ "title": title, "error": e.to_string() })), diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index aef604eb36..e1b5d59bf5 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -217,3 +217,26 @@ fn export_all_open_documents_writes_each_and_reports_failures() { assert_eq!(s.active_index(), Some(0)); let _ = std::fs::remove_dir_all(&dir); } + +/// An SVG document last saved with linked images exports as one SVG with its images embedded: no +/// image file is written beside the copies (#4920 review). +#[test] +fn export_all_open_documents_writes_one_file_each() { + let dir = std::env::temp_dir().join(format!("vc-export-all-one-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("out")).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "name": "pic"})).unwrap(); + let mut png = vec![]; + image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + s.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + s.execute("document.save", &json!({"path": dir.join("pic.svg"), "format": "svg", "options": {"images": "link"}})).unwrap(); + let saved: Vec<_> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).filter(|e| e.path().is_file()).collect(); + assert!(saved.len() > 1, "the linked save wrote its image beside it: {saved:?}"); + let out = dir.join("out"); + let r = s.execute("addon.document.exportAllOpen", &json!({"folder": out, "format": "svg"})).unwrap(); + let names: Vec<String> = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(names, ["pic.svg"], "{r}"); + assert!(std::fs::read_to_string(out.join("pic.svg")).unwrap().contains("data:image/png;base64,"), "the image is embedded"); + let _ = std::fs::remove_dir_all(&dir); +} From 6d6757c929b0b6a73e9489d10d972cd8e6a26f53 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sun, 1 Nov 2026 06:33:57 +0300 Subject: [PATCH 258/260] Export All Open Documents: every page and artboard, linked data included Each format's copy options are given in full, so no remembered option applies: PDF and .ai copies write every page (range all), SVG copies the art of every artboard in one file (useArtboards false), native, .ai and EPS copies include linked files' data. --- crates/engine/src/cmd/addons/document.rs | 21 ++++++++--- .../engine/src/cmd/addons/document/tests.rs | 36 +++++++++++++++++++ 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index 04609d3e6a..30548b80a7 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export All Open Documents", ["Object", "Plug-ins", "Document Tools"], None, - "{folder, format?: vectorcraft|pdf|svg|svgz|ai|eps (default: pdf)} write a copy of every open document, in tab order, to `folder` as File › Save a Copy writes it, each named after its document (<name>.<ext>; -2, -3… added when that name is taken, so no file is replaced), one file each (images embedded, artboards together): every document keeps its path, title and modified state, and no undo step is made. A document that can't be written is listed in `failed` and the others are still written; the active document stays active → {files: [{title, path, warnings}], failed: [{title, error}], format}", + "{folder, format?: vectorcraft|pdf|svg|svgz|ai|eps (default: pdf)} write a copy of every open document, in tab order, to `folder` as File › Save a Copy writes it, each named after its document (<name>.<ext>; -2, -3… added when that name is taken, so no file is replaced), one self-contained file each with all of its art (images embedded or included, every artboard; no remembered save options apply): every document keeps its path, title and modified state, and no undo step is made. A document that can't be written is listed in `failed` and the others are still written; the active document stays active → {files: [{title, path, warnings}], failed: [{title, error}], format}", has_doc, export_all_open ), @@ -98,6 +98,20 @@ fn save_timestamped_copy(s: &mut Session, p: &Value) -> Result<Value> { fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id })) } +/// The save options of every copy, given in full so that no document's remembered options (linked +/// SVG images, a PDF page range, separate artboard files) apply: one self-contained file per +/// document with all of its art. Each format reads only the options it has, and `range` is left +/// out of SVG, where it would pick artboards over `useArtboards`. +fn copy_options(format: &str) -> Value { + match format { + "svg" | "svgz" => json!({ "images": "embed", "useArtboards": false }), + "pdf" => json!({ "range": "all" }), + "eps" => json!({ "includeLinkedFiles": true, "useArtboards": false }), + "ai" | "ait" => json!({ "range": "all", "includeLinked": true, "separateArtboards": false }), + _ => json!({ "includeLinked": true, "separateArtboards": false }), + } +} + fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "addon.document.exportAllOpen"; let format = fileio::save_format(Some(str_param(p, "format").unwrap_or("pdf")), None).map_err(|e| bad(C, e))?; @@ -117,10 +131,7 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> { failed.push(json!({ "title": title, "error": "every numbered name for the copy is taken" })); continue; }; - // One file per document: the remembered options of a document saved before in this format - // (linked SVG images, separate artboard files) would write others beside it. Each format - // reads only the options it has. - let options = json!({ "images": "embed", "separateArtboards": false }); + let options = copy_options(format.id); match fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id, "options": options })) { Ok(r) => { written.push(path.clone()); diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index e1b5d59bf5..562a389e8a 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -240,3 +240,39 @@ fn export_all_open_documents_writes_one_file_each() { assert!(std::fs::read_to_string(out.join("pic.svg")).unwrap().contains("data:image/png;base64,"), "the image is embedded"); let _ = std::fs::remove_dir_all(&dir); } + +/// A PDF document last saved with a page range exports with every page, and an SVG document with +/// two artboards exports as one SVG holding the art of both (#4920 review). +#[test] +fn export_all_open_documents_keeps_every_page_and_artboard() { + let dir = std::env::temp_dir().join(format!("vc-export-all-pages-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("out")).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2, "name": "pages"})).unwrap(); + s.execute("document.save", &json!({"path": dir.join("pages.pdf"), "format": "pdf", "options": {"range": "1"}})).unwrap(); + let pages = |b: &[u8]| { + String::from_utf8_lossy(b).matches("/Type /Page\n").count() + + String::from_utf8_lossy(b).matches("/Type/Page/").count() + + String::from_utf8_lossy(b).matches("/Type /Page/").count() + + String::from_utf8_lossy(b).matches("/Type /Page ").count() + }; + let first = pages(&std::fs::read(dir.join("pages.pdf")).unwrap()); + let out = dir.join("out"); + s.execute("addon.document.exportAllOpen", &json!({"folder": out, "format": "pdf"})).unwrap(); + let copy = pages(&std::fs::read(out.join("pages.pdf")).unwrap()); + assert!(copy > first, "the copy has every page: {first} saved, {copy} exported"); + // SVG: one file with the art on both artboards. + let a = s.doc().unwrap().doc.artboards[1].rect; + s.execute("shape.rectangle", &json!({"x": a.x0 + 10.0, "y": a.y0 + 10.0, "width": 20, "height": 20})).unwrap(); + s.execute("addon.document.exportAllOpen", &json!({"folder": out, "format": "svg"})).unwrap(); + let svgs: Vec<String> = + std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).filter(|n| n.ends_with(".svg")).collect(); + assert_eq!(svgs, ["pages.svg"]); + let svg = std::fs::read_to_string(out.join("pages.svg")).unwrap(); + // Not the first artboard alone (its 100 × 100 box at the origin): the art's own bounds. + let view = svg.split("viewBox=\"").nth(1).and_then(|v| v.split('"').next()).unwrap(); + let w: f64 = view.split_whitespace().nth(2).unwrap().parse().unwrap(); + assert!(w > 19.0 && w < 30.0, "the SVG shows the art (the square on the second artboard), not the first artboard: viewBox {view}"); + let _ = std::fs::remove_dir_all(&dir); +} From a76d9215da087a9577a525d4bdae9e174cd1a291 Mon Sep 17 00:00:00 2001 From: bflatastic <bombayapirat@gmail.com> Date: Sun, 1 Nov 2026 10:51:18 +0700 Subject: [PATCH 259/260] Fix #4923: Find Nearest Swatch matches colours to a library's swatches Object > Plug-ins > Color Effects > Find Nearest Swatch... picks a library (the document's swatches, a built-in library, or a library or colour book the user saved or loaded) and Fill and Stroke, and lists each colour of the selection with its three closest swatches and their CIEDE2000 difference. Apply gives each colour its nearest swatch as one undo step. - addon.color.nearestSwatch (a query): the closest swatches of a library to each colour of the selection's fills and strokes (solid colours and gradient stops, inside groups and type), or to a colour given, with deltaE; count 1..50. - addon.color.applyNearestSwatch: recolours those paints (and gradient meshes) to their nearest swatch; global and spot swatches link, and a library's swatches the colours take are added to the document first (as swatch.library.add adds them), so a spot colour stays spot. - The library picker Image Trace's Document Library uses moves to the Swatches panel module and is shared. - No colour book data ships: only libraries VectorCraft computes or the user loads are searched. --- ROADMAP.md | 4 +- crates/engine/src/cmd/addons/arrange.rs | 2 +- crates/engine/src/cmd/addons/color.rs | 24 ++- crates/engine/src/cmd/addons/color/nearest.rs | 198 ++++++++++++++++++ .../src/cmd/addons/color/nearest/tests.rs | 115 ++++++++++ crates/engine/tests/command_sweep.rs | 5 + crates/ui-egui/src/addons/color.rs | 5 +- crates/ui-egui/src/addons/color/nearest.rs | 147 +++++++++++++ crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/i18n/bg.tsv | 7 + crates/ui-egui/src/i18n/bs.tsv | 7 + crates/ui-egui/src/i18n/ca.tsv | 7 + crates/ui-egui/src/i18n/cs.tsv | 7 + crates/ui-egui/src/i18n/da.tsv | 7 + crates/ui-egui/src/i18n/de.tsv | 7 + crates/ui-egui/src/i18n/el.tsv | 7 + crates/ui-egui/src/i18n/es.tsv | 7 + crates/ui-egui/src/i18n/fi.tsv | 7 + crates/ui-egui/src/i18n/fr.tsv | 7 + crates/ui-egui/src/i18n/hu.tsv | 7 + crates/ui-egui/src/i18n/id.tsv | 7 + crates/ui-egui/src/i18n/it.tsv | 7 + crates/ui-egui/src/i18n/ja.tsv | 7 + crates/ui-egui/src/i18n/ka.tsv | 7 + crates/ui-egui/src/i18n/ko.tsv | 7 + crates/ui-egui/src/i18n/nl.tsv | 7 + crates/ui-egui/src/i18n/pl.tsv | 7 + crates/ui-egui/src/i18n/pt-br.tsv | 7 + crates/ui-egui/src/i18n/ru.tsv | 7 + crates/ui-egui/src/i18n/sv.tsv | 7 + crates/ui-egui/src/i18n/tr.tsv | 7 + crates/ui-egui/src/i18n/uk.tsv | 7 + crates/ui-egui/src/i18n/vi.tsv | 7 + crates/ui-egui/src/i18n/zh-hans.tsv | 7 + crates/ui-egui/src/i18n/zh-hant.tsv | 7 + crates/ui-egui/src/menus/invoke.rs | 1 + crates/ui-egui/src/panels/image_trace.rs | 24 +-- .../ui-egui/src/panels/image_trace/tests.rs | 1 + crates/ui-egui/src/panels/swatches.rs | 4 +- .../ui-egui/src/panels/swatches/libraries.rs | 18 ++ docs/mcp.md | 24 +++ docs/target-app-parity.md | 7 +- docs/ui-parity.md | 4 +- 43 files changed, 737 insertions(+), 29 deletions(-) create mode 100644 crates/engine/src/cmd/addons/color/nearest.rs create mode 100644 crates/engine/src/cmd/addons/color/nearest/tests.rs create mode 100644 crates/ui-egui/src/addons/color/nearest.rs diff --git a/ROADMAP.md b/ROADMAP.md index c85be5aefd..4d5918cba5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -9,7 +9,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Path Precision Tools add-on's Expand Dashes into Paths; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Color Effects add-on's Find Nearest Swatch; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923). - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). @@ -211,6 +212,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Progress log row for the Color Effects add-on's Find Nearest Swatch (#4923); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Path Precision Tools add-on's Expand Dashes into Paths (#4922); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Randomize Opacity (#4925); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Sort Objects (#4917); headline numbers unchanged. | diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 9b11a71153..735d721335 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -120,7 +120,7 @@ fn number_in(p: &Value, key: &str, default: f64, (lo, hi): (f64, f64), cmd: &str } /// Whole-number param `key` within `lo..=hi`, `None` when left out. -fn whole_in(p: &Value, key: &str, (lo, hi): (u64, u64), cmd: &str) -> Result<Option<u64>> { +pub(super) fn whole_in(p: &Value, key: &str, (lo, hi): (u64, u64), cmd: &str) -> Result<Option<u64>> { let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) }; let n = v.as_u64().ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number")))?; if (lo..=hi).contains(&n) { Ok(Some(n)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 4426624ccf..3dc037a2fa 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -2,9 +2,11 @@ //! Duotone and Invert Colors, in Effect › Color Effects) are the effects crate's; here, Apply as //! Filter writes any colour adjustment into the colours themselves, Select by Color Kind selects the //! objects that use spot colours, carry a live colour adjustment, or are images of a colour model, -//! and Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print. Its panel and -//! its submenu, Object › Plug-ins › Color Effects, are the UI's. +//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, and Find Nearest +//! Swatch ([`nearest`]) matches colours to a swatch library's. Its panel and its submenu, Object › +//! Plug-ins › Color Effects, are the UI's. +mod nearest; mod print_fixes; #[cfg(test)] mod tests; @@ -50,6 +52,24 @@ pub fn specs() -> Vec<CommandSpec> { has_doc, print_fixes::run ), + cmd!( + query "addon.color.nearestSwatch", + "Find Nearest Swatch", + ["Object", "Plug-ins", "Color Effects"], + None, + "{library?: a swatch library's id or name (swatch.library.list: the built-in ones, and the colour books and libraries the user saved or loaded) or \"document\" (the document's swatches; the default), color?: colour (look this colour up; default: the selection's), fill?: true, stroke?: true (the selected objects' fills and strokes, their type's and those of the objects inside them: solid colours and gradient stops, once each, the first 100), count?: 1..50 (5), ids?: [id…] (default: the selection)} list the library's colour swatches closest to each colour, closest first, by CIEDE2000 difference (ΔE; under 1 hardly tells apart, about 2 to 3 close). Tint swatches, None and Registration aren't matched → {library, colors: [{values, hex, matches: [{name, values, hex, spot, deltaE}]}]}", + has_doc, + nearest::find + ), + cmd!( + "addon.color.applyNearestSwatch", + "Apply Nearest Swatch", + ["Object", "Plug-ins", "Color Effects"], + None, + "{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step: a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}", + has_selection, + nearest::apply + ), ] } diff --git a/crates/engine/src/cmd/addons/color/nearest.rs b/crates/engine/src/cmd/addons/color/nearest.rs new file mode 100644 index 0000000000..5a9d0e7c75 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/nearest.rs @@ -0,0 +1,198 @@ +//! Find Nearest Swatch (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`; Object › +//! Plug-ins › Color Effects › Find Nearest Swatch…): the swatches of a library, a colour book the +//! user loaded or the document closest to each colour of the selection (CIEDE2000), and the +//! colours replaced by them as one undo step (#4923). + +use serde_json::{Value, json}; +use vectorcraft_color::cms::{Lab, delta_e2000}; +use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_doc::swatches::color_name; +use vectorcraft_doc::{Document, NodeId, NodeKind}; + +use super::super::super::colorcmds::recolor_links; +use super::super::super::menucmds::squash; +use super::super::super::swatchlib::{DOCUMENT_SWATCHES, library_swatches}; +use super::super::super::{bad, checked_ids_or_selection, color_value, index, switch_or, text_param}; +use super::super::arrange::whole_in; +use crate::{Result, Session}; + +const FIND: &str = "addon.color.nearestSwatch"; +const APPLY: &str = "addon.color.applyNearestSwatch"; +/// The most colours of the selection looked up. +const MAX_COLORS: usize = 100; + +/// The `library` param ([`DOCUMENT_SWATCHES`] when left out) and its colour swatches with their Lab +/// values. +fn candidates(s: &Session, p: &Value, cmd: &str) -> Result<(String, Vec<(Swatch, Lab)>)> { + let key = text_param(p, "library", cmd)?.unwrap_or(DOCUMENT_SWATCHES).to_string(); + let swatches = library_swatches(s, &key).ok_or_else(|| bad(cmd, format!("no swatch library `{key}` (see swatch.library.list)")))?; + let labs: Vec<(Swatch, Lab)> = swatches + .into_iter() + .filter(|w| !w.is_reserved()) + .filter_map(|w| { + let lab = w.paint.color()?.to_lab(); + Some((w, lab)) + }) + .collect(); + if labs.is_empty() { + return Err(bad(cmd, format!("`{key}` has no colours"))); + } + Ok((key, labs)) +} + +/// The `count` swatches of `among` closest to `c`, closest first, with their difference (ΔE 2000). +fn nearest(among: &[(Swatch, Lab)], c: Color, count: usize) -> Vec<(&Swatch, f32)> { + let lab = c.to_lab(); + let mut v: Vec<(&Swatch, f32)> = among.iter().map(|(w, l)| (w, delta_e2000(*l, lab))).collect(); + v.sort_by(|a, b| a.1.total_cmp(&b.1)); + v.truncate(count); + v +} + +/// The solid colours and gradient stops of the fills (`fill`) and strokes (`stroke`) of `ids`, of +/// everything inside them and of their type, once each and at most [`MAX_COLORS`]. +fn art_colors(d: &Document, ids: &[NodeId], fill: bool, stroke: bool) -> Vec<Color> { + let mut out: Vec<Color> = vec![]; + let mut add = |p: &Paint| { + let colors: Vec<Color> = match p { + Paint::Solid { color, .. } => vec![*color], + Paint::Gradient(g) => g.gradient.stops.iter().map(|s| s.color).collect(), + _ => vec![], + }; + for c in colors { + if out.len() < MAX_COLORS && !out.contains(&c) { + out.push(c); + } + } + }; + for n in ids.iter().filter_map(|id| d.node(*id)) { + n.walk(&mut |m| { + for it in &m.appearance.items { + if if it.is_fill() { fill } else { stroke } { + add(it.paint()); + } + } + if let NodeKind::Text(t) = &m.kind { + for r in &t.runs { + if fill { + add(&r.style.fill); + } + if stroke { + add(&r.style.stroke); + } + } + } + }); + } + out +} + +/// A swatch's name and values as the results give them. +fn described(w: &Swatch) -> Value { + let c = w.paint.color().unwrap_or_default(); + json!({ "name": w.name, "values": color_name(c), "hex": c.to_hex(), "spot": w.spot }) +} + +pub(super) fn find(s: &mut Session, p: &Value) -> Result<Value> { + let count = whole_in(p, "count", (1, 50), FIND)?.map_or(5, index); + let (fill, stroke) = (switch_or(p, "fill", true, FIND)?, switch_or(p, "stroke", true, FIND)?); + let colors = match p.get("color").filter(|v| !v.is_null()) { + Some(v) => vec![color_value(v).ok_or_else(|| bad(FIND, "`color` is not a colour"))?], + None => { + let ids = checked_ids_or_selection(s, p, FIND)?; + if ids.is_empty() { + return Err(bad(FIND, "select objects or give `color`")); + } + art_colors(&s.doc()?.doc, &ids, fill, stroke) + } + }; + let (library, among) = candidates(s, p, FIND)?; + let found: Vec<Value> = colors + .iter() + .map(|c| { + let matches: Vec<Value> = nearest(&among, *c, count) + .into_iter() + .map(|(w, de)| { + let mut m = described(w); + m["deltaE"] = json!((f64::from(de) * 100.0).round() / 100.0); + m + }) + .collect(); + json!({ "values": color_name(*c), "hex": c.to_hex(), "matches": matches }) + }) + .collect(); + Ok(json!({ "library": library, "colors": found })) +} + +pub(super) fn apply(s: &mut Session, p: &Value) -> Result<Value> { + let (fill, stroke) = (switch_or(p, "fill", true, APPLY)?, switch_or(p, "stroke", true, APPLY)?); + let ids = checked_ids_or_selection(s, p, APPLY)?; + if ids.is_empty() { + return Err(bad(APPLY, "nothing selected")); + } + let (library, among) = candidates(s, p, APPLY)?; + // The swatch each colour takes, once each. + let colors = art_colors(&s.doc()?.doc, &ids, fill, stroke); + let mut used: Vec<&Swatch> = vec![]; + for c in &colors { + if let Some((w, _)) = nearest(&among, *c, 1).first() + && !used.iter().any(|u| u.name == w.name) + { + used.push(w); + } + } + if used.is_empty() { + return Ok(json!({ "changed": 0, "swatches": [], "added": [] })); + } + let undo = s.doc()?.history.undo.len(); + // A library's swatches join the document's first, as Add to Swatches adds them, so spot and + // global colours stay linked to theirs. + let mut added = vec![]; + let mut names: Vec<String> = used.iter().map(|w| w.name.clone()).collect(); + if library != DOCUMENT_SWATCHES { + let r = s.execute("swatch.library.add", &json!({ "library": library, "names": names }))?; + let listed = |k: &str| r.get(k).and_then(Value::as_array).cloned().unwrap_or_default(); + let in_doc: Vec<String> = listed("added").iter().chain(&listed("existing")).filter_map(Value::as_str).map(str::to_string).collect(); + let d = &s.doc()?.doc; + // Each library swatch's copy: the document swatch with its paint among those added or kept. + names = used + .iter() + .map(|w| in_doc.iter().find(|n| d.swatch(n).is_some_and(|x| x.paint == w.paint)).cloned().unwrap_or_else(|| w.name.clone())) + .collect(); + added = listed("added"); + } + // Each used swatch's paint as art takes it: linked to a global or spot swatch. + let d = &s.doc()?.doc; + let paints: Vec<(Lab, Paint)> = used + .iter() + .zip(&names) + .filter_map(|(w, name)| { + let lab = w.paint.color()?.to_lab(); + let paint = d.swatch(name).filter(|x| x.global).and_then(|_| d.tint_paint(name, 1.0)).unwrap_or_else(|| w.paint.clone()); + Some((lab, paint)) + }) + .collect(); + // shortcut: a colour past the MAX_COLORS looked up takes the closest of the swatches those + // took; look up every colour if documents with more colours need their own matches. + let to = |c: Color| -> Option<&Paint> { + let lab = c.to_lab(); + paints.iter().min_by(|a, b| delta_e2000(a.0, lab).total_cmp(&delta_e2000(b.0, lab))).map(|(_, p)| p) + }; + let links = |c: &mut Color, link: &mut Option<String>, tint: &mut f32| { + let Some(Paint::Solid { color, swatch, .. }) = to(*c) else { return false }; + if *c == *color && *link == *swatch { + return false; + } + (*c, *link, *tint) = (*color, swatch.clone(), 1.0); + true + }; + let given = json!({ + "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "fill": fill, "stroke": stroke, "includeImages": false, "includePatterns": false, + }); + let r = recolor_links(s, &given, "Apply Nearest Swatch", &|c| to(c).and_then(Paint::color).unwrap_or(c), &links)?; + squash(s, undo, "Apply Nearest Swatch"); + Ok(json!({ "changed": r["changed"], "swatches": names, "added": added })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/color/nearest/tests.rs b/crates/engine/src/cmd/addons/color/nearest/tests.rs new file mode 100644 index 0000000000..0436d19c89 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/nearest/tests.rs @@ -0,0 +1,115 @@ +//! Find Nearest Swatch. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::NodeId; + +use crate::Session; + +const FIND: &str = "addon.color.nearestSwatch"; +const APPLY: &str = "addon.color.applyNearestSwatch"; + +/// A document with a global swatch "Brand" and a selected rectangle filled `fill`, stroked `stroke`. +fn doc(fill: &str, stroke: Option<&str>) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("swatch.new", &json!({"name": "Brand", "color": "#ff8000", "global": true})).unwrap(); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color": fill})).unwrap(); + match stroke { + Some(c) => s.execute("paint.setStroke", &json!({"color": c})).unwrap(), + None => s.execute("paint.setStroke", &json!({"none": true})).unwrap(), + }; + (s, id) +} + +fn paints(s: &Session, id: NodeId) -> (Paint, Paint) { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + (n.appearance.fill_paint(), n.appearance.items.iter().find(|i| !i.is_fill()).unwrap().paint().clone()) +} + +fn names(matches: &Value) -> Vec<&str> { + matches.as_array().unwrap().iter().map(|m| m["name"].as_str().unwrap()).collect() +} + +#[test] +fn the_closest_swatches_of_a_library_are_listed_closest_first() { + let (mut s, _) = doc("#ff6634", None); + let v = s.execute(FIND, &json!({"library": "web-safe-216", "count": 3})).unwrap(); + assert_eq!(v["library"], "web-safe-216"); + let colors = v["colors"].as_array().unwrap(); + assert_eq!(colors.len(), 1, "the fill; no stroke"); + assert_eq!((colors[0]["hex"].as_str(), colors[0]["values"].as_str()), (Some("#ff6634"), Some("R=255 G=102 B=52"))); + let m = &colors[0]["matches"]; + assert_eq!(names(m)[0], "#FF6633"); + let de: Vec<f64> = m.as_array().unwrap().iter().map(|x| x["deltaE"].as_f64().unwrap()).collect(); + assert_eq!(de.len(), 3); + assert!(de[0] < 1.0 && de.windows(2).all(|w| w[0] <= w[1]), "{de:?}"); + // A colour given is looked up instead of the selection's. + let v = s.execute(FIND, &json!({"library": "web-safe-216", "color": "#010203", "count": 1})).unwrap(); + assert_eq!(names(&v["colors"][0]["matches"]), ["#000000"]); +} + +#[test] +fn the_document_swatches_are_the_default_library() { + let (mut s, _) = doc("#ff8010", Some("#ff8010")); + let v = s.execute(FIND, &json!({})).unwrap(); + assert_eq!(v["library"], "document"); + assert_eq!(v["colors"].as_array().unwrap().len(), 1, "fill and stroke share a colour: looked up once"); + assert_eq!(names(&v["colors"][0]["matches"])[0], "Brand"); + assert!(!names(&v["colors"][0]["matches"]).contains(&"[Registration]")); +} + +#[test] +fn applying_links_each_colour_to_its_nearest_document_swatch_as_one_undo_step() { + let (mut s, id) = doc("#ff8010", Some("#ff8010")); + let undo = s.doc().unwrap().history.undo.len(); + let v = s.execute(APPLY, &json!({"stroke": false})).unwrap(); + assert_eq!((v["changed"].as_u64(), v["swatches"].clone(), v["added"].clone()), (Some(1), json!(["Brand"]), json!([]))); + let (fill, stroke) = paints(&s, id); + assert!(matches!(&fill, Paint::Solid { swatch: Some(n), color, .. } if n == "Brand" && color.to_hex() == "#ff8000"), "{fill:?}"); + assert_eq!(stroke.color().unwrap().to_hex(), "#ff8010", "strokes left alone"); + let st = s.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.history.undo.last().unwrap().label.as_str()), (undo + 1, "Apply Nearest Swatch")); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(paints(&s, id).0.color().unwrap().to_hex(), "#ff8010"); +} + +#[test] +fn a_library_spot_colour_joins_the_document_and_stays_spot() { + let (mut s, id) = doc("#e01525", None); + // A colour book of one spot colour, loaded as a user would load one they own. + s.execute("swatch.new", &json!({"name": "Ink Red", "color": "#e01020", "spot": true})).unwrap(); + let data = s.execute("swatch.library.save", &json!({"names": ["Ink Red"]})).unwrap()["data"].as_str().unwrap().to_string(); + s.execute("swatch.delete", &json!({"names": ["Ink Red"]})).unwrap(); + let lib = s.execute("swatch.library.load", &json!({"data": data, "name": "Book.vcswatches"})).unwrap()["library"].as_str().unwrap().to_string(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + let v = s.execute(APPLY, &json!({"library": lib})).unwrap(); + assert_eq!((v["swatches"].clone(), v["added"].clone()), (json!(["Ink Red"]), json!(["Ink Red"]))); + let d = &s.doc().unwrap().doc; + assert!(d.swatch("Ink Red").is_some_and(|w| w.spot && w.global)); + assert!(matches!(paints(&s, id).0, Paint::Solid { swatch: Some(n), .. } if n == "Ink Red")); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "adding and applying undo together"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.swatch("Ink Red").is_none()); + assert_eq!(paints(&s, id).0, Paint::solid(Color::from_hex("#e01525").unwrap())); +} + +#[test] +fn bad_requests_are_refused() { + let (mut s, _) = doc("#ff8010", None); + for (p, why) in [ + (json!({"library": "nope"}), "no swatch library `nope`"), + (json!({"library": "spectrum-gradients"}), "has no colours"), + (json!({"count": 0}), "`count` must be from 1 to 50"), + (json!({"color": "zzz"}), "`color` is not a colour"), + (json!({"fill": "yes"}), "`fill` must be true or false"), + ] { + let e = s.execute(FIND, &p).unwrap_err().to_string(); + assert!(e.contains(why), "{p}: {e}"); + } + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute(FIND, &json!({})).unwrap_err().to_string().contains("select objects or give `color`")); + assert!(s.execute(APPLY, &json!({})).is_err(), "nothing selected"); +} diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 38a60e2394..7202df9605 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -434,6 +434,11 @@ fn structured_junk() { ("addon.color.printFixes", json!({"inkLimit": 1e308, "overprintBlack": -1e308})), ("addon.color.printFixes", json!({"inkLimit": 1, "overprintBlack": 1, "removeWhiteOverprint": true, "scope": "document", "textOnly": true})), ("addon.color.printFixes", json!({"inkLimit": [300], "scope": 3, "ids": "x"})), + ("addon.color.nearestSwatch", json!({"library": 7, "count": u64::MAX, "color": [1e308, -1e308, "x"]})), + ("addon.color.nearestSwatch", json!({"library": "web-safe-216", "color": {"l": 1e30, "a": -1e30, "b": 0}, "count": 50})), + ("addon.color.nearestSwatch", json!({"library": "spectrum-gradients", "fill": "x", "ids": [u64::MAX]})), + ("addon.color.applyNearestSwatch", json!({"library": "web-safe-216", "fill": true, "stroke": true})), + ("addon.color.applyNearestSwatch", json!({"library": "nope", "ids": "x", "stroke": 3})), ("effect.apply", json!({"effect": "no.such.effect"})), ("effect.remove", json!({"index": 99})), ("effect.setParams", json!({"index": 0, "params": null})), diff --git a/crates/ui-egui/src/addons/color.rs b/crates/ui-egui/src/addons/color.rs index c3944cbb83..af472edb94 100644 --- a/crates/ui-egui/src/addons/color.rs +++ b/crates/ui-egui/src/addons/color.rs @@ -3,7 +3,9 @@ //! filter, into the colours themselves (`addon.color.filter`); below, under Inks, it opens Duotone's //! dialog and Print Ink Fixes' (`addon.color.printFixes`). The submenu applies the add-on's live //! effects, Duotone and Vector Halftone among them (Effect › Color Effects has them too), opens -//! Print Ink Fixes and opens the panel. +//! Print Ink Fixes and Find Nearest Swatch ([`nearest`]) and opens the panel. + +pub mod nearest; use egui::Ui; use serde_json::{Map, Value, json}; @@ -97,6 +99,7 @@ pub fn menu() -> Vec<Item> { Item::Cmd("Vector Halftone…", "effect.dialog", json!({ "effect": "addon.color.halftone" })), Item::Sep, cmd(print_fixes()), + Item::Cmd("Find Nearest Swatch…", nearest::COMMAND, Value::Null), Item::Sep, Item::Sub( "Select by Color Kind", diff --git a/crates/ui-egui/src/addons/color/nearest.rs b/crates/ui-egui/src/addons/color/nearest.rs new file mode 100644 index 0000000000..b073119d6a --- /dev/null +++ b/crates/ui-egui/src/addons/color/nearest.rs @@ -0,0 +1,147 @@ +//! Find Nearest Swatch in the interface (Object › Plug-ins › Color Effects › Find Nearest +//! Swatch…): a dialog that picks a library (the document's swatches, or a colour library or book) +//! and Fill and Stroke, and lists each colour of the selection with its closest swatches and their +//! difference, as `addon.color.nearestSwatch` finds them; Apply runs +//! `addon.color.applyNearestSwatch`. + +use egui::Ui; +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::panels::swatches; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::widgets; + +/// The command Apply runs, and the dialog's kind. +pub const COMMAND: &str = "addon.color.applyNearestSwatch"; +pub const KIND: &str = "nearestSwatch"; +/// The query that lists the matches, and how many of each colour's the dialog shows. +const FIND: &str = "addon.color.nearestSwatch"; +const MATCHES: u64 = 3; +const LABEL_W: f32 = 60.0; +const CHIP: f32 = 14.0; + +/// The dialog's fields to start with: the document's swatches, fills and strokes. +pub(crate) fn fields() -> Value { + json!({ "library": DOCUMENT_SWATCHES, "fill": true, "stroke": true }) +} + +pub(crate) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Find Nearest Swatch").to_string(), + body, + confirm, + ok: Some("Apply"), + min_width: 340.0, + ok_enabled: Some(|app, _| app.session.active().is_some_and(|st| !st.selection.is_empty())), + ..DialogSpec::FORM +}; + +/// A colour chip of `hex`, then `text`. +fn chip_label(ui: &mut Ui, hex: &str, text: &str, color: egui::Color32) { + let (r, _) = ui.allocate_exact_size(egui::vec2(CHIP, CHIP), egui::Sense::hover()); + widgets::swatch_tile(ui, r, &Paint::solid(Color::from_hex(hex).unwrap_or_default()), false, false); + ui.label(egui::RichText::new(text).color(color)); +} + +fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + let key = d.str("library"); + widgets::label_row(ui, tl!("Library:"), LABEL_W, |ui| { + if let Some(k) = widgets::combo(ui, "nearest-library", &swatches::library_label(app, &key), 220.0, |ui| swatches::library_list(app, ui, &key)) + { + d.fields.insert("library".into(), json!(k)); + } + }); + ui.horizontal(|ui| { + form::check(ui, d, "fill", tl!("Fill")); + form::check(ui, d, "stroke", tl!("Stroke")); + }); + ui.add_space(6.0); + let t = Tokens::get(ui.ctx()); + if app.session.active().is_none_or(|st| st.selection.is_empty()) { + ui.label(egui::RichText::new(tl!("Select objects to find the swatches nearest their colors.")).color(t.text_dim)); + return false; + } + let mut p = form::params(d); + p["count"] = json!(MATCHES); + let found = match app.session.execute(FIND, &p) { + Ok(v) => v, + Err(e) => { + ui.label(egui::RichText::new(crate::i18n::message(crate::i18n::current(), &e.to_string())).color(t.text_dim)); + return false; + } + }; + let colors = found["colors"].as_array().cloned().unwrap_or_default(); + // Each colour, then its matches indented, closest first. + egui::ScrollArea::vertical().max_height(280.0).show(ui, |ui| { + for c in &colors { + ui.horizontal(|ui| chip_label(ui, c["hex"].as_str().unwrap_or_default(), c["values"].as_str().unwrap_or_default(), t.text)); + for m in c["matches"].as_array().into_iter().flatten() { + ui.horizontal(|ui| { + ui.add_space(CHIP + 8.0); + let de = m["deltaE"].as_f64().unwrap_or_default(); + chip_label(ui, m["hex"].as_str().unwrap_or_default(), m["name"].as_str().unwrap_or_default(), t.text); + ui.label(egui::RichText::new(format!("ΔE {de:.1}")).color(t.text_dim)); + }); + } + } + }); + false +} + +/// Apply: give each colour its nearest swatch and close. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { + app.ui.dialog = None; + app.run(COMMAND, form::params(d)) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use vectorcraft_color::Paint; + use vectorcraft_engine::Session; + + use crate::tests_labels::painted_text; + use crate::{VectorcraftApp, menus}; + + #[test] + fn find_nearest_swatch_lists_the_matches_and_applies_the_nearest() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": "Brand", "color": "#ff8000", "global": true})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff8010"})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Color Effects"] && e.label == "Find Nearest Swatch…").unwrap(); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(&mut app, &cmd, p); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::KIND)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Find Nearest Swatch", "Library:", "Document Swatches", "Fill", "Stroke", "R=255 G=128 B=16", "Brand", "ΔE", "Apply"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + // Another library lists its own swatches. + app.ui.dialog.as_mut().unwrap().fields.insert("library".into(), json!("web-safe-216")); + assert!(painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())).contains("#FF6600")); + app.ui.dialog.as_mut().unwrap().fields.insert("library".into(), json!("document")); + let undo = app.session.doc().unwrap().history.undo.len(); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), undo + 1); + let fill = st.doc.node(st.selection.objects[0]).unwrap().appearance.fill_paint(); + assert!(matches!(fill, Paint::Solid { swatch: Some(n), .. } if n == "Brand")); + // Nothing selected: the dialog says what to do and Apply is off. + app.run("select.none", json!({})).unwrap(); + menus::invoke(&mut app, &cmd, serde_json::Value::Null); + assert!( + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())) + .contains("Select objects to find the swatches nearest their colors.") + ); + assert!(!(super::SPEC.ok_enabled.unwrap())(&app, app.ui.dialog.as_ref().unwrap()), "Apply is off"); + } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 0e9f7b75f1..6e86304e21 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -402,6 +402,7 @@ registry! { RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC, PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC, DivideDashes: [crate::addons::pathtools::dashes::KIND] => crate::addons::pathtools::dashes::SPEC, + NearestSwatch: [crate::addons::color::nearest::KIND] => crate::addons::color::nearest::SPEC, ArrangeTools: [crate::addons::arrange::GRID, crate::addons::arrange::REPLACE, crate::addons::arrange::SIZE, crate::addons::arrange::OPACITY, crate::addons::arrange::SORT] => crate::addons::arrange::SPEC, ShortcutImport: [shortcut_import::KIND] => DialogSpec::window(shortcut_import::show, shortcut_import::confirm), } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index ee71fa0f61..f3f6cbfbb6 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5829,6 +5829,13 @@ anchor Points: Точки: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` задайте `inkLimit`, `removeWhiteOverprint` или `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Корекциите на мастилата за печат работят върху CMYK документи: първо изберете Файл › Цветен режим на документа › CMYK цвят @msg `{key}` must be 0..{max} `{key}` трябва да е 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Намиране на най-близкия образец… + Find Nearest Swatch Намиране на най-близкия образец + Apply Nearest Swatch Прилагане на най-близкия образец + Select objects to find the swatches nearest their colors. Изберете обекти, за да намерите най-близките до цветовете им образци. +@msg select objects or give `color` изберете обекти или задайте `color` +@msg `color` is not a colour `color` не е цвят # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Инструмент „Ъгли“ Slide Anchor Along Path Плъзгане на опорна точка по пътя diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 69b53b2d11..d7efa9c0e7 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5953,6 +5953,13 @@ shape Open Otvoren Gap 4 Razmak 4 Dash 5 Crtica 5 Gap 5 Razmak 5 +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Pronađi najbliži uzorak boje… + Find Nearest Swatch Pronađi najbliži uzorak boje + Apply Nearest Swatch Primijeni najbliži uzorak boje + Select objects to find the swatches nearest their colors. Odaberite objekte da pronađete uzorke boja najbliže njihovim bojama. +@msg select objects or give `color` odaberite objekte ili navedite `color` +@msg `color` is not a colour `color` nije boja # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Alat za uglove Slide Anchor Along Path Klizanje sidra po putanji diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index ced6fdc32e..cd6172d6a6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5935,6 +5935,13 @@ anchor Points: Punts: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` indiqueu `inkLimit`, `removeWhiteOverprint` o `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Les correccions de tinta per a impressió funcionen en documents CMYK: trieu primer Fitxer › Mode de color del document › Color CMYK @msg `{key}` must be 0..{max} `{key}` ha de ser 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Cerca la mostra més propera… + Find Nearest Swatch Cerca la mostra més propera + Apply Nearest Swatch Aplica la mostra més propera + Select objects to find the swatches nearest their colors. Seleccioneu objectes per trobar les mostres més properes als seus colors. +@msg select objects or give `color` seleccioneu objectes o indiqueu `color` +@msg `color` is not a colour `color` no és un color # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Eina de cantonades Slide Anchor Along Path Llisca l’ancoratge pel traçat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index c7626cc9f6..34c7f4e035 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5947,6 +5947,13 @@ anchor Points: Body: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` zadejte `inkLimit`, `removeWhiteOverprint` nebo `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Opravy tiskových barev fungují v dokumentech CMYK: nejprve zvolte Soubor › Barevný režim dokumentu › Barvy CMYK @msg `{key}` must be 0..{max} `{key}` musí být 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Najít nejbližší položku vzorníku… + Find Nearest Swatch Najít nejbližší položku vzorníku + Apply Nearest Swatch Použít nejbližší položku vzorníku + Select objects to find the swatches nearest their colors. Vyberte objekty, k jejichž barvám chcete najít nejbližší položky vzorníku. +@msg select objects or give `color` vyberte objekty nebo zadejte `color` +@msg `color` is not a colour `color` není barva # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Nástroj Rohy Slide Anchor Along Path Posunout kotevní bod po cestě diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index d66fe03333..5a23913424 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5845,6 +5845,13 @@ anchor Points: Punkter: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` angiv `inkLimit`, `removeWhiteOverprint` eller `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Trykfarverettelser virker på CMYK-dokumenter: vælg først Filer › Dokumentets farvetilstand › CMYK-farve @msg `{key}` must be 0..{max} `{key}` skal være 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Find nærmeste farveprøve… + Find Nearest Swatch Find nærmeste farveprøve + Apply Nearest Swatch Anvend nærmeste farveprøve + Select objects to find the swatches nearest their colors. Markér objekter for at finde de farveprøver, der ligger tættest på deres farver. +@msg select objects or give `color` markér objekter, eller angiv `color` +@msg `color` is not a colour `color` er ikke en farve # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Hjørneværktøj Slide Anchor Along Path Skub ankerpunkt langs sti diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2a787c528f..101bbefac6 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5532,6 +5532,13 @@ anchor Points: Punkte: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` geben Sie `inkLimit`, `removeWhiteOverprint` oder `overprintBlack` an @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Druckfarbkorrekturen wirken in CMYK-Dokumenten: Wählen Sie zuerst Datei › Dokumentfarbmodus › CMYK-Farbe @msg `{key}` must be 0..{max} `{key}` muss 0..{max} sein +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Ähnlichstes Farbfeld suchen… + Find Nearest Swatch Ähnlichstes Farbfeld suchen + Apply Nearest Swatch Ähnlichstes Farbfeld anwenden + Select objects to find the swatches nearest their colors. Wählen Sie Objekte aus, um die Farbfelder zu finden, die ihren Farben am nächsten kommen. +@msg select objects or give `color` wählen Sie Objekte aus oder geben Sie `color` an +@msg `color` is not a colour `color` ist keine Farbe # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Ecken-Werkzeug Slide Anchor Along Path Ankerpunkt entlang des Pfads verschieben diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 335d01af63..e704faade5 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5898,6 +5898,13 @@ anchor Points: Σημεία: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` δώστε `inkLimit`, `removeWhiteOverprint` ή `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Οι διορθώσεις μελανιών εκτύπωσης ισχύουν σε έγγραφα CMYK: επιλέξτε πρώτα Αρχείο › Λειτουργία χρώματος εγγράφου › Χρώμα CMYK @msg `{key}` must be 0..{max} το `{key}` πρέπει να είναι 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Εύρεση πλησιέστερου δείγματος χρώματος… + Find Nearest Swatch Εύρεση πλησιέστερου δείγματος χρώματος + Apply Nearest Swatch Εφαρμογή πλησιέστερου δείγματος χρώματος + Select objects to find the swatches nearest their colors. Επιλέξτε αντικείμενα για να βρείτε τα δείγματα χρωμάτων που πλησιάζουν περισσότερο τα χρώματά τους. +@msg select objects or give `color` επιλέξτε αντικείμενα ή δώστε `color` +@msg `color` is not a colour το `color` δεν είναι χρώμα # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Γωνίες (Corner Tool) Slide Anchor Along Path Ολίσθηση σημείου αγκύρωσης κατά μήκος διαδρομής diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 0b7a0cfaa6..4ebddbe9a9 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5889,6 +5889,13 @@ anchor Points: Puntos: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` indique `inkLimit`, `removeWhiteOverprint` u `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Las correcciones de tinta para impresión funcionan en documentos CMYK: elija primero Archivo › Modo de color del documento › Color CMYK @msg `{key}` must be 0..{max} `{key}` debe ser 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Buscar muestra más cercana… + Find Nearest Swatch Buscar muestra más cercana + Apply Nearest Swatch Aplicar muestra más cercana + Select objects to find the swatches nearest their colors. Seleccione objetos para buscar las muestras más cercanas a sus colores. +@msg select objects or give `color` seleccione objetos o indique `color` +@msg `color` is not a colour `color` no es un color # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Herramienta Esquinas Slide Anchor Along Path Deslizar punto de ancla por el trazado diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index c733d6143a..7042b21f22 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5977,6 +5977,13 @@ anchor Points: Pisteet: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` anna `inkLimit`, `removeWhiteOverprint` tai `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Painovärien korjaukset toimivat CMYK-asiakirjoissa: valitse ensin Tiedosto › Asiakirjan väritila › CMYK-väri @msg `{key}` must be 0..{max} `{key}` on oltava 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Etsi lähin värimalli… + Find Nearest Swatch Etsi lähin värimalli + Apply Nearest Swatch Käytä lähintä värimallia + Select objects to find the swatches nearest their colors. Valitse objektit, joiden väreille haluat etsiä lähimmät värimallit. +@msg select objects or give `color` valitse objekteja tai anna `color` +@msg `color` is not a colour `color` ei ole väri # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Kulmatyökalu Slide Anchor Along Path Liu’uta ankkuripistettä polkua pitkin diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 737acaf423..48eb621eb9 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5944,6 +5944,13 @@ anchor Points: Points : @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` indiquez `inkLimit`, `removeWhiteOverprint` ou `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Les corrections d’encres pour l’impression s’appliquent aux documents CMJN : choisissez d’abord Fichier › Mode colorimétrique du document › Couleur CMJN @msg `{key}` must be 0..{max} `{key}` doit être compris entre 0 et {max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Rechercher la nuance la plus proche… + Find Nearest Swatch Rechercher la nuance la plus proche + Apply Nearest Swatch Appliquer la nuance la plus proche + Select objects to find the swatches nearest their colors. Sélectionnez des objets pour trouver les nuances les plus proches de leurs couleurs. +@msg select objects or give `color` sélectionnez des objets ou indiquez `color` +@msg `color` is not a colour `color` n’est pas une couleur # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Outil Angles Slide Anchor Along Path Faire glisser le point d’ancrage le long du tracé diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9c7cc7f8fc..81f9482631 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5933,6 +5933,13 @@ anchor Points: Pontok: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` adja meg: `inkLimit`, `removeWhiteOverprint` vagy `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first A nyomdai festékjavítások CMYK-dokumentumokon működnek: előbb válassza a Fájl › Dokumentum színmódja › CMYK-szín parancsot @msg `{key}` must be 0..{max} `{key}` értéke 0..{max} lehet +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Legközelebbi színminta keresése… + Find Nearest Swatch Legközelebbi színminta keresése + Apply Nearest Swatch Legközelebbi színminta alkalmazása + Select objects to find the swatches nearest their colors. Jelöljön ki objektumokat a színeikhez legközelebbi színminták megkereséséhez. +@msg select objects or give `color` jelöljön ki objektumokat, vagy adja meg ezt: `color` +@msg `color` is not a colour a(z) `color` nem szín # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Sarok eszköz Slide Anchor Along Path Horgonypont csúsztatása az útvonal mentén diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 8cd5905e90..89633ae991 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5845,6 +5845,13 @@ anchor Points: Titik: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` berikan `inkLimit`, `removeWhiteOverprint`, atau `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Perbaikan Tinta Cetak bekerja pada dokumen CMYK: pilih dulu Berkas › Mode warna dokumen › Warna CMYK @msg `{key}` must be 0..{max} `{key}` harus 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Cari Swatch Terdekat… + Find Nearest Swatch Cari Swatch Terdekat + Apply Nearest Swatch Terapkan Swatch Terdekat + Select objects to find the swatches nearest their colors. Pilih objek untuk menemukan swatch yang paling dekat dengan warnanya. +@msg select objects or give `color` pilih objek atau berikan `color` +@msg `color` is not a colour `color` bukan warna # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Alat sudut Slide Anchor Along Path Geser titik jangkar sepanjang jalur diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index aa17ab6748..6acfaf3c9a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5566,6 +5566,13 @@ anchor Points: Punti: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` indica `inkLimit`, `removeWhiteOverprint` o `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Le correzioni inchiostri di stampa funzionano nei documenti CMYK: scegli prima File › Metodo colore documento › Colore CMYK @msg `{key}` must be 0..{max} `{key}` deve essere 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Trova campione più vicino… + Find Nearest Swatch Trova campione più vicino + Apply Nearest Swatch Applica campione più vicino + Select objects to find the swatches nearest their colors. Seleziona gli oggetti per trovare i campioni più vicini ai loro colori. +@msg select objects or give `color` seleziona gli oggetti o indica `color` +@msg `color` is not a colour `color` non è un colore # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Strumento Angoli Slide Anchor Along Path Fai scorrere il punto di ancoraggio lungo il tracciato diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 62f6526f54..4bf3cd6bd1 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5633,6 +5633,13 @@ anchor Points: ポイント: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` `inkLimit`、`removeWhiteOverprint` または `overprintBlack` を指定してください @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first 印刷インキの修正は CMYK ドキュメントで使用できます。先にファイル › ドキュメントのカラーモード › CMYK カラーを選択してください @msg `{key}` must be 0..{max} `{key}` は 0..{max} にしてください +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… 最も近いスウォッチを検索… + Find Nearest Swatch 最も近いスウォッチを検索 + Apply Nearest Swatch 最も近いスウォッチを適用 + Select objects to find the swatches nearest their colors. カラーに最も近いスウォッチを探すオブジェクトを選択してください。 +@msg select objects or give `color` オブジェクトを選択するか `color` を指定してください +@msg `color` is not a colour `color` はカラーではありません # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool コーナーツール Slide Anchor Along Path パスに沿ってアンカーポイントをスライド diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index c8cc2bd053..cf411b072c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5936,6 +5936,13 @@ anchor Points: წერტილები: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` მიუთითეთ `inkLimit`, `removeWhiteOverprint` ან `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first საბეჭდი მელნის შესწორებები მუშაობს CMYK დოკუმენტებზე: ჯერ აირჩიეთ ფაილი › დოკუმენტის ფერის რეჟიმი › CMYK ფერი @msg `{key}` must be 0..{max} `{key}` უნდა იყოს 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… უახლოესი ფერის ნიმუშის პოვნა… + Find Nearest Swatch უახლოესი ფერის ნიმუშის პოვნა + Apply Nearest Swatch უახლოესი ფერის ნიმუშის გამოყენება + Select objects to find the swatches nearest their colors. აირჩიეთ ობიექტები მათ ფერებთან უახლოესი ფერის ნიმუშების საპოვნელად. +@msg select objects or give `color` აირჩიეთ ობიექტები ან მიუთითეთ `color` +@msg `color` is not a colour `color` ფერი არ არის # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool კუთხეების ხელსაწყო Slide Anchor Along Path საყრდენი წერტილის სრიალი ტრაექტორიაზე diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e38285e6d6..81f6c600c6 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5529,6 +5529,13 @@ anchor Points: 포인트: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` `inkLimit`, `removeWhiteOverprint` 또는 `overprintBlack`을 지정하십시오 @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first 인쇄 잉크 수정은 CMYK 문서에서 작동합니다. 먼저 파일 › 문서 색상 모드 › CMYK 색상을 선택하십시오 @msg `{key}` must be 0..{max} `{key}`은(는) 0..{max}이어야 합니다 +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… 가장 가까운 견본 찾기… + Find Nearest Swatch 가장 가까운 견본 찾기 + Apply Nearest Swatch 가장 가까운 견본 적용 + Select objects to find the swatches nearest their colors. 색상에 가장 가까운 견본을 찾을 개체를 선택하십시오. +@msg select objects or give `color` 개체를 선택하거나 `color`를 지정하십시오 +@msg `color` is not a colour `color`은(는) 색상이 아닙니다 # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool 모퉁이 도구 Slide Anchor Along Path 패스를 따라 앵커 포인트 밀기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 02694f7157..3448536832 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5889,6 +5889,13 @@ anchor Points: Punten: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` geef `inkLimit`, `removeWhiteOverprint` of `overprintBlack` op @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Drukinktcorrecties werken in CMYK-documenten: kies eerst Bestand › Documentkleurmodus › CMYK-kleur @msg `{key}` must be 0..{max} `{key}` moet 0..{max} zijn +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Dichtstbijzijnde staal zoeken… + Find Nearest Swatch Dichtstbijzijnde staal zoeken + Apply Nearest Swatch Dichtstbijzijnde staal toepassen + Select objects to find the swatches nearest their colors. Selecteer objecten om de stalen te vinden die het dichtst bij hun kleuren liggen. +@msg select objects or give `color` selecteer objecten of geef `color` op +@msg `color` is not a colour `color` is geen kleur # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Hoekengereedschap Slide Anchor Along Path Ankerpunt langs pad schuiven diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index a40dc3bf74..14825f83cf 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5801,6 +5801,13 @@ anchor Points: Punkty: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` podaj `inkLimit`, `removeWhiteOverprint` lub `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Poprawki farb drukarskich działają w dokumentach CMYK: najpierw wybierz Plik › Tryb koloru dokumentu › Kolor CMYK @msg `{key}` must be 0..{max} `{key}` musi wynosić 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Znajdź najbliższą próbkę… + Find Nearest Swatch Znajdź najbliższą próbkę + Apply Nearest Swatch Zastosuj najbliższą próbkę + Select objects to find the swatches nearest their colors. Zaznacz obiekty, aby znaleźć próbki najbliższe ich kolorom. +@msg select objects or give `color` zaznacz obiekty lub podaj `color` +@msg `color` is not a colour `color` nie jest kolorem # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Narzędzie Narożniki Slide Anchor Along Path Przesuń punkt kontrolny wzdłuż ścieżki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index fff027e8bf..96a31c3e57 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5864,6 +5864,13 @@ anchor Points: Pontos: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` informe `inkLimit`, `removeWhiteOverprint` ou `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first As Correções de Tinta para Impressão funcionam em documentos CMYK: escolha antes Arquivo › Modo de Cor do Documento › Cor CMYK @msg `{key}` must be 0..{max} `{key}` deve ser 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Localizar Amostra Mais Próxima… + Find Nearest Swatch Localizar Amostra Mais Próxima + Apply Nearest Swatch Aplicar Amostra Mais Próxima + Select objects to find the swatches nearest their colors. Selecione objetos para localizar as amostras mais próximas de suas cores. +@msg select objects or give `color` selecione objetos ou informe `color` +@msg `color` is not a colour `color` não é uma cor # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Ferramenta Cantos Slide Anchor Along Path Deslizar Ponto de Ancoragem pelo Caminho diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index bfe567e5e7..fdb51b80df 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5924,6 +5924,13 @@ anchor Points: Точки: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` задайте `inkLimit`, `removeWhiteOverprint` или `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Исправления печатных красок работают в документах CMYK: сначала выберите Файл › Цветовой режим документа › Цвет CMYK @msg `{key}` must be 0..{max} `{key}` должен быть 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Найти ближайший образец… + Find Nearest Swatch Найти ближайший образец + Apply Nearest Swatch Применить ближайший образец + Select objects to find the swatches nearest their colors. Выделите объекты, чтобы найти образцы, ближайшие к их цветам. +@msg select objects or give `color` выделите объекты или укажите `color` +@msg `color` is not a colour `color` не является цветом # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Инструмент «Углы» Slide Anchor Along Path Сдвинуть опорную точку вдоль контура diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 96598b23bc..e2dddf022b 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5999,6 +5999,13 @@ shape Open Öppen @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` ange `inkLimit`, `removeWhiteOverprint` eller `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Tryckfärgskorrigeringar fungerar i CMYK-dokument: välj först Fil › Dokumentets färgläge › CMYK-färg @msg `{key}` must be 0..{max} `{key}` måste vara 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Sök närmaste färgruta… + Find Nearest Swatch Sök närmaste färgruta + Apply Nearest Swatch Använd närmaste färgruta + Select objects to find the swatches nearest their colors. Markera objekt för att hitta de färgrutor som ligger närmast deras färger. +@msg select objects or give `color` markera objekt eller ange `color` +@msg `color` is not a colour `color` är ingen färg # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Hörnverktyget Slide Anchor Along Path Skjut ankarpunkt längs bana diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index bd09496235..9ecf2ccf93 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5904,6 +5904,13 @@ anchor Points: Noktalar: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` `inkLimit`, `removeWhiteOverprint` veya `overprintBlack` verin @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Baskı Mürekkebi Düzeltmeleri CMYK belgelerinde çalışır: önce Dosya › Belge Renk Modu › CMYK Rengi'ni seçin @msg `{key}` must be 0..{max} `{key}` 0..{max} olmalıdır +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… En Yakın Renk Örneğini Bul… + Find Nearest Swatch En Yakın Renk Örneğini Bul + Apply Nearest Swatch En Yakın Renk Örneğini Uygula + Select objects to find the swatches nearest their colors. Renklerine en yakın renk örneklerini bulmak için nesneleri seçin. +@msg select objects or give `color` nesneleri seçin veya `color` verin +@msg `color` is not a colour `color` bir renk değil # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Köşe Aracı Slide Anchor Along Path Bağlantı Noktasını Yol Boyunca Kaydır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 89f55871f0..d348440a2c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5546,6 +5546,13 @@ anchor Points: Точки: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` задайте `inkLimit`, `removeWhiteOverprint` або `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Виправлення друкарських фарб працюють у документах CMYK: спершу виберіть Файл › Колірний режим документа › Колір CMYK @msg `{key}` must be 0..{max} `{key}` має бути 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Знайти найближчий зразок… + Find Nearest Swatch Знайти найближчий зразок + Apply Nearest Swatch Застосувати найближчий зразок + Select objects to find the swatches nearest their colors. Виділіть об’єкти, щоб знайти зразки, найближчі до їхніх кольорів. +@msg select objects or give `color` виділіть об’єкти або вкажіть `color` +@msg `color` is not a colour `color` не є кольором # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Інструмент «Кути» Slide Anchor Along Path Зсунути опорну точку вздовж контуру diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 3fbcdf3169..09652ede2b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5549,6 +5549,13 @@ anchor Points: Điểm: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` hãy cho `inkLimit`, `removeWhiteOverprint` hoặc `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first Sửa mực in hoạt động trên tài liệu CMYK: trước hết chọn Tệp › Chế độ màu tài liệu › Màu CMYK @msg `{key}` must be 0..{max} `{key}` phải là 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… Tìm mẫu màu gần nhất… + Find Nearest Swatch Tìm mẫu màu gần nhất + Apply Nearest Swatch Áp dụng mẫu màu gần nhất + Select objects to find the swatches nearest their colors. Chọn đối tượng để tìm các mẫu màu gần nhất với màu của chúng. +@msg select objects or give `color` chọn đối tượng hoặc cung cấp `color` +@msg `color` is not a colour `color` không phải là màu # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool Công cụ Góc Slide Anchor Along Path Trượt điểm neo dọc đường dẫn diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 046fdde3c5..841bd4528a 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5790,6 +5790,13 @@ anchor Points: 点: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` 请指定 `inkLimit`、`removeWhiteOverprint` 或 `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first 印刷油墨修正适用于 CMYK 文档:请先选择 文件 › 文档颜色模式 › CMYK 颜色 @msg `{key}` must be 0..{max} `{key}` 必须为 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… 查找最接近的色板… + Find Nearest Swatch 查找最接近的色板 + Apply Nearest Swatch 应用最接近的色板 + Select objects to find the swatches nearest their colors. 选择对象以查找与其颜色最接近的色板。 +@msg select objects or give `color` 请选择对象或提供 `color` +@msg `color` is not a colour `color` 不是颜色 # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool 转角工具 Slide Anchor Along Path 沿路径滑动锚点 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index f414e61b6f..a515d59a74 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5586,6 +5586,13 @@ anchor Points: 點: @msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` 請指定 `inkLimit`、`removeWhiteOverprint` 或 `overprintBlack` @msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first 印刷油墨修正適用於 CMYK 文件:請先選擇 檔案 › 文件色彩模式 › CMYK 色彩 @msg `{key}` must be 0..{max} `{key}` 必須為 0..{max} +# Color Effects add-on: Find Nearest Swatch (Object › Plug-ins › Color Effects). + Find Nearest Swatch… 尋找最接近的色票… + Find Nearest Swatch 尋找最接近的色票 + Apply Nearest Swatch 套用最接近的色票 + Select objects to find the swatches nearest their colors. 選取物件以尋找與其顏色最接近的色票。 +@msg select objects or give `color` 請選取物件或提供 `color` +@msg `color` is not a colour `color` 不是顏色 # Path Precision Tools add-on: the Corner Tool and Slide Anchor Along Path. Corner Tool 轉角工具 Slide Anchor Along Path 沿路徑滑動錨點 diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 77dd67f447..07f601e5df 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -69,6 +69,7 @@ pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static st } "object.vectorHalftone" => (crate::dialogs::halftone::KIND, crate::dialogs::halftone::fields()), crate::addons::pathtools::dashes::COMMAND => (crate::addons::pathtools::dashes::KIND, crate::addons::pathtools::dashes::fields()), + crate::addons::color::nearest::COMMAND => (crate::addons::color::nearest::KIND, crate::addons::color::nearest::fields()), "artboard.rearrange" => (crate::dialogs::rearrange_artboards::KIND, crate::dialogs::rearrange_artboards::open_fields(app)), _ => return None, }) diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index 7e365aba0d..3c878633f3 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -17,7 +17,7 @@ use vectorcraft_doc::{Node, NodeId, NodeKind, TraceView}; use vectorcraft_engine::cmd::TracePresetChange; use vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES; -use super::{first_selected, library_panel, pstate, set_pstate, swatches}; +use super::{first_selected, pstate, set_pstate, swatches}; use crate::VectorcraftApp; use crate::widgets::{self, menu_item}; @@ -46,24 +46,6 @@ fn palette_label(id: &str) -> &'static str { } } -/// The name of Document Library's library `key` (the document's swatches or a swatch library); a -/// library that is gone shows its key. -fn library_label(app: &VectorcraftApp, key: &str) -> String { - match swatches::limit_name(app, key) { - Some(_) if key == DOCUMENT_SWATCHES => tl!(swatches::DOCUMENT_SWATCHES).to_string(), - Some(name) => library_panel::library_name(key, &name).to_string(), - None => key.to_string(), - } -} - -/// Document Library's choices: the document's swatches, then the colour libraries (`current` -/// checked) → the key chosen. -fn library_list(app: &VectorcraftApp, ui: &mut Ui, current: &str) -> Option<String> { - let document = menu_item(ui, swatches::DOCUMENT_SWATCHES, true, current == DOCUMENT_SWATCHES).then(|| DOCUMENT_SWATCHES.to_string()); - ui.separator(); - library_panel::library_items(ui, &swatches::colour_libraries(app), &|id| id == current).or(document) -} - /// Document Library's Colors choices with the document's swatches: All, then the document's color /// groups (`current` checked; `None` is All) → the choice, `Some(None)` for All. fn color_group_list(app: &VectorcraftApp, ui: &mut Ui, current: Option<&str>) -> Option<Option<String>> { @@ -656,7 +638,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.horizontal(|ui| { widgets::dim_label(ui, tl!("Library:")); let key = st.params["library"].as_str().unwrap_or(DOCUMENT_SWATCHES).to_string(); - if let Some(k) = widgets::combo(ui, "it-library", &library_label(app, &key), 170.0, |ui| library_list(app, ui, &key)) { + if let Some(k) = + widgets::combo(ui, "it-library", &swatches::library_label(app, &key), 170.0, |ui| swatches::library_list(app, ui, &key)) + { if k != DOCUMENT_SWATCHES { st.params["colorGroup"] = Value::Null; } diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index 0850bfefc5..d946d4bdc8 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -1,4 +1,5 @@ use super::*; +use crate::panels::library_panel; use egui::{Event, PointerButton, Pos2, Rect, vec2}; /// One headless frame of the panel (and its menu) with `events`: the texts drawn, with where. diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 2dd054f395..dc0a1bda5d 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -39,8 +39,8 @@ use dnd::drag_of; use dnd::highlighted; pub(crate) use dnd::{click_selection, drag_preview}; pub(crate) use libraries::{ - DOCUMENT_SWATCHES, SwatchLibraries, USER_SLOT, colour_libraries, limit_key, limit_name, load_library, open_library, other_library, user_library, - window_menu, + DOCUMENT_SWATCHES, SwatchLibraries, USER_SLOT, colour_libraries, library_label, library_list, limit_key, limit_name, load_library, open_library, + other_library, user_library, window_menu, }; #[cfg(test)] pub(crate) use tiles::describe; diff --git a/crates/ui-egui/src/panels/swatches/libraries.rs b/crates/ui-egui/src/panels/swatches/libraries.rs index f5b4d4fb68..c1053915aa 100644 --- a/crates/ui-egui/src/panels/swatches/libraries.rs +++ b/crates/ui-egui/src/panels/swatches/libraries.rs @@ -16,6 +16,24 @@ pub(crate) fn colour_libraries(app: &VectorcraftApp) -> Vec<LibraryRef> { library_refs(swatchlib::libraries(&app.session).into_iter().filter(|l| l.category != "gradients" && has_colours(&l.id)).collect()) } +/// The name of library choice `key` (the document's swatches or a swatch library, as Image +/// Trace's Document Library and Find Nearest Swatch pick one); a library that is gone shows its key. +pub(crate) fn library_label(app: &VectorcraftApp, key: &str) -> String { + match limit_name(app, key) { + Some(_) if key == swatchlib::DOCUMENT_SWATCHES => tl!(DOCUMENT_SWATCHES).to_string(), + Some(name) => library_panel::library_name(key, &name).to_string(), + None => key.to_string(), + } +} + +/// The library choices: the document's swatches, then the colour libraries (`current` checked) → +/// the key chosen. +pub(crate) fn library_list(app: &VectorcraftApp, ui: &mut Ui, current: &str) -> Option<String> { + let document = menu_item(ui, DOCUMENT_SWATCHES, true, current == swatchlib::DOCUMENT_SWATCHES).then(|| swatchlib::DOCUMENT_SWATCHES.to_string()); + ui.separator(); + library_panel::library_items(ui, &colour_libraries(app), &|id| id == current).or(document) +} + /// What Limit to Library menus call the document's own swatches ([`swatchlib::DOCUMENT_SWATCHES`]). pub(crate) const DOCUMENT_SWATCHES: &str = "Document Swatches"; diff --git a/docs/mcp.md b/docs/mcp.md index dcfe46e532..fa8e05fab3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6385,6 +6385,30 @@ one, out of range values and a request with no fix on. {"name":"run_command","arguments":{"command":"addon.color.printFixes","params":{"scope":"document","inkLimit":300,"removeWhiteOverprint":true,"overprintBlack":100}}} ``` +### Find Nearest Swatch + +`addon.color.nearestSwatch {library?, color?, fill?, stroke?, count?, ids?}` (a query: no undo step) lists, for each +colour of the selected objects, the colour swatches of a library closest to it, closest first, by CIEDE2000 difference +(`deltaE`: under 1 hardly tells apart, about 2 to 3 close) (#4923). `library` is a swatch library's id or name, as +`swatch.library.list` lists them: the built-in ones, and the libraries and colour books (`.acb`, `.ase`, `.gpl`) the +user saved or loaded with `swatch.library.load`; `"document"` (the default) is the document's own swatches. The colours +are the solid colours and gradient stops of the selection's fills (`fill`, true) and strokes (`stroke`, true), of the +objects inside it and of its type, once each, the first 100; `color` looks one colour up instead. `count` is 1…50 (5). +Tint swatches, None and Registration aren't matched. → `{library, colors: [{values, hex, matches: [{name, values, hex, +spot, deltaE}]}]}` (`values` as a default swatch name reads them: `C=10 M=20 Y=30 K=0`, `R=255 G=128 B=0`…) + +`addon.color.applyNearestSwatch {library?, fill?, stroke?, ids?}` (Object › Plug-ins › Color Effects › Find Nearest +Swatch…, whose dialog lists each colour's three closest swatches with their difference; Apply runs it) gives each solid +colour and gradient stop of the selected objects' fills and strokes (and gradient meshes) the colour of its nearest +swatch, as one undo step. A global or spot swatch's colour links to it. The library's swatches the colours take are +added to the document's first, as `swatch.library.add` adds them, so a spot colour from a colour book stays spot; +images and patterns keep their colours. → `{changed, swatches: [the document swatches the colours took], added}` + +```json +{"name":"run_command","arguments":{"command":"addon.color.nearestSwatch","params":{"library":"web-safe-216","color":{"c":10,"m":80,"y":90,"k":0},"count":3}}} +{"name":"run_command","arguments":{"command":"addon.color.applyNearestSwatch","params":{"library":"document","stroke":false}}} +``` + ## Arrange Tools add-on Arrange Tools is a built-in add-on that lays out, swaps, replaces and sizes selected objects: its commands are diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9bfa5a1af3..953e3e65a4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Path Precision Tools add-on: Expand Dashes into Paths, #4922; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Color Effects add-on: Find Nearest Swatch, #4923; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -1460,10 +1460,15 @@ Symbols area (#4938), from the public symbol documentation ([create and place sy A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Document Tools › Export All Open Documents as PDF (or as SVG) asks for a folder and writes a copy of every open document there, each named after its document with `-2`, `-3`… added when a name is taken, so no file is replaced (`addon.document.exportAllOpen {folder, format?}`, #4920). Each copy is written as Save a Copy writes it: the documents keep their paths, titles and modified state, and the active one stays active. A document that can't be written is named in the status bar and the others are still written. Tests: `addons::document::tests::export_all_open_documents_writes_each_to_the_folder_picked` (ui-egui), `cmd::addons::document::tests::export_all_open_documents_writes_each_and_reports_failures` (engine). +## Color Effects add-on: Find Nearest Swatch (2026-11-01) + +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Color Effects › Find Nearest Swatch… lists each colour of the selection (fills and strokes, as ticked; solid colours and gradient stops, inside groups and type) with the three swatches of the chosen library closest to it by CIEDE2000 difference, with that difference (`addon.color.nearestSwatch`, #4923). The library is the document's swatches, a built-in library, or a library or colour book the user saved or loaded (no colour book data ships with VectorCraft). Apply gives each colour its nearest swatch as one undo step (`addon.color.applyNearestSwatch`): global and spot swatches link, and a library's swatches the colours take are added to the document first, so a spot colour stays spot. Remaining: typing a colour to look up in the dialog (the command takes `color`), and applying a match other than the nearest. Tests: `cmd::addons::color::nearest::tests` (engine), `addons::color::nearest::tests::find_nearest_swatch_lists_the_matches_and_applies_the_nearest` (ui-egui). + ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Color Effects add-on (a VectorCraft addition): Find Nearest Swatch (#4923); evidence added; scores unchanged. | | 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): Export All Open Documents as PDF or SVG (#4920); evidence added; scores unchanged. | | 2026-11-01 | minor | Path Precision Tools add-on (a VectorCraft addition): Expand Dashes into Paths (#4922); evidence added; scores unchanged. | | 2026-11-01 | minor | Type core: the Glyphs panel highlights the character selected with the Type tool and scrolls it into view (#4908); evidence added; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3c618c46bb..89ea9b36a8 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Artboards panel: drag a row to reorder the artboards, #4687) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Color Effects add-on: Find Nearest Swatch, #4923) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -352,6 +352,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Artwork Cleanup add-on (VectorCraft addition): Object › Plug-ins › Artwork Cleanup opens its panel, which checks the selection or the document for 16 kinds of issue, lists them with counts, and shows or fixes the picked rows or all of them, each fix one undo step; Simplify Anchors (Keep Shape), Rejoin Path Pieces and Deep Ungroup open their options first | done | `addon.cleanup.*`, `crates/ui-egui/src/addons/cleanup.rs` and its tests; not a feature of the reference app, so it is not scored | | Artwork Cleanup add-on text tools (VectorCraft addition): the panel's Text row, which the panel can hide, and Object › Plug-ins › Artwork Cleanup set the alignment of point type keeping its place, break type into lines (Shift-click: paragraphs), words or glyphs, split type at the cursor, reset a text transform (Alt-click: and its horizontal scale), combine point type, remove line or paragraph breaks and replace missing fonts, each one undo step | done | `addon.cleanup.*` text commands, `crates/ui-egui/src/addons/cleanup.rs` and its tests; a VectorCraft addition, so it is not scored | | Color Effects add-on (VectorCraft addition): live Exposure, Desaturate and Invert Colors in Effect › Color Effects and Object › Plug-ins › Color Effects; its panel picks a colour adjustment and its values and adds it as a live effect or applies it as a filter, into the colours, as one undo step; Select by Color Kind selects the objects that use spot colours, carry colour effects, or are RGB, CMYK or grayscale images; Vector Halftone draws an object as halftone dots live (the dots Object › Vector Halftone makes), which Expand Appearance and the exporters write as paths; Duotone prints each colour's tone with one to four inks (a tint of a spot tone's swatch, or the CMYK mix of several), live or as a filter, its dialog a row per tone and the picked tone's curve; Print Ink Fixes (a CMYK document's ink limit, white overprint removed, black overprint set) opens its options from the submenu and the panel's Inks | done | `addon.color.*`, `crates/ui-egui/src/addons/color.rs` and its tests; not a feature of the reference app, so it is not scored | +| Color Effects add-on (VectorCraft addition): Object › Plug-ins › Color Effects › Find Nearest Swatch… picks a Library (Document Swatches, a built-in library, or a library or colour book the user saved or loaded) and Fill and Stroke, lists each colour of the selection with its three closest swatches (chip, name, ΔE 2000), and Apply gives each colour its nearest swatch (global and spot swatches linked; a library's swatches added to the document first), one undo step | done | #4923; `addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, `crates/engine/src/cmd/addons/color/nearest.rs`, `crates/ui-egui/src/addons/color/nearest.rs` and their tests; not a feature of the reference app, so it is not scored | ## Look and feel @@ -394,6 +395,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Color Effects add-on (a VectorCraft addition): Find Nearest Swatch (#4923); scores and estimates unchanged | | 2026-11-01 | minor | Artboards panel: a row dragged above or below another reorders the artboards (#4687); scores and estimates unchanged | | 2026-11-01 | minor | Document Tools add-on (a VectorCraft addition): Export All Open Documents as PDF or SVG (#4920); scores and estimates unchanged | | 2026-11-01 | minor | Path Precision Tools add-on (a VectorCraft addition): Expand Dashes into Paths (#4922); scores and estimates unchanged | From 05d5f99fd7e7dc00db3a9754d594b1214945d855 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:55:12 +0100 Subject: [PATCH 260/260] ci: run the desktop printing check through the shared gate (#5062) * ci: run the desktop printing check through the shared gate print.yml ran its own Windows job, which the CI workflow rules phase out, and each PR saved its own ~1.3 GB cache. The same commands now run through craft-common-actions' gate.yml on windows-2022, without craft-fonts, nextest or the wasm target as before. The gate never saves from a pull request; a manual run on main seeds the cache. storytold/craft-common-actions#118. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * ci: call the shared gate at main storytold/craft-common-actions#119 is merged, so main's gate takes an empty packages list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: FredApps <FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- .github/workflows/print.yml | 44 ++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/.github/workflows/print.yml b/.github/workflows/print.yml index 400a819442..058705ce29 100644 --- a/.github/workflows/print.yml +++ b/.github/workflows/print.yml @@ -13,27 +13,27 @@ on: workflow_dispatch: permissions: contents: read -env: - CARGO_TERM_COLOR: always - CARGO_INCREMENTAL: 0 +# A newer push to a PR branch cancels its older run. +concurrency: + group: print-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: + # Desktop printing on Windows, through the suite's shared gate. Pull requests restore the cache + # but never save one; a manual run on main saves the cache they restore. windows: - runs-on: windows-2022 - timeout-minutes: 90 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: dtolnay/rust-toolchain@e2a55d2ffb04f378e9626c28d38b36d230d1e12f # master - with: - toolchain: stable - components: clippy - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - with: - key: desktop-print - - run: cargo clippy --locked -p vectorcraft --all-targets -- -D warnings - - run: cargo test --locked -p vectorcraft - - name: Check pending submission and queue refusal feedback - shell: bash - # A filter that matches nothing still passes, so fail unless some test ran. - run: | - cargo test --locked -p vectorcraft-ui-egui --lib -- tests::printps | tee printps.log - grep -Eq 'test result: ok\. [1-9][0-9]* passed' printps.log || { echo "::error::tests::printps matched no tests"; exit 1; } + # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["windows-2022"]' + timeout-minutes: 90 + # As before: printing builds and tests without craft-fonts, nextest or the wasm target. + craft-fonts-ref: "" + tools: "" + targets: "" + # A filter that matches nothing still passes, so the printps run fails unless some test ran. + command: | + cargo clippy --locked -p vectorcraft --all-targets -- -D warnings + cargo test --locked -p vectorcraft + log="$RUNNER_TEMP/printps.log" + cargo test --locked -p vectorcraft-ui-egui --lib -- tests::printps | tee "$log" + grep -Eq 'test result: ok\. [1-9][0-9]* passed' "$log" || { echo "::error::tests::printps matched no tests"; exit 1; }