From 620c07848b16db4773f28ccc6b566be19935d94c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 03:02:49 -0800 Subject: [PATCH 01/33] Plug-ins: Preferences set the instruction budget for object-filter runs (Normal or Large) Preferences > Plug-ins & Scratch Disks > Plug-in Instruction Budget (`pluginInstructionBudget`) is a VectorCraft setting. Normal, the default, keeps the limits a filter run has today. Large gives each object filter run 250 M instructions plus 4,000 per input byte, with the 60 s time budget, Cancel and the other limits unchanged. An approved heavy filter keeps its 1 G and 300 s with either value; live effects, exporters and importers keep their own budgets. The next run of an installed filter uses the value in force when the run is prepared. prefs.set refuses any value but normal or large; a saved preferences file with another value reads as Normal and the other preferences load as saved. Docs: docs/plugins.md, docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/plugin.rs | 18 ++++++-- crates/engine/src/cmd/prefscmds.rs | 8 ++++ crates/engine/src/lib.rs | 2 +- crates/engine/src/prefs.rs | 26 ++++++++++++ crates/engine/src/tests/plugins.rs | 53 ++++++++++++++++++++++++ crates/engine/src/tests/prefs.rs | 32 ++++++++++++++ crates/plugins/src/lib.rs | 2 +- crates/plugins/src/runtime.rs | 11 +++++ crates/plugins/tests/abi.rs | 19 ++++++++- 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/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.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/prefs_dialog/tests.rs | 23 ++++++++++ docs/mcp.md | 5 +++ docs/plugins.md | 18 +++++++- docs/target-app-parity.md | 1 + 41 files changed, 239 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 48a6649d77..5570dc6a81 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -161,6 +161,8 @@ pub struct FilterRun { parent: Option, /// The document it was made from, and that document's revision then. document: (u64, u64), + /// The plug-in's limits with the Plug-in Instruction Budget in force when it was made. + limits: vectorcraft_plugins::Limits, } /// A filter's output handed in by a [`FilterRun`] made away from `plugin.run`, with what the run @@ -245,7 +247,11 @@ impl FilterRun { let capacity = (plugin.limits().max_memory_bytes / 2).min(i32::MAX as usize).saturating_sub(params.len()); let (input, read_only) = objects::encode_input_with(&st.doc, &inputs, &kinds, capacity).map_err(err)?; let document = (st.uid, st.revision); - Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document }) + let limits = match s.prefs.plugin_instruction_budget { + crate::PluginBudget::Normal => plugin.limits().clone(), + crate::PluginBudget::Large => plugin.large_limits(), + }; + Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document, limits }) } /// The plug-in, for its name and budget. @@ -274,7 +280,13 @@ impl FilterRun { /// can run on any thread; inside a [`vectorcraft_doc::cancel::scope`] Cancel stops it between /// two slices of its budget. pub fn run(&self) -> Result> { - self.plugin.run(&self.input, &self.params).map_err(err) + self.plugin.run_limited(&self.input, &self.params, &self.limits).map_err(err) + } + + /// The limits it runs under: the plug-in's, with the Plug-in Instruction Budget in force when + /// it was made. + pub fn limits(&self) -> &vectorcraft_plugins::Limits { + &self.limits } /// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the @@ -289,7 +301,7 @@ impl FilterRun { let may = self.plugin.manifest().permissions(); let calls = super::plugin_call::Calls::of(s, may.contains(&Permission::DocRead), may.contains(&Permission::DocWrite)); let mut bridge = |id: &str, args: &Value| super::plugin_call::call(s, &calls, id, args); - self.plugin.run_calling(&self.input, &self.params, self.plugin.limits(), &mut bridge).0.map_err(err) + self.plugin.run_calling(&self.input, &self.params, &self.limits, &mut bridge).0.map_err(err) } /// Runs a plug-in that calls commands and applies its output: the calls and the output are one diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index b6c500749f..7f1a5ae0c1 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -320,6 +320,14 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("hyphenationExceptions", "Hyphenation", "", "Exceptions (comma separated)", text), // Plug-ins & Scratch Disks p!("pluginsFolder", "Plug-ins & Scratch Disks", "Plug-ins", "Additional Plug-ins Folder", text), + // The instructions each object filter run gets: Large gives at least 250 M besides those for each byte of input. + p!( + "pluginInstructionBudget", + "Plug-ins & Scratch Disks", + "Plug-ins", + "Plug-in Instruction Budget", + choice(&[("normal", "Normal"), ("large", "Large")]) + ), p!("scratchPrimary", "Plug-ins & Scratch Disks", "Scratch Disks", "Primary", text), p!("scratchSecondary", "Plug-ins & Scratch Disks", "Scratch Disks", "Secondary", text), // User Interface diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4f7532108d..a2ac06a280 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -411,7 +411,7 @@ use history::history_budget_for; pub use history::{History, HistoryEntry, NamedStep, default_history_budget}; pub(crate) use interaction::PreviewCopies; pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope}; -pub use prefs::{DrawMode, Prefs}; +pub use prefs::{DrawMode, PluginBudget, Prefs}; pub use sanity::TOO_DEEP; pub(crate) use sanity::{deselect_hidden, is_guide_path}; #[cfg(test)] diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 86525e9214..a47b71cb5d 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -10,6 +10,26 @@ pub enum DrawMode { Inside, } +/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: the instructions an object filter's run +/// may use ([`vectorcraft_plugins::Plugin::large_limits`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "lowercase")] +pub enum PluginBudget { + /// The plug-in's own limits. + #[default] + Normal, + /// At least [`vectorcraft_plugins::LARGE_FUEL`] instructions besides those for each byte of + /// input; the time budget is unchanged. + Large, +} + +/// A saved Plug-in Instruction Budget: any value but `large`, of any type, reads as Normal, and the +/// other preferences are read as they are. +fn plugin_budget<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { + let saved = ::deserialize(d)?; + Ok(if saved.as_str() == Some("large") { PluginBudget::Large } else { PluginBudget::Normal }) +} + /// A saved Default Language as its tag: older preferences hold the language's name, and one the list /// no longer has reads as the default. fn language_tag<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { @@ -173,6 +193,11 @@ pub struct Prefs { pub fonts_folder: String, // Plug-ins & Scratch Disks pub plugins_folder: String, + /// Plug-in Instruction Budget: the instructions each object filter run gets, from + /// `plugin.run`, a plug-in command and the app alike. Live effects, exporters and importers + /// keep their own budgets. + #[serde(deserialize_with = "plugin_budget")] + pub plugin_instruction_budget: PluginBudget, pub scratch_primary: String, pub scratch_secondary: String, // User Interface @@ -485,6 +510,7 @@ impl Default for Prefs { hyphenation_exceptions: String::new(), fonts_folder: String::new(), plugins_folder: String::new(), + plugin_instruction_budget: PluginBudget::Normal, scratch_primary: s("Startup"), scratch_secondary: s("None"), ui_brightness: s("mediumDark"), diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 1572004d11..037fb83a1c 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4414,6 +4414,59 @@ fn a_cancelled_filter_run_changes_nothing() { assert_eq!(s.doc().unwrap().doc, before); } +/// Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget: with Normal a light filter +/// runs out of instructions and changes nothing; with Large the same installed filter finishes, as +/// one undo step, without being installed again. The time budget, Cancel and a heavy filter's +/// larger budget stay as they are, and setting Normal again applies to the next run. +#[test] +fn the_plugin_instruction_budget_preference_sets_a_filter_run_s_instructions() { + use cmd::plugin::FilterRun; + let mut s = session(); + let id = "test.engine.largebudget"; + let output = json!({"objects": [{"path": triangle(), "name": "Plug-in"}]}).to_string(); + // More steps than a light budget pays for, fewer than 5 times it. + install_wat(&mut s, &tpl::spinning(&tpl::manifest(id, "filter", "{}"), 20_000_000, &output)); + let p = json!({"id": id, "ids": []}); + let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let e = s.execute("plugin.run", &p).unwrap_err().to_string(); + assert!(e.contains("instruction budget"), "{e}"); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo)); + + run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": "large"})); + let light = vectorcraft_plugins::Limits::default(); + let large = FilterRun::prepare(&s, &p).unwrap().limits().clone(); + assert_eq!(large, vectorcraft_plugins::Limits { fuel_base: vectorcraft_plugins::LARGE_FUEL, ..light.clone() }); + assert_eq!((large.fuel_per_byte, large.wall_time_ms), (light.fuel_per_byte, light.wall_time_ms)); + // Cancel still stops it, and it changes nothing. + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + let r = vectorcraft_doc::cancel::scope(&token, None, || s.execute("plugin.run", &p)); + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo)); + let made = run(&mut s, "plugin.run", p.clone())["ids"].clone(); + assert_eq!(made.as_array().map(Vec::len), Some(1)); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + + // A heavy filter keeps its larger budget with either choice. + let heavy_id = "test.engine.largebudget.heavy"; + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&heavy(heavy_id, 1)), "allowHeavy": true})); + let hp = json!({"id": heavy_id, "ids": []}); + for budget in ["large", "normal"] { + run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": budget})); + let limits = FilterRun::prepare(&s, &hp).unwrap().limits().clone(); + let heavy_limits = (vectorcraft_plugins::HEAVY_FUEL, vectorcraft_plugins::HEAVY_WALL_TIME_MS); + assert_eq!((limits.fuel_base, limits.wall_time_ms), heavy_limits, "{budget}"); + } + + // Normal again: the next run runs out of instructions. + let undo = s.doc().unwrap().history.undo.len(); + let e = s.execute("plugin.run", &p).unwrap_err().to_string(); + assert!(e.contains("instruction budget"), "{e}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + run(&mut s, "plugin.remove", json!({"id": id})); + run(&mut s, "plugin.remove", json!({"id": heavy_id})); +} + /// The manifest of a filter `id` named "Cmd Test" of `kind` with `commands` (a JSON list). fn with_commands(id: &str, kind: &str, commands: &str) -> String { format!(r#"{{"id":"{id}","name":"Cmd Test","version":"1","kind":"{kind}","commands":{commands}}}"#) diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 521d2eabde..eb089b1993 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -447,6 +447,38 @@ fn gpu_preference_defaults_to_automatic_and_validates() { assert_eq!(s.prefs.gpu_preference, "automatic"); } +/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: Normal by default, Large by value or +/// label, kept through a save and load, and reset with its category. Setting another value is an +/// error that changes nothing; a saved value that is missing, unknown or of another type reads as +/// Normal and leaves the other saved preferences as they are. +#[test] +fn plugin_instruction_budget_defaults_to_normal_and_validates() { + let mut s = Session::new(); + assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal); + assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("normal")); + set_pref(&mut s, "pluginInstructionBudget", json!("Large")); + assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large); + assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("large")); + for bad in [json!("unlimited"), json!(""), json!(5), json!(null), json!(true), json!(["large"])] { + assert!(s.execute("prefs.set", &json!({"key": "pluginInstructionBudget", "value": bad})).is_err(), "{bad}"); + assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large, "{bad}"); + } + let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap(); + assert_eq!(back.plugin_instruction_budget, PluginBudget::Large); + let other_values = [json!("unlimited"), json!(5), json!(null), json!(["large"]), json!({"large": true}), json!("LARGE")]; + let saved_files = other_values.map(|v| json!({"keyboardIncrement": 4, "pluginInstructionBudget": v})); + for saved in std::iter::once(json!({"keyboardIncrement": 4})).chain(saved_files) { + let read: Prefs = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!((read.plugin_instruction_budget, read.keyboard_increment), (PluginBudget::Normal, 4.0), "{saved}"); + } + let l = s.execute("prefs.list", &json!({})).unwrap(); + let row = l.as_array().unwrap().iter().find(|e| e["key"] == "pluginInstructionBudget").unwrap().clone(); + assert_eq!((row["category"].as_str(), row["section"].as_str()), (Some("Plug-ins & Scratch Disks"), Some("Plug-ins"))); + assert_eq!((&row["options"], &row["value"]), (&json!(["normal", "large"]), &json!("large"))); + s.execute("prefs.reset", &json!({"category": "Plug-ins & Scratch Disks"})).unwrap(); + assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal); +} + /// Performance › Linux Display Server (#1151): automatic by default, X11 by value or label, and /// anything else is an error that changes nothing. #[test] diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index b304e1721e..019dd0d858 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -53,7 +53,7 @@ pub mod wat; pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec}; -pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Limits, Plugin, heavy_terms}; +pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; #[doc(hidden)] pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE}; diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 5a2db2ff0d..0cb6197e97 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -35,6 +35,11 @@ pub const HEAVY_FUEL: u64 = 1_000_000_000; /// Wall-clock budget of a heavy filter's run, in milliseconds. pub const HEAVY_WALL_TIME_MS: u64 = 300_000; +/// Instructions a filter's run may use besides [`Limits::fuel_per_byte`] for each byte of input +/// when Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget is Large +/// ([`Plugin::large_limits`]): 5 times the default. +pub const LARGE_FUEL: u64 = 250_000_000; + /// The limit a run reports when its input and parameters together are past half its memory. pub(crate) const SELECTION_TOO_LARGE: &str = "memory budget (the selection is too large to hand over)"; @@ -215,6 +220,12 @@ impl Plugin { pub fn limits(&self) -> &Limits { &self.limits } + /// Its limits with the Large instruction budget: at least [`LARGE_FUEL`] instructions besides + /// those for each byte of input, and every other limit, the time budget included, as it is. A + /// heavy filter keeps its larger budget. + pub fn large_limits(&self) -> Limits { + Limits { fuel_base: self.limits.fuel_base.max(LARGE_FUEL), ..self.limits.clone() } + } /// Module size in bytes. pub fn size(&self) -> usize { self.size diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index abc2cd05eb..26dec0a7d2 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -7,7 +7,7 @@ use std::time::{Duration, Instant}; use serde_json::{Value, json}; use vectorcraft_plugins::storage::{Meter, Storage, StorageError}; -use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, Limits, Plugin, Report, heavy_terms, registry, wat as tpl}; +use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, LARGE_FUEL, Limits, Plugin, Report, heavy_terms, registry, wat as tpl}; /// The example Desaturate plug-in, built from `crates/plugins/example`. const DESATURATE: &[u8] = include_bytes!("fixtures/desaturate.wasm"); @@ -259,6 +259,23 @@ fn a_heavy_filter_finishes_what_a_light_one_cannot() { assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes()); } +/// The Large instruction budget gives a light filter 5 times the instructions besides those for +/// each byte of input, so it finishes 20 million steps of a loop that its own budget can't, in the +/// same time budget. A heavy filter keeps its larger budget, and every other limit stays. +#[test] +fn the_large_budget_finishes_what_a_light_one_cannot_and_keeps_a_heavy_one() { + let light = Plugin::load(&build(&tpl::spinning(MANIFEST, 20_000_000, INPUT)), Limits::default()).unwrap(); + assert_eq!(light.run(INPUT.as_bytes(), b"{}"), Err(Error::Limit("instruction budget".into()))); + let large = light.large_limits(); + assert_eq!(large, Limits { fuel_base: LARGE_FUEL, ..Limits::default() }); + assert_eq!(LARGE_FUEL, 5 * Limits::default().fuel_base); + assert_eq!(light.run_limited(INPUT.as_bytes(), b"{}", &large).unwrap(), INPUT.as_bytes()); + let heavy = r#"{"id":"test.heavy","name":"Heavy","version":"1","kind":"filter","budget":"heavy"}"#; + let heavy = Plugin::load(&build(&tpl::spinning(heavy, 1, INPUT)), Limits::default()).unwrap(); + assert_eq!(heavy.large_limits(), *heavy.limits()); + assert_eq!((heavy.large_limits().fuel_base, heavy.large_limits().wall_time_ms), (HEAVY_FUEL, HEAVY_WALL_TIME_MS)); +} + #[test] fn an_exporter_returns_its_file_with_an_export_s_budget() { use vectorcraft_plugins::export::{self, Target}; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 71e443a399..98defa52fa 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -126,6 +126,7 @@ Add to Swatches Добавяне към образци Add Used Colors Добавяне на използваните цветове Additional Plug-ins Folder Допълнителна папка за плъгини + Plug-in Instruction Budget Бюджет на инструкции за плъгини Additional Fonts Folder Допълнителна папка за шрифтове Adjust Adjoining Width Points Регулиране на прилежащите точки за ширина Adjust Color Balance… Коригиране на цветовия баланс… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 883d6dd387..5e774a17fb 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3856,6 +3856,7 @@ theme Appearance Izgled 90° & 45° Angles Uglovi od 90° i 45° 90° Angles Uglovi od 90° Additional Plug-ins Folder Dodatni folder dodataka + Plug-in Instruction Budget Budžet instrukcija za dodatke Additional Fonts Folder Dodatni folder fontova Alignment Guides Vodilice za poravnanje Anchor Points, Handle, and Bounding Box Display Prikaz sidrenih tačaka, ručki i graničnog okvira diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..255567aa2b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -222,6 +222,7 @@ Add Used Colors Afegeix els colors utilitzats Additional Fonts Folder Carpeta addicional de tipus de lletra Additional Plug-ins Folder Carpeta addicional de complements + Plug-in Instruction Budget Pressupost d’instruccions dels complements Adjust Adjoining Width Points Ajusta els punts d’amplada contigus Adjust Color Balance… Ajusta l’equilibri de color… Adjust Colors Ajusta els colors diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..0de0d8bbf9 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3959,6 +3959,7 @@ theme Appearance Motiv 90° & 45° Angles Úhly 90° a 45° 90° Angles Úhly 90° Additional Plug-ins Folder Další složka zásuvných modulů + Plug-in Instruction Budget Rozpočet instrukcí zásuvných modulů Additional Fonts Folder Další složka písem Alignment Guides Vodítka zarovnání Anchor Points, Handle, and Bounding Box Display Zobrazení kotevních bodů, úchytů a ohraničovacího rámečku diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..1cd1b5f5b5 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6356,6 +6356,7 @@ theme Appearance Udseende 90° & 45° Angles 90° & 45°-vinkler 90° Angles 90°-vinkler Additional Plug-ins Folder Yderligere mappe med plug-ins + Plug-in Instruction Budget Instruktionsbudget for plug-ins Additional Fonts Folder Yderligere mappe med skrifttyper Alignment Guides Justeringshjælpelinjer Anchor Points, Handle, and Bounding Box Display Visning af ankerpunkter, håndtag og afgrænsningsboks diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..02b3339693 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -115,6 +115,7 @@ Add to Swatches Zu Farbfeldern hinzufügen Add Used Colors Verwendete Farben hinzufügen Additional Plug-ins Folder Zusätzlicher Plug-in-Ordner + Plug-in Instruction Budget Anweisungsbudget für Plug-ins Additional Fonts Folder Zusätzlicher Schriftenordner Adjust Adjoining Width Points Angrenzende Breitenpunkte anpassen Adjust Color Balance… Farbbalance anpassen… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..5cf4fa65bf 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -120,6 +120,7 @@ Add to Swatches Προσθήκη στα δείγματα χρωμάτων Add Used Colors Προσθήκη των χρησιμοποιημένων χρωμάτων Additional Plug-ins Folder Πρόσθετος φάκελος επεκτάσεων + Plug-in Instruction Budget Προϋπολογισμός εντολών επεκτάσεων Additional Fonts Folder Πρόσθετος φάκελος γραμματοσειρών Adjust Adjoining Width Points Ρύθμιση γειτονικών σημείων πλάτους Adjust Color Balance… Ρύθμιση ισορροπίας χρωμάτων… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..b5f74cbbab 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -140,6 +140,7 @@ Add to Swatches Agregar a muestras Add Used Colors Agregar colores usados Additional Plug-ins Folder Carpeta de plugins adicionales + Plug-in Instruction Budget Presupuesto de instrucciones de plugins Additional Fonts Folder Carpeta de fuentes adicionales Adjust Adjoining Width Points Ajustar puntos de anchura contiguos Adjust Color Balance… Ajustar equilibrio de color… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..b50cb96d67 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3897,6 +3897,7 @@ theme Appearance Ulkoasu 90° & 45° Angles 90° ja 45° kulmat 90° Angles 90° kulmat Additional Plug-ins Folder Lisälaajennusten kansio + Plug-in Instruction Budget Laajennusten käskybudjetti Additional Fonts Folder Lisäfonttien kansio Alignment Guides Tasausapuviivat Anchor Points, Handle, and Bounding Box Display Ankkuripisteiden, kahvojen ja rajausruudun näyttö diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8af602785b..bfaa0d577f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -141,6 +141,7 @@ Add to Swatches Ajouter au nuancier Add Used Colors Ajouter les couleurs utilisées Additional Plug-ins Folder Dossier de modules externes supplémentaires + Plug-in Instruction Budget Budget d’instructions des modules externes Additional Fonts Folder Dossier de polices supplémentaires Adjust Adjoining Width Points Ajuster les points de largeur adjacents Adjust Color Balance… Régler la balance des couleurs… diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..ce48ab0bec 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -163,6 +163,7 @@ Add to the Current Shortcuts વર્તમાન શૉર્ટકટમાં ઉમેરો Additional Fonts Folder વધારાનું ફોન્ટ ફોલ્ડર Additional Plug-ins Folder વધારાનું પ્લગ-ઇન ફોલ્ડર + Plug-in Instruction Budget પ્લગ-ઇન સૂચના બજેટ Adjust Adjoining Width Points અડીને આવેલા પહોળાઈ બિંદુઓ ગોઠવો Adjust Color Balance… રંગ બૅલેન્સ ગોઠવો… Adjust Colors રંગ ગોઠવો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..ca59b6b956 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -256,6 +256,7 @@ Add Used Colors उपयोग किए रंग जोड़ें Additional Fonts Folder अतिरिक्त फ़ॉन्ट फ़ोल्डर Additional Plug-ins Folder अतिरिक्त प्लग-इन फ़ोल्डर + Plug-in Instruction Budget प्लग-इन निर्देश बजट Adjust Adjoining Width Points सटे हुए चौड़ाई पॉइंट समायोजित करें Adjust Color Balance… कलर बैलेंस समायोजित करें… Adjust Colors रंग समायोजित करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..86b9fafb5c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -210,6 +210,7 @@ Add Used Colors Használt színek hozzáadása Additional Fonts Folder További betűtípusok mappája Additional Plug-ins Folder További bővítmények mappája + Plug-in Instruction Budget Bővítmények utasításkerete Adjust Adjoining Width Points Szomszédos szélességi pontok igazítása Adjust Color Balance… Színegyensúly beállítása… Adjust Colors Színek beállítása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5f865e69b..919f3aa92c 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3633,6 +3633,7 @@ theme Appearance Tampilan 90° & 45° Angles Sudut 90° & 45° 90° Angles Sudut 90° Additional Plug-ins Folder Folder plug-in tambahan + Plug-in Instruction Budget Anggaran instruksi plug-in Additional Fonts Folder Folder font tambahan Alignment Guides Panduan perataan Anchor Points, Handle, and Bounding Box Display Tampilan titik jangkar, pegangan, dan kotak pembatas diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..524fd54da5 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -140,6 +140,7 @@ Add to Swatches Aggiungi ai campioni Add Used Colors Aggiungi colori usati Additional Plug-ins Folder Cartella plug-in aggiuntivi + Plug-in Instruction Budget Budget di istruzioni dei plug-in Additional Fonts Folder Cartella font aggiuntivi Adjust Adjoining Width Points Regola punti di larghezza adiacenti Adjust Color Balance… Regola bilanciamento colore… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..6cf6c34c50 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1069,6 +1069,7 @@ digits Malayalam マラヤーラム数字 Add to Selection 選択範囲に追加 Add to Swatches スウォッチに追加 Additional Plug-ins Folder 追加プラグインフォルダー + Plug-in Instruction Budget プラグインの命令予算 Additional Fonts Folder 追加フォントフォルダー Adjust Adjoining Width Points 隣接する幅ポイントを調整 Adjust Colors カラーを調整 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..40bbf49cf7 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5611,6 +5611,7 @@ theme Appearance იერსახე 90° & 45° Angles 90° და 45° კუთხეები 90° Angles 90° კუთხეები Additional Plug-ins Folder დამატებითი პლაგინები + Plug-in Instruction Budget პლაგინების ინსტრუქციების ბიუჯეტი Additional Fonts Folder შრიფტების დამატებითი საქაღალდე Alignment Guides გასწორების დამხმარე ხაზები Anchor Points, Handle, and Bounding Box Display საყრდენი წერტილების, სახელურებისა და შემომსაზღვრელი ჩარჩოს ჩვენება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..8149cbc28d 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1059,6 +1059,7 @@ digits Malayalam 말라얄람어 Add to Selection 선택 영역에 추가 Add to Swatches 견본에 추가 Additional Plug-ins Folder 추가 플러그인 폴더 + Plug-in Instruction Budget 플러그인 명령어 예산 Additional Fonts Folder 추가 글꼴 폴더 Adjust Adjoining Width Points 인접한 너비 점 조정 Adjust Colors 색상 조정 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..6a134ca794 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4250,6 +4250,7 @@ theme Appearance Vormgeving 90° & 45° Angles Hoeken van 90° & 45° 90° Angles Hoeken van 90° Additional Plug-ins Folder Extra map met plug-ins + Plug-in Instruction Budget Instructiebudget voor plug-ins Additional Fonts Folder Extra map met lettertypen Alignment Guides Uitlijnhulplijnen Anchor Points, Handle, and Bounding Box Display Weergave van ankerpunten, greep en begrenzingskader diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..a91aa8809e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3836,6 +3836,7 @@ theme Appearance Wygląd 90° & 45° Angles Kąty 90° i 45° 90° Angles Kąty 90° Additional Plug-ins Folder Dodatkowy folder wtyczek + Plug-in Instruction Budget Budżet instrukcji wtyczek Additional Fonts Folder Dodatkowy folder czcionek Alignment Guides Linie wyrównania Anchor Points, Handle, and Bounding Box Display Wyświetlanie punktów kontrolnych, uchwytów i obwiedni diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..d148fbc149 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -146,6 +146,7 @@ Add to Selection Adicionar à Seleção Add to Swatches Adicionar às Amostras Additional Plug-ins Folder Pasta Adicional de Plug-ins + Plug-in Instruction Budget Orçamento de Instruções de Plug-ins Additional Fonts Folder Pasta Adicional de Fontes Adjust Adjoining Width Points Ajustar Pontos de Largura Adjacentes Adjust Color Balance… Ajustar Equilíbrio de Cores… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..e69a529a5c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -138,6 +138,7 @@ Add to Swatches Добавить в образцы Add Used Colors Добавить использованные цвета Additional Plug-ins Folder Папка дополнительных модулей + Plug-in Instruction Budget Бюджет инструкций модулей Additional Fonts Folder Папка дополнительных шрифтов Adjust Adjoining Width Points Настроить смежные точки ширины Adjust Color Balance… Настроить цветовой баланс… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..18545c765c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -128,6 +128,7 @@ Add to Swatches Lägg till i färgrutor Add Used Colors Lägg till använda färger Additional Plug-ins Folder Mapp för ytterligare plugins + Plug-in Instruction Budget Instruktionsbudget för plugins Additional Fonts Folder Mapp för ytterligare typsnitt Adjust Adjoining Width Points Justera angränsande breddpunkter Adjust Color Balance… Justera färgbalans… diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..ecbfde9057 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -125,6 +125,7 @@ Add to Swatches Renk Örneklerine Ekle Add Used Colors Kullanılan Renkleri Ekle Additional Plug-ins Folder Ek Eklentiler Klasörü + Plug-in Instruction Budget Eklenti Talimat Bütçesi Additional Fonts Folder Ek Yazı Tipleri Klasörü Adjust Adjoining Width Points Bitişik Genişlik Noktalarını Ayarlayın Adjust Color Balance… Renk Dengesini Ayarlayın… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..8757292124 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -134,6 +134,7 @@ Add to Swatches Додати до зразків Add Used Colors Додати використані кольори Additional Plug-ins Folder Папка додаткових модулів + Plug-in Instruction Budget Бюджет інструкцій модулів Additional Fonts Folder Папка додаткових шрифтів Adjust Adjoining Width Points Налаштувати суміжні точки ширини Adjust Color Balance… Налаштувати колірний баланс… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..1425c54e87 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -156,6 +156,7 @@ Add Used Colors Thêm các màu đã dùng Additional Fonts Folder Thư mục phông bổ sung Additional Plug-ins Folder Thư mục plug-in bổ sung + Plug-in Instruction Budget Ngân sách lệnh của plug-in Adjust Adjoining Width Points Điều chỉnh các điểm chiều rộng kề nhau Adjust Color Balance… Điều chỉnh cân bằng màu… Adjust Colors Điều chỉnh màu sắc diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..366f4f6729 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -89,6 +89,7 @@ Add to Swatches 添加到色板 Add Used Colors 添加已用颜色 Additional Plug-ins Folder 附加增效工具文件夹 + Plug-in Instruction Budget 增效工具指令预算 Additional Fonts Folder 附加字体文件夹 Adjust Adjoining Width Points 调整相邻宽度点 Adjust Color Balance… 调整色彩平衡… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..1ac2a15e11 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -98,6 +98,7 @@ Add to Swatches 新增至色票 Add Used Colors 新增使用中的顏色 Additional Plug-ins Folder 額外的增效模組資料夾 + Plug-in Instruction Budget 增效模組指令預算 Additional Fonts Folder 額外的字體資料夾 Adjust Adjoining Width Points 調整相鄰寬度點 Adjust Color Balance… 調整色彩平衡… diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 3ecf868532..54e53a8b63 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -20,6 +20,29 @@ fn marquee_selection_choices_are_saved_from_preferences() { assert!(text.contains("Drag Direction"), "{text}"); } +/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: shown with its choices, applied by OK, +/// saved with the UI state and read back from it when the app starts again. +#[test] +fn plugin_instruction_budget_shows_applies_and_restores() { + let mut a = app(); + open(&mut a, Some("Plug-ins & Scratch Disks")); + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(text.contains("Plug-in Instruction Budget") && text.contains("Normal"), "{text}"); + a.ui.dialog.as_mut().unwrap().fields.insert("pluginInstructionBudget".into(), json!("large")); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.plugin_instruction_budget, vectorcraft_engine::PluginBudget::Large); + let saved: Value = serde_json::from_slice(&serde_json::to_vec(&a.ui).unwrap()).unwrap(); + assert_eq!(saved["engine_prefs"]["pluginInstructionBudget"], json!("large")); + let mut b = app(); + b.ui.engine_prefs = saved["engine_prefs"].clone(); + restore(&mut b); + assert_eq!(b.session.prefs.plugin_instruction_budget, vectorcraft_engine::PluginBudget::Large); + // A saved value this version doesn't offer reads as Normal, and the other preferences stay. + b.ui.engine_prefs = json!({"keyboardIncrement": 4, "pluginInstructionBudget": 7}); + restore(&mut b); + assert_eq!((b.session.prefs.plugin_instruction_budget, b.session.prefs.keyboard_increment), (vectorcraft_engine::PluginBudget::Normal, 4.0)); +} + #[test] fn geometric_snapping_is_a_saved_smart_guides_preference() { let mut a = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..540cb0509e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11046,6 +11046,10 @@ no file, and an import opens no document). A filter whose manifest asks for a he `plugin.inspect {path | dataBase64}` entry) needs a person's approval, and `plugin.install` refuses `allowHeavy: true` from a request. `plugin.run` runs it where it is called, so the call may take minutes; `notifications/cancelled` stops it. +The preference `pluginInstructionBudget` (`normal`, the default, or `large`; `prefs.set` refuses any other value) +sets the instructions every object filter run gets: Large gives a light filter 250 M instructions instead of 50 M, +plus 4,000 per input byte either way, with its 60 s time budget unchanged; a heavy filter keeps its own budget with +either value. The next `plugin.run` or plug-in command uses the value set ([plug-ins](plugins.md#instruction-budget-preference)). A plug-in whose manifest lists permissions (`permissions` in its `plugin.inspect` entry, with `needsApproval: true`) needs a person's approval too, and `plugin.install` refuses `grant: [permission]` from a request. With a desktop app connected, `ui.installPlugin` opens the approval dialog and returns `{pending: "pluginInstall"}`; `answer_dialog`, @@ -11138,6 +11142,7 @@ Disable and Continue can't save the plug-in it turns off, this launch skips it a {"name":"run_command","arguments":{"command":"plugin.setEnabled","params":{"id":"org.example.wobble","enabled":true}}} {"name":"run_command","arguments":{"command":"plugin.install","params":{"path":"/plugins/desaturate.wasm"}}} {"name":"run_command","arguments":{"command":"plugin.run","params":{"id":"org.vectorcraft.example.desaturate","params":{"amount":60}}}} +{"name":"run_command","arguments":{"command":"prefs.set","params":{"key":"pluginInstructionBudget","value":"large"}}} {"name":"run_command","arguments":{"command":"effect.apply","params":{"effect":"plugin.org.example.wobble","params":{"size":4}}}} {"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/plot.hpgl","importer":"plugin.org.example.hpgl"}}} {"name":"run_command","arguments":{"command":"plugin.org.example.tidy.grow","params":{"by":3}}} diff --git a/docs/plugins.md b/docs/plugins.md index 2702e4fe7b..344e3b7c00 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -126,7 +126,7 @@ defaults): | Module size | 32 MiB | rejected | | Linear memory | 512 MiB per instance (input and parameters: at most half) | `memory.grow` returns -1; oversized input or initial memory fails | | Output | 64 MiB of JSON | `Limit("output size")` | -| Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run`; a [heavy filter](#heavy-filters) 1 G + 4,000 per byte; an export or import 10 G + 4,000 per byte | `Limit("instruction budget")` | +| Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run`; an object filter with the [Large instruction budget](#instruction-budget-preference) 250 M + 4,000 per byte; a [heavy filter](#heavy-filters) 1 G + 4,000 per byte; an export or import 10 G + 4,000 per byte | `Limit("instruction budget")` | | Wall clock | 60 s per filter run, 5 s per live-effect run, 300 s per heavy filter run, export or import (checked every 20 M instructions; the web build reads the page's `performance.now()`) | `Limit("time budget")` | | Import input | 128 MiB of the file (`vectorcraft_plugins::import::MAX_INPUT_BYTES`) | the file doesn't open; a larger file named by `path` is not read past that | | Call depth | 1,024 frames | trap | @@ -136,6 +136,22 @@ An export runs where the export runs: with Background Export on, on the export's plug-in between two of those 20 M-instruction slices; nothing is written then. An import stops the same way when the open it runs in is cancelled, and nothing opens then. +### Instruction budget preference + +Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`, VectorCraft's own +setting) sets the instructions each object filter run gets, from the app, `plugin.run`, a plug-in's commands, scripts +and MCP alike: + +- **Normal** (`normal`, the default): the limits in the table above, 50 M + 4,000 per input byte. +- **Large** (`large`): 250 M + 4,000 per input byte (`vectorcraft_plugins::LARGE_FUEL`, 5 times Normal). The 60 s time + budget, the memory, output and call depth limits stay as they are. + +A [heavy filter](#heavy-filters) keeps its 1 G and 300 s with either choice. Live effects, exporters and importers keep +their own budgets. A change applies to the next run of every installed filter, without installing it again. Cancel and +the time budget stop a run between two 20 M-instruction slices with either choice. `prefs.set {key: +"pluginInstructionBudget", value}` takes `normal` or `large` (or the labels Normal and Large) and refuses any other +value; a saved preferences file with another value reads as Normal. + ### Live effects while a document opens While the app draws a document on screen, the live-effect runs of its first view share a 2,000 ms budget diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..12a4fde680 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2200,6 +2200,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Changed plug-in gradients lose spot plates (G17):** a gradient that a filter or importer changes loses each stop's swatch link, tint and process `plates` together, in fills and strokes, and keeps the stop's color, offset, opacity and midpoint; a gradient returned unchanged keeps all three. Regressions: `crates/plugins/src/objects/tests.rs` (`changed_gradient_fill_and_stroke_drop_spot_plates`, `unchanged_gradient_paint_keeps_spot_plates`). Scores and hours unchanged. - **Plug-in data kept with the document (G17):** a filter writes JSON of at most 1 MiB with `documentData` (one undo step with its objects; `null` removes it) and reads it back in `_context.documentData`, which no other filter is given. It is the document's foreign data (`unknown.pluginData`, by plug-in id), as the perspective grid is, so the native file keeps it with no section of its own; an exporter is given the whole document, so it can read every plug-in's. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_export.rs` (the exporter), `crates/doc/src/plugin_data.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. - **Heavy filter plug-ins (G17):** a filter's manifest may ask for `"budget": "heavy"`: 1 G instructions (20 times a light run's) and 300 s a run, for routing, packing or simulation. Install Plug-in… and File › Open ask the user first, `plugin.install` needs `allowHeavy: true` (`plugin.inspect` tells beforehand), the Additional Plug-ins Folder skips such filters, and the plug-in store keeps the answer. Its dialog has no Preview; the app runs it on a thread of its own with a progress window (Cancel, Continue in Background) and applies the result as `plugin.run` with the same parameters, one undo step, unless the document or the plug-in changed meanwhile. Regressions: `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. +- **Plug-in instruction budget preference (G17, VectorCraft's own setting):** Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`) is Normal by default, which keeps the 50 M instructions a light filter run gets, or Large, which gives each object filter run 250 M plus the 4,000 per input byte, with the 60 s time budget, Cancel and the other limits unchanged. A heavy filter keeps its 1 G and 300 s with either choice; live effects, exporters and importers keep their own budgets. A change applies to the next run of an installed filter; `prefs.set` refuses any other value, and a saved file with another value reads as Normal. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. Scores and hours unchanged. - **Safe Mode for plug-ins (G17):** `vectorcraft --safe-mode` and `vectorcraft-cli --safe-mode ` start without plug-ins. When a launch stopped while a plug-in was loading or drawing its first live effect, the next launch names that plug-in, without saying it caused the stop, and offers Disable and Continue, Start Normally or Start in Safe Mode. Help › Safe Mode lists the disabled plug-ins with Enable on Re-launch, which takes effect at the next launch, and the app bar and the window title show Safe Mode. The help page (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, pages 65 to 69) describes the same choice between diagnosing and starting normally, a Safe Mode with the problem item off and the rest of the app working, and turning the item back on at the next launch. In Safe Mode no plug-in loads or runs, and a live-effect plug-in draws its object's geometry unchanged while the object keeps the effect, which the Appearance panel marks "(Safe Mode)" with the plug-in's id in its tooltip and `effect.list` marks `skipped`; Expand Appearance refuses such an object. The web build keeps no plug-ins between page loads and has no marker. Each desktop launch with preferences keeps a marker in the `Launch` folder next to them; `vectorcraft-cli` and a desktop launch without preferences keep none, so a stop there leads to no choice at the next launch. Disabled plug-ins are listed in `Plug-ins/disabled.json`. `plugin.safeMode` reports Safe Mode and the disabled plug-ins, and `plugin.setEnabled` changes the list. Regressions: `crates/plugins/src/safe_mode.rs`, `crates/plugins/tests/safe_mode.rs`, `crates/engine/tests/plugin_safe_mode.rs`, `crates/ui-egui/tests/safe_mode.rs`. Scores and hours unchanged. - **Hang report and Copy Troubleshooting Info:** when the desktop app's interface thread stays in one part of a frame for 3 s (VectorCraft's own value), a watching thread writes a hang report to the log and to `logs/hang-report-.txt`, and removes the file when the interface answers again. A later launch that finds a report no process holds writes it to the log, keeps it as `logs/hang-report.1.txt` and, unless another start-up message is showing, says so in the status bar. Help › Copy Troubleshooting Info (`help.copyTroubleshootingInfo`) copies the platform facts, the recent commands and frame times, and the reports of this session and the last one. Regressions: `apps/vectorcraft/src/hang_watch/tests.rs`, `crates/ui-egui/src/hang_beacon.rs`, `crates/ui-egui/src/troubleshooting.rs`. Scores and hours unchanged. - **A disabled plug-in whose update stays in the store is turned on:** when `plugin.install` writes a module that lists permissions to the `Plug-ins` folder, its grant can't be written, and the folder can't be returned to the old module (or, on a first install, the new module can't be removed), the folder holds the new module, so a disabled plug-in is turned on, by id and by stored file, as for any install the folder holds. The old grant, or none, doesn't cover the new module, so the next start skips it until it is approved. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. From c8ca3a2f587b17f44e7f4ea65e67e2675435e1f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 05:15:43 -0800 Subject: [PATCH 02/33] MCP: confined exporter plug-ins and unreadable linked files keep paths outside the read roots Under automation read roots, an exporter plug-in's format (plugin.) counts as an output that carries the native document, since its plug-in is given the document's JSON. document.serialize, document.export, document.exportSelection, Export for Screens and assets.export rows and file.exportAs refuse it before the plug-in runs and before any file or folder is written when the document links a JavaScript file, a linked image or placed file, a kept relative path or a data set's image outside the roots, with the existing errors. The JSON the plug-in is given leaves out an Export for Screens folder outside the roots. file.package refuses, before anything is written, a linked file whose native document it can't read to check: a native document that doesn't load, a PDF or .ai file that can't be opened (one that needs a password to open, or a damaged one), and a PDF, .ai or EPS file whose editing data doesn't load. The error, "a linked file's editing data can't be read to check it against the read roots", names no file or folder and gets rows in the complete-message catalogs. A PDF or EPS file without editing data is copied as before, and packages made without read roots are unchanged. --- crates/engine/src/cmd/fileio/access.rs | 9 ++- crates/engine/src/cmd/fileio/encode.rs | 10 ++- crates/engine/src/cmd/package.rs | 62 +++++++++++---- crates/engine/src/tests/package.rs | 56 ++++++++++++++ crates/engine/tests/plugin_export.rs | 102 +++++++++++++++++++++++++ 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/hi.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/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 + docs/mcp.md | 10 +++ docs/target-app-parity.md | 1 + 31 files changed, 252 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 1ded8d1f0b..bd55624b32 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -144,8 +144,9 @@ pub(crate) fn check_scripts_of(cmd: &str, doc: &vectorcraft_doc::Document, doc_p } /// Does a file of a document with `artboards` artboards, written in format `format` with options -/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates and -/// EPS files always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p` +/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates, +/// EPS files and the files of an exporter plug-in's format (`plugin.`, whose plug-in is given +/// the native document's JSON) always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p` /// picks only some of the artboards; a PDF does with Preserve Editing on (as its preset, standard and /// options leave it) unless `p` picks only some of the artboards. Neither a `.ai` file nor a PDF /// does when `useArtboards` is false in `p` (one page, the bounds of the art). Options the encoder @@ -159,6 +160,7 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards let art_page = || super::encode::use_artboards(cmd, p).is_ok_and(|u| u == Some(false)); match format { "svg" | "svgz" | "vectorcraft" | "template" | "eps" => true, + _ if vectorcraft_plugins::export::plugin_id(format).is_some() => true, "ai" | "ait" => { let legacy = super::format(format).is_some_and(|f| super::legacy_ai::wanted(cmd, f, p).unwrap_or(false)); !legacy && !(format == "ai" && art_page()) && every_artboard() @@ -228,7 +230,8 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu /// `cmd` may write `d` in format `format` (a format id other than SVG and SVGZ) with options `p`: /// always, unless read roots are in force, the file carries the native document (a native file or -/// template, an EPS file, a `.ai` or `.ait` file or a PDF with Preserve Editing, as +/// template, an EPS file, a `.ai` or `.ait` file, a PDF with Preserve Editing or an exporter +/// plug-in's file, as /// [`names_linked_scripts`] counts them with `d`'s artboards) and that document names a file /// outside them ([`crate::cmd::links::names_hidden_file`]: a linked image or placed file, the /// relative path kept of one taken from `base`, a data set's image, or stored brushes that can't be diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index c2140477ad..bf669332db 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -1038,12 +1038,14 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result { /// The file exporter plug-in `plugin` writes of `doc` in its format `f` /// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON -/// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else -/// one named after the document) with that path's extension when the plug-in lists it, else its -/// first. Its warnings come back with the file, as losses (the plug-in gives them no kind). +/// ([`vectorcraft_format::json_part`]), without an Export for Screens folder outside the read roots +/// ([`super::access::with_readable_settings_folder`]), and `p`'s `params`, for the file `p`'s `path` +/// names (else one named after the document) with that path's extension when the plug-in lists it, +/// else its first. Its warnings come back with the file, as losses (the plug-in gives them no kind). fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result { use vectorcraft_plugins::{Error, export}; - let doc = &*doc.without_edit_modes(); + let doc = doc.without_edit_modes(); + let doc = &*super::access::with_readable_settings_folder(&doc); let file = vectorcraft_format::save_with(doc, &vectorcraft_format::SaveOptions::default()).map_err(|e| EngineError::Other(e.to_string()))?; let path = p.get("path").and_then(Value::as_str); let listed = path.map(super::extension).and_then(|e| f.extensions.iter().copied().find(|x| *x == e)); diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index 3a182629df..531fbd81a8 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Package", [], None, - "{folder?, name?: (default: \" Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true ( Report.txt)} copy the saved document as it is now into folder/name as .vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \".zip\", dataBase64} (a zip of the files in /) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{folder?, name?: (default: \" Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true ( Report.txt)} copy the saved document as it is now into folder/name as .vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \".zip\", dataBase64} (a zip of the files in /) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while a linked native document, or a linked PDF, .ai or EPS file that carries one, can't be read to check it (a damaged file, or a PDF that needs a password to open); a PDF or EPS file without editing data is copied", has_doc, package )] @@ -113,27 +113,56 @@ thread_local! { pub(crate) static PARTS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of -/// a PDF, `.ai` or EPS file; `None` for other files and for data that can't be read. -fn carried_document(name: &str, bytes: &[u8]) -> Option { - if super::place::document::is_native(name, bytes) { - return vectorcraft_format::load_file(bytes).ok().map(|f| f.doc); - } - let data = - if super::place::document::is_pdf(name, bytes) { vectorcraft_pdf::editing(bytes).map(|e| e.data) } else { vectorcraft_eps::native(bytes) }; - vectorcraft_format::load(&data?).ok() +/// The native document a linked file is or carries ([`carried_document`]). +enum Carried { + /// The file is no native document and carries none: an image, or a PDF, `.ai` or EPS file + /// without editing data. + Absent, + /// The native document, read. + Readable(Box), + /// The file is a native document, or carries one, that can't be read: a damaged native file, + /// a PDF or `.ai` file that can't be opened without a password or can't be read at all, or + /// editing data that doesn't read as a native document. + Unreadable, } +/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of +/// a PDF, `.ai` or EPS file. +fn carried_document(name: &str, bytes: &[u8]) -> Carried { + let read = |data: &[u8]| vectorcraft_format::load(data).map_or(Carried::Unreadable, |d| Carried::Readable(Box::new(d))); + if super::place::document::is_native(name, bytes) { + return vectorcraft_format::load_file(bytes).map_or(Carried::Unreadable, |f| Carried::Readable(Box::new(f.doc))); + } + if super::place::document::is_pdf(name, bytes) { + // A PDF that can't be opened may carry editing data all the same. + return match vectorcraft_pdf::open_pdf(bytes, None) { + Ok(opened) => opened.editing().map_or(Carried::Absent, |e| read(&e.data)), + Err(_) => Carried::Unreadable, + }; + } + if !vectorcraft_eps::has_native(bytes) { + return Carried::Absent; + } + vectorcraft_eps::native(bytes).map_or(Carried::Unreadable, |data| read(&data)) +} + +/// The error for a linked file the package would copy whose native document can't be read to +/// check the files and folders it names against the read roots. +const UNREADABLE: &str = "a linked file's editing data can't be read to check it against the read roots"; + /// Under read roots, the linked file `name` (`bytes`, found at `path`) is copied only when the -/// native document it is or carries ([`carried_document`]) links no JavaScript file outside them (a -/// relative path taken from the file's folder): the copy would name it. +/// native document it is or carries ([`carried_document`]) can be read and links no JavaScript file +/// outside them (a relative path taken from the file's folder): the copy would name it. A file +/// whose native document can't be read is refused, as its links can't be checked. The error names +/// no file or folder. fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> { if crate::file_access::current().is_none() { return Ok(()); } match carried_document(name, bytes) { - Some(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true), - None => Ok(()), + Carried::Readable(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true), + Carried::Unreadable => Err(bad(C, UNREADABLE)), + Carried::Absent => Ok(()), } } @@ -150,7 +179,10 @@ fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> { return Ok(()); } match carried_document(name, bytes) { - Some(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => Err(bad(C, FOLDER_OUTSIDE)), + Carried::Readable(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => { + Err(bad(C, FOLDER_OUTSIDE)) + } + Carried::Unreadable => Err(bad(C, UNREADABLE)), _ => Ok(()), } } diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index 6ab5d73828..61a4c64846 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -465,6 +465,62 @@ fn a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_ assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1); } +/// A confined request packages no linked file whose native document it can't read to check against +/// its read roots: a PDF that needs a password to open, and a native document that doesn't load, +/// even inside the roots. The package is refused before anything is written, with an error that +/// names no file or folder. A PDF without editing data is copied, and the person's package copies +/// every file. +#[test] +fn a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read() { + let home = Folder::new("package-unreadable-home"); + let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap(); + let out = home.file("out"); + let package = |s: &mut Session, p: Value| crate::file_access::confine(Some(&roots), || s.execute("file.package", &p)); + let refused = |s: &mut Session, p: Value| { + let e = package(s, p.clone()).expect_err("refused"); + assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e:?}"); + let e = e.to_string(); + assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{p}: {e}"); + assert!(!e.contains(home.0.to_string_lossy().as_ref()) && !e.contains("part."), "{p}: {e}"); + assert!(!std::path::Path::new(&out).exists(), "{p}"); + }; + let mut part = session(); + run(&mut part, "shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})); + std::fs::create_dir_all(home.0.join("art")).unwrap(); + let native = home.file("art/part.vectorcraft"); + let pdf = home.file("art/part.pdf"); + save(&mut part, &native); + let pdf_of = + |part: &mut Session, p: Value| vectorcraft_format::base64_decode(run(part, "document.serialize", p)["dataBase64"].as_str().unwrap()).unwrap(); + let editable = pdf_of(&mut part, json!({"format": "pdf"})); + let locked = pdf_of(&mut part, json!({"format": "pdf", "security": {"openPassword": "open sesame"}})); + assert!(vectorcraft_pdf::editing_with(&locked, Some("open sesame")).is_some(), "the locked PDF carries editing data"); + let plain = pdf_of(&mut part, json!({"format": "pdf", "preserveEditing": false})); + let poster = |placed: &str| { + let mut s = session(); + let r = run(&mut s, "file.place", json!({"path": placed, "link": true})); + assert_eq!(r["linked"], true, "{r}"); + save(&mut s, &home.file("poster.vectorcraft")); + s + }; + write(&pdf, &editable); + let mut s = poster(&pdf); + write(&pdf, &locked); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"relink": false})); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); + // A PDF without editing data. + write(&pdf, &plain); + assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1); + std::fs::remove_dir_all(&out).unwrap(); + // A native document that doesn't load, rewritten or copied as it is. + let mut s = poster(&native); + write(&native, b"not a document"); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"folder": out, "relink": false})); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); +} + /// A missing link stored as a path relative to the document names a file inside a confined /// request's read root: the package report and Document Info give its stored path. #[test] diff --git a/crates/engine/tests/plugin_export.rs b/crates/engine/tests/plugin_export.rs index cc39566875..1f47b76e52 100644 --- a/crates/engine/tests/plugin_export.rs +++ b/crates/engine/tests/plugin_export.rs @@ -287,3 +287,105 @@ fn a_cancelled_export_stops_the_exporter() { assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); assert!(took >= wait && took < Duration::from_secs(10), "stopped while running, not before: {took:?}"); } + +/// Every string in `v`, at any depth. +fn strings_in(v: &Value, out: &mut Vec) { + match v { + Value::String(s) => out.push(s.clone()), + Value::Array(items) => items.iter().for_each(|v| strings_in(v, out)), + Value::Object(map) => map.values().for_each(|v| strings_in(v, out)), + _ => {} + } +} + +/// A confined caller: an exporter, given the native document's JSON, is not run for a document +/// that links a JavaScript file, a data set's image or a placed file outside the read roots. Every +/// command that writes its format refuses, before any file or folder is written, with an error +/// that names no file or folder, and the document keeps its links. A data set's image inside the +/// roots is given to it, the JSON it is given leaves out an Export for Screens folder outside them, +/// and the person's export gives it every path as stored. +#[test] +fn a_confined_exporter_is_refused_stored_paths_outside_the_read_roots() { + use vectorcraft_engine::file_access::{AutomationRoots, confine}; + + let away = tmp_dir("confined-away"); + let home = tmp_dir("confined-home"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + s.execute("assets.add", &json!({"ids": [r["id"]]})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + install(&mut s, &tpl::echo_exporter(&tpl::exporter("test.confined", r#"["tsc"]"#, "{}"), Echo::Input)); + let format = "plugin.test.confined"; + let roots = AutomationRoots::new(&[home.as_path()], &[home.as_path()]).unwrap(); + let out = path_of(&home.join("out")); + let outputs = [ + ("document.serialize", json!({"format": format})), + ("document.export", json!({"format": format})), + ("document.export", json!({"format": format, "path": path_of(&home.join("export.tsc"))})), + ("document.exportSelection", json!({"format": format})), + ("document.exportForScreens", json!({"folder": out, "formats": [{"format": format}]})), + ("assets.export", json!({"folder": out, "formats": [{"format": format}]})), + ]; + let hidden = [path_of(&away), path_of(&home)]; + // `assets`: an asset's file is checked too (its document holds the asset's art and the + // document's data sets, not other art). + let refused = |s: &mut Session, why: &str, assets: bool| { + for (cmd, p) in outputs.iter().filter(|(cmd, _)| assets || *cmd != "assets.export") { + let e = confine(roots.as_ref(), || s.execute(cmd, p)).expect_err(&format!("{cmd} {p}: {why}")); + assert!(matches!(e, EngineError::BadParams { .. }), "{cmd} {p}: {e:?}"); + let e = e.to_string(); + assert!(e.contains(why), "{cmd} {p}: {e}"); + for h in &hidden { + assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}"); + } + } + assert_eq!(std::fs::read_dir(&home).unwrap().count(), 0, "nothing is written"); + }; + // The strings of the JSON the exporter is given. + let given = |s: &mut Session, confined: bool| { + let p = json!({"format": format}); + let r = if confined { confine(roots.as_ref(), || s.execute("document.export", &p)) } else { s.execute("document.export", &p) }; + let mut found = vec![]; + strings_in(&serde_json::from_slice(&exported(&r.unwrap())).unwrap(), &mut found); + found + }; + + let script = path_of(&away.join("menu.js")); + s.execute("svgInteractivity.addFile", &json!({"file": script})).unwrap(); + refused(&mut s, "a linked JavaScript file is outside the read roots", true); + assert!(given(&mut s, false).contains(&script), "the person's export"); + s.execute("svgInteractivity.removeFile", &json!({"file": script})).unwrap(); + + let set_image = |s: &mut Session, path: &str| { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let values = [("Photo".to_string(), vectorcraft_doc::DataValue::Image(path.into()))].into_iter().collect(); + doc.variables.datasets = vec![vectorcraft_doc::DataSet { name: "Row 1".into(), values }]; + }; + let photo = path_of(&away.join("photo.png")); + set_image(&mut s, &photo); + refused(&mut s, "a linked image file is outside the read roots", true); + assert!(given(&mut s, false).contains(&photo), "the person's export"); + let inside = path_of(&home.join("photo.png")); + set_image(&mut s, &inside); + assert!(given(&mut s, true).contains(&inside), "an image inside the read roots"); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).variables.datasets.clear(); + + let folder = path_of(&away.join("screens")); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).export_settings = serde_json::from_value(json!({"folder": folder})).unwrap(); + assert!(!given(&mut s, true).contains(&folder), "the export folder is left out"); + assert!(given(&mut s, false).contains(&folder), "the person's export"); + assert_eq!(s.doc().unwrap().doc.export_settings.get("folder"), Some(&json!(folder)), "the document keeps it"); + + let mut part = Session::new(); + part.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let placed = path_of(&away.join("part.vectorcraft")); + part.execute("file.saveAs", &json!({"path": placed})).unwrap(); + s.execute("file.place", &json!({"path": placed, "link": true})).unwrap(); + refused(&mut s, "a linked image file is outside the read roots", false); + // The asset's file holds the rectangle alone, without the placed file. + let r = confine(roots.as_ref(), || s.execute("assets.export", &outputs[5].1)).unwrap(); + let mut found = vec![]; + strings_in(&serde_json::from_slice(&std::fs::read(r["files"][0].as_str().unwrap()).unwrap()).unwrap(), &mut found); + assert!(!found.contains(&placed), "{found:?}"); +} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 69bedf6160..09e294bf89 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5596,6 +5596,7 @@ digits Malayalam Malaiàlam @msg a linked JavaScript file is outside the read roots un fitxer JavaScript enllaçat és fora de les arrels de lectura @msg a linked image file is outside the read roots un fitxer d’imatge enllaçat és fora de les arrels de lectura @msg a linked file's export folder is outside the read roots la carpeta d’exportació d’un fitxer enllaçat és fora de les arrels de lectura +@msg a linked file's editing data can't be read to check it against the read roots no es poden llegir les dades d’edició d’un fitxer enllaçat per comprovar-les amb les arrels de lectura @msg the library's file is outside the read roots el fitxer de la biblioteca és fora de les arrels de lectura @msg {file} names more than one linked JavaScript file {file} correspon a més d’un fitxer JavaScript enllaçat @msg automation path rejected: outside the write root {root}: {path} camí d’automatització rebutjat: fora de l’arrel d’escriptura {root}: {path} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 2bb3c2e1ce..8463f682d1 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5741,6 +5741,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg a linked JavaScript file is outside the read roots propojený soubor JavaScript je mimo kořeny pro čtení @msg a linked image file is outside the read roots propojený soubor obrázku je mimo kořeny pro čtení @msg a linked file's export folder is outside the read roots exportní složka propojeného souboru je mimo kořeny pro čtení +@msg a linked file's editing data can't be read to check it against the read roots editační data propojeného souboru nelze přečíst a ověřit vůči kořenům pro čtení @msg automation path rejected: outside the write root {root}: {path} cesta automatizace odmítnuta: mimo kořen pro zápis {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} cesta automatizace odmítnuta: mimo kořeny pro zápis {roots}: {path} @msg automation path rejected: path is empty cesta automatizace odmítnuta: cesta je prázdná diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 2d85da633f..aa9efe4f19 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1381,6 +1381,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg a linked JavaScript file is outside the read roots en linket JavaScript-fil ligger uden for læserødderne @msg a linked image file is outside the read roots en linket billedfil ligger uden for læserødderne @msg a linked file's export folder is outside the read roots eksportmappen for en linket fil ligger uden for læserødderne +@msg a linked file's editing data can't be read to check it against the read roots redigeringsdataene for en linket fil kan ikke læses for at kontrollere dem mod læserødderne @msg a name names one asset: give multiple: false, or one object et navn angiver ét aktiv: angiv multiple: false eller ét objekt @msg a namespace declaration uses a reserved prefix or URI en navnerumserklæring bruger et reserveret præfiks eller en reserveret URI @msg a namespace qualifier is undefined en navnerumskvalifikator er udefineret diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index f99f958d5b..0fc4f0df52 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -9237,6 +9237,7 @@ breakText Glyphs Glyphen @msg a linked JavaScript file is outside the read roots eine verknüpfte JavaScript-Datei liegt außerhalb der Lesestammordner @msg a linked image file is outside the read roots eine verknüpfte Bilddatei liegt außerhalb der Lesestammordner @msg a linked file's export folder is outside the read roots der Exportordner einer verknüpften Datei liegt außerhalb der Lesestammordner +@msg a linked file's editing data can't be read to check it against the read roots die Bearbeitungsdaten einer verknüpften Datei können nicht gelesen werden, um sie mit den Lesestammordnern abzugleichen @msg a number cannot be read eine Zahl kann nicht gelesen werden @msg a swatch exchange block is too long ein Block der Farbfeld-Austauschdatei ist zu lang @msg a swatch exchange name is too long ein Name in der Farbfeld-Austauschdatei ist zu lang diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 398d5b2509..344e48c2ca 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5438,6 +5438,7 @@ digits Malayalam Μαλαγιάλαμ @msg a linked JavaScript file is outside the read roots ένα συνδεδεμένο αρχείο JavaScript είναι εκτός των ριζών ανάγνωσης @msg a linked image file is outside the read roots ένα συνδεδεμένο αρχείο εικόνας είναι εκτός των ριζών ανάγνωσης @msg a linked file's export folder is outside the read roots ο φάκελος εξαγωγής ενός συνδεδεμένου αρχείου είναι εκτός των ριζών ανάγνωσης +@msg a linked file's editing data can't be read to check it against the read roots τα δεδομένα επεξεργασίας ενός συνδεδεμένου αρχείου δεν μπορούν να διαβαστούν για έλεγχο με τις ρίζες ανάγνωσης @msg the library's file is outside the read roots το αρχείο της βιβλιοθήκης είναι εκτός των ριζών ανάγνωσης @msg {file} names more than one linked JavaScript file το {file} αντιστοιχεί σε περισσότερα από ένα συνδεδεμένα αρχεία JavaScript @msg automation path rejected: outside the write root {root}: {path} απορρίφθηκε η διαδρομή αυτοματισμού: εκτός ρίζας εγγραφής {root}: {path} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 984268465a..3c729cc32e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5475,6 +5475,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg a linked JavaScript file is outside the read roots un archivo JavaScript vinculado está fuera de las carpetas raíz de lectura @msg a linked image file is outside the read roots un archivo de imagen vinculado está fuera de las carpetas raíz de lectura @msg a linked file's export folder is outside the read roots la carpeta de exportación de un archivo vinculado está fuera de las carpetas raíz de lectura +@msg a linked file's editing data can't be read to check it against the read roots no se pueden leer los datos de edición de un archivo vinculado para comprobarlos con las carpetas raíz de lectura @msg automation path rejected: outside the write root {root}: {path} ruta de automatización rechazada: fuera de la carpeta raíz de escritura {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} ruta de automatización rechazada: fuera de las carpetas raíz de escritura {roots}: {path} @msg automation path rejected: path is empty ruta de automatización rechazada: la ruta está vacía diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1b49c99ca6..c749afe12e 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5665,6 +5665,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg a linked JavaScript file is outside the read roots linkitetty JavaScript-tiedosto on lukujuurten ulkopuolella @msg a linked image file is outside the read roots linkitetty kuvatiedosto on lukujuurten ulkopuolella @msg a linked file's export folder is outside the read roots linkitetyn tiedoston vientikansio on lukujuurten ulkopuolella +@msg a linked file's editing data can't be read to check it against the read roots linkitetyn tiedoston muokkaustietoja ei voi lukea niiden tarkistamiseksi lukujuuria vasten @msg the library's file is outside the read roots kirjaston tiedosto on lukujuurten ulkopuolella @msg {file} names more than one linked JavaScript file {file} vastaa useampaa kuin yhtä linkitettyä JavaScript-tiedostoa @msg automation path rejected: outside the write root {root}: {path} automaation polku hylättiin: kirjoitusjuuren {root} ulkopuolella: {path} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 54b133a741..c127ead580 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5457,6 +5457,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg a linked JavaScript file is outside the read roots un fichier JavaScript lié est hors des dossiers racines de lecture @msg a linked image file is outside the read roots un fichier image lié est hors des dossiers racines de lecture @msg a linked file's export folder is outside the read roots le dossier d’exportation d’un fichier lié est hors des dossiers racines de lecture +@msg a linked file's editing data can't be read to check it against the read roots impossible de lire les données d’édition d’un fichier lié pour les vérifier par rapport aux dossiers racines de lecture @msg automation path rejected: outside the write root {root}: {path} chemin d’automatisation refusé : hors du dossier racine d’écriture {root} : {path} @msg automation path rejected: outside the write roots {roots}: {path} chemin d’automatisation refusé : hors des dossiers racines d’écriture {roots} : {path} @msg automation path rejected: path is empty chemin d’automatisation refusé : le chemin est vide diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 5801e04f8c..3af874669e 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6627,6 +6627,7 @@ antiAlias Sharp शार्प @msg a linked JavaScript file is outside the read roots एक लिंक की गई जावास्क्रिप्ट फ़ाइल पढ़ने की जड़ों के बाहर है @msg a linked image file is outside the read roots एक लिंक की गई छवि फ़ाइल पढ़ने की जड़ों के बाहर है @msg a linked file's export folder is outside the read roots एक लिंक की गई फ़ाइल का निर्यात फ़ोल्डर पढ़ने की जड़ों के बाहर है +@msg a linked file's editing data can't be read to check it against the read roots एक लिंक की गई फ़ाइल का संपादन डेटा पढ़ने की जड़ों से जाँचने के लिए पढ़ा नहीं जा सकता @msg the library's file is outside the read roots लाइब्रेरी की फ़ाइल पढ़ने की जड़ों के बाहर है @msg {file} names more than one linked JavaScript file {file} एक से अधिक लिंक की गई जावास्क्रिप्ट फ़ाइलों से मेल खाता है @msg automation path rejected: outside the write root {root}: {path} स्वचालन पाथ खारिज: लिखने की जड़ के बाहर {root}: {path} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9d32256c22..39da9c03a5 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5195,6 +5195,7 @@ imageTrace Outline Körvonal @msg a linked JavaScript file is outside the read roots egy csatolt JavaScript-fájl kívül esik az olvasási gyökereken @msg a linked image file is outside the read roots egy csatolt képfájl kívül esik az olvasási gyökereken @msg a linked file's export folder is outside the read roots egy csatolt fájl exportálási mappája kívül esik az olvasási gyökereken +@msg a linked file's editing data can't be read to check it against the read roots egy csatolt fájl szerkesztési adatai nem olvashatók be az olvasási gyökerekkel való ellenőrzéshez @msg automation path rejected: outside the write root {root}: {path} az automatizálás útvonala elutasítva: kívül esik az írási gyökéren ({root}): {path} @msg automation path rejected: outside the write roots {roots}: {path} az automatizálás útvonala elutasítva: kívül esik az írási gyökereken ({roots}): {path} @msg automation path rejected: parent traversal below a folder that doesn't exist: {path} az automatizálás útvonala elutasítva: szülőmappára lépés egy nem létező mappa alatt: {path} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ab83d2e323..79ae12733e 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5501,6 +5501,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg a linked JavaScript file is outside the read roots un file JavaScript collegato è fuori dalle cartelle radice di lettura @msg a linked image file is outside the read roots un file immagine collegato è fuori dalle cartelle radice di lettura @msg a linked file's export folder is outside the read roots la cartella di esportazione di un file collegato è fuori dalle cartelle radice di lettura +@msg a linked file's editing data can't be read to check it against the read roots impossibile leggere i dati di modifica di un file collegato per verificarli rispetto alle cartelle radice di lettura @msg automation path rejected: outside the write root {root}: {path} percorso di automazione rifiutato: fuori dalla cartella radice di scrittura {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} percorso di automazione rifiutato: fuori dalle cartelle radice di scrittura {roots}: {path} @msg automation path rejected: path is empty percorso di automazione rifiutato: il percorso è vuoto diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index a45098fc2e..1d3e65f5b3 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5543,6 +5543,7 @@ liquify-list-end {0}, {1} {0}、{1} @msg a linked JavaScript file is outside the read roots リンクされた JavaScript ファイルが読み込みルートの外にあります @msg a linked image file is outside the read roots リンクされた画像ファイルが読み込みルートの外にあります @msg a linked file's export folder is outside the read roots リンクされたファイルの書き出しフォルダーが読み込みルートの外にあります +@msg a linked file's editing data can't be read to check it against the read roots リンクされたファイルの編集データを読み込めないため、読み込みルートと照合できません @msg automation path rejected: outside the write root {root}: {path} 自動化のパスを拒否しました: 書き込みルート {root} の外です: {path} @msg automation path rejected: outside the write roots {roots}: {path} 自動化のパスを拒否しました: 書き込みルート {roots} のいずれの中でもありません: {path} @msg automation path rejected: path is empty 自動化のパスを拒否しました: パスが空です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a14fc1f8e7..94c534b69d 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2065,6 +2065,7 @@ @msg {var_key} must be at most {most} {var_key} უნდა იყოს მაქსიმუმ {most} @msg a linked image file is outside the read roots დაკავშირებული გამოსახულების ფაილი წაკითხვის ძირეული საქაღალდეების გარეთაა @msg a linked file's export folder is outside the read roots დაკავშირებული ფაილის ექსპორტის საქაღალდე წაკითხვის ძირეული საქაღალდეების გარეთაა +@msg a linked file's editing data can't be read to check it against the read roots დაკავშირებული ფაილის რედაქტირების მონაცემების წაკითხვა ვერ ხერხდება წაკითხვის ძირეულ საქაღალდეებთან შესამოწმებლად Neon & Glow ნეონი და ნათება Show Hidden Panels at Edge დამალული პანელების ჩვენება კიდესთან @msg `anchor` must be a [subpath, anchor] pair `anchor` უნდა იყოს წყვილი [subpath, anchor] diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 9b678e5ea6..c342c4cdc4 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5470,6 +5470,7 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg a linked JavaScript file is outside the read roots 연결된 JavaScript 파일이 읽기 루트 밖에 있습니다 @msg a linked image file is outside the read roots 연결된 이미지 파일이 읽기 루트 밖에 있습니다 @msg a linked file's export folder is outside the read roots 연결된 파일의 내보내기 폴더가 읽기 루트 밖에 있습니다 +@msg a linked file's editing data can't be read to check it against the read roots 연결된 파일의 편집 데이터를 읽을 수 없어 읽기 루트와 대조할 수 없습니다 @msg automation path rejected: outside the write root {root}: {path} 자동화 경로가 거부되었습니다: 쓰기 루트 {root} 밖입니다: {path} @msg automation path rejected: outside the write roots {roots}: {path} 자동화 경로가 거부되었습니다: 쓰기 루트 {roots} 밖입니다: {path} @msg automation path rejected: path is empty 자동화 경로가 거부되었습니다: 경로가 비어 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index cc1c484470..6cc11bf241 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6220,6 +6220,7 @@ imageTrace Outline Contour @msg a linked JavaScript file is outside the read roots een gekoppeld JavaScript-bestand staat buiten de leesroots @msg a linked image file is outside the read roots een gekoppeld afbeeldingsbestand staat buiten de leesroots @msg a linked file's export folder is outside the read roots de exportmap van een gekoppeld bestand staat buiten de leesroots +@msg a linked file's editing data can't be read to check it against the read roots de bewerkingsgegevens van een gekoppeld bestand kunnen niet worden gelezen om ze aan de leesroots te toetsen @msg a name names one asset: give multiple: false, or one object een naam noemt één asset: geef multiple: false, of één object @msg a namespace declaration uses a reserved prefix or URI een naamruimtedeclaratie gebruikt een gereserveerd voorvoegsel of een gereserveerde URI @msg a namespace qualifier is undefined een naamruimtekwalificatie is niet gedefinieerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index a1e9b75723..ec761f3ef3 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5567,6 +5567,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg a linked JavaScript file is outside the read roots połączony plik JavaScript jest poza katalogami głównymi odczytu @msg a linked image file is outside the read roots połączony plik obrazu jest poza katalogami głównymi odczytu @msg a linked file's export folder is outside the read roots folder eksportu połączonego pliku jest poza katalogami głównymi odczytu +@msg a linked file's editing data can't be read to check it against the read roots nie można odczytać danych edycji połączonego pliku, aby sprawdzić je względem katalogów głównych odczytu @msg automation path rejected: outside the write root {root}: {path} odrzucono ścieżkę automatyzacji: poza katalogiem głównym zapisu {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} odrzucono ścieżkę automatyzacji: poza katalogami głównymi zapisu {roots}: {path} @msg automation path rejected: path is empty odrzucono ścieżkę automatyzacji: ścieżka jest pusta diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 590d0f0e29..19e3a9aab6 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4737,6 +4737,7 @@ axis Both Ambos @msg a linked JavaScript file is outside the read roots um arquivo JavaScript vinculado está fora das raízes de leitura @msg a linked image file is outside the read roots um arquivo de imagem vinculado está fora das raízes de leitura @msg a linked file's export folder is outside the read roots a pasta de exportação de um arquivo vinculado está fora das raízes de leitura +@msg a linked file's editing data can't be read to check it against the read roots não é possível ler os dados de edição de um arquivo vinculado para verificá-los em relação às raízes de leitura @msg automation path rejected: outside the write root {root}: {path} caminho da automação rejeitado: fora da raiz de gravação {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} caminho da automação rejeitado: fora das raízes de gravação {roots}: {path} @msg automation path rejected: path is empty caminho da automação rejeitado: o caminho está vazio diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 021a4f5db1..11937505a4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5501,6 +5501,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg a linked JavaScript file is outside the read roots связанный файл JavaScript находится вне корневых папок для чтения @msg a linked image file is outside the read roots связанный файл изображения находится вне корневых папок для чтения @msg a linked file's export folder is outside the read roots папка экспорта связанного файла находится вне корневых папок для чтения +@msg a linked file's editing data can't be read to check it against the read roots не удаётся прочитать данные редактирования связанного файла, чтобы сверить их с корневыми папками для чтения @msg automation path rejected: outside the write root {root}: {path} путь автоматизации отклонён: вне корневой папки для записи {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} путь автоматизации отклонён: вне корневых папок для записи {roots}: {path} @msg automation path rejected: path is empty путь автоматизации отклонён: путь пуст diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 199c3ab08c..d036270cdf 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5383,6 +5383,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg automation path rejected: outside the read roots {roots}: {path} automatiseringssökvägen avvisades: utanför läsrötterna {roots}: {path} @msg a linked image file is outside the read roots en länkad bildfil ligger utanför läsrötterna @msg a linked file's export folder is outside the read roots exportmappen för en länkad fil ligger utanför läsrötterna +@msg a linked file's editing data can't be read to check it against the read roots redigeringsdata för en länkad fil kan inte läsas för att kontrolleras mot läsrötterna @msg automation path rejected: outside the write root {root}: {path} automatiseringssökvägen avvisades: utanför skrivroten {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} automatiseringssökvägen avvisades: utanför skrivrötterna {roots}: {path} @msg automation path rejected: path is empty automatiseringssökvägen avvisades: sökvägen är tom diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 603a918b40..97d774d2ef 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7289,6 +7289,7 @@ axis Y Axis Y ekseni @msg a linked JavaScript file is outside the read roots bağlantılı bir JavaScript dosyası okuma köklerinin dışında @msg a linked image file is outside the read roots bağlantılı bir görüntü dosyası okuma köklerinin dışında @msg a linked file's export folder is outside the read roots bağlantılı bir dosyanın dışa aktarma klasörü okuma köklerinin dışında +@msg a linked file's editing data can't be read to check it against the read roots bağlantılı bir dosyanın düzenleme verileri okuma köklerine göre denetlemek için okunamıyor @msg the line is too long, or the paths it passes too many, to check çizgi denetlenemeyecek kadar uzun veya geçtiği yollar çok fazla @msg the method needs an XML value yöntem için bir XML değeri gerekir @msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) boya bir serbest biçimli degrade değil (paint.editGradient {kind} ile bir tane uygulayın) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 5d4e663cb1..21873928ba 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5485,6 +5485,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg a linked JavaScript file is outside the read roots зв’язаний файл JavaScript перебуває поза кореневими папками для читання @msg a linked image file is outside the read roots зв’язаний файл зображення перебуває поза кореневими папками для читання @msg a linked file's export folder is outside the read roots папка експорту зв’язаного файлу перебуває поза кореневими папками для читання +@msg a linked file's editing data can't be read to check it against the read roots не вдається прочитати дані редагування зв’язаного файлу, щоб звірити їх із кореневими папками для читання @msg automation path rejected: outside the write root {root}: {path} шлях автоматизації відхилено: поза кореневою папкою для запису {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} шлях автоматизації відхилено: поза кореневими папками для запису {roots}: {path} @msg automation path rejected: path is empty шлях автоматизації відхилено: шлях порожній diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index e4cc719e80..7a058289d0 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4849,6 +4849,7 @@ theme Appearance Giao diện @msg a linked JavaScript file is outside the read roots một tệp JavaScript được liên kết nằm ngoài các thư mục gốc đọc @msg a linked image file is outside the read roots một tệp hình ảnh được liên kết nằm ngoài các thư mục gốc đọc @msg a linked file's export folder is outside the read roots thư mục xuất của một tệp được liên kết nằm ngoài các thư mục gốc đọc +@msg a linked file's editing data can't be read to check it against the read roots không thể đọc dữ liệu chỉnh sửa của một tệp được liên kết để kiểm tra với các thư mục gốc đọc @msg the library's file is outside the read roots tệp của thư viện nằm ngoài các thư mục gốc đọc @msg {file} names more than one linked JavaScript file {file} khớp với nhiều hơn một tệp JavaScript được liên kết @msg automation path rejected: outside the write root {root}: {path} đường dẫn tự động bị từ chối: ngoài thư mục gốc ghi {root}: {path} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 8bcfed5519..b5d788109c 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5217,6 +5217,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg a linked JavaScript file is outside the read roots 链接的 JavaScript 文件位于所有读取根目录之外 @msg a linked image file is outside the read roots 链接的图像文件位于所有读取根目录之外 @msg a linked file's export folder is outside the read roots 链接文件的导出文件夹位于所有读取根目录之外 +@msg a linked file's editing data can't be read to check it against the read roots 无法读取链接文件的编辑数据,因此无法对照读取根目录进行检查 @msg automation path rejected: outside the write root {root}: {path} 已拒绝自动化路径:位于写入根目录 {root} 之外:{path} @msg automation path rejected: outside the write roots {roots}: {path} 已拒绝自动化路径:位于所有写入根目录 {roots} 之外:{path} @msg automation path rejected: path is empty 已拒绝自动化路径:路径为空 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 42b9d9017c..bb93d2a060 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2842,6 +2842,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg a linked JavaScript file is outside the read roots 連結的 JavaScript 檔案位於所有讀取根目錄之外 @msg a linked image file is outside the read roots 連結的影像檔案位於所有讀取根目錄之外 @msg a linked file's export folder is outside the read roots 連結檔案的匯出資料夾位於所有讀取根目錄之外 +@msg a linked file's editing data can't be read to check it against the read roots 無法讀取連結檔案的編輯資料,因此無法對照讀取根目錄進行檢查 @msg automation path rejected: outside the write root {root}: {path} 已拒絕自動化路徑:位於寫入根目錄 {root} 之外:{path} @msg automation path rejected: outside the write roots {roots}: {path} 已拒絕自動化路徑:位於所有寫入根目錄 {roots} 之外:{path} @msg automation path rejected: path is empty 已拒絕自動化路徑:路徑是空的 diff --git a/docs/mcp.md b/docs/mcp.md index adef77ff3b..92d99d7751 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -286,6 +286,16 @@ the suite) keep the agent to the folders you give it: linked native document with `relink: false`, as it is: when the native document such a file is or carries keeps a folder outside the read roots, the package is refused before anything is written with "a linked file's export folder is outside the read roots", which names no file or folder. +- An exporter plug-in's format (`plugin.`) carries the native document too: its plug-in is given the + document's JSON. The JavaScript and linked image rules above refuse its files from every command that writes + them, before the plug-in runs and before any file or folder is written, and the JSON the plug-in is given + leaves out an Export for Screens folder outside the read roots. +- `file.package` refuses, before anything is written, a linked file whose native document it can't read to + check against the read roots: a native document that doesn't load, a PDF or `.ai` file that can't be opened + (one that needs a password to open, or a damaged one), and a PDF, `.ai` or EPS file whose editing data + doesn't load. The error, "a linked file's editing data can't be read to check it against the read roots", + names no file or folder. A PDF, `.ai` or EPS file without editing data is copied as before, and the person at + the keyboard packages every linked file as before. - `plugin.list`, `plugin.safeMode`, `file.recovery.*` and `ui_inspect`'s `scriptReport` leave out the paths outside the read roots, also those the person or an earlier request put there. In `plugin.list`, the plug-in folder last loaded is `null` in `folder.folder`, and a failed file in `folder.failed` and a plug-in's `source` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6b53d04b36..ef7e44b26c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -900,6 +900,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Clipboard flavors under `--automation-read-root`: `clipboard.flavours` leaves out the SVG, and its markup as text, that `clipboard.exportSvg` refuses. `crates/engine/src/tests/links.rs` (`confined_clipboard_flavours_leave_out_a_withheld_svg`). - Preserve Editing SVG under `--automation-read-root`: the native document an SVG or SVGZ carries leaves out an Export for Screens folder outside the read roots, and keeps the other export settings and the art; the open document keeps the folder, and a folder inside the roots is kept. `crates/engine/src/tests/links.rs` (`confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_roots`). - Native document output and linked images under `--automation-read-root`: the outputs that carry the native document (a native file or template, an EPS file, a `.ai` or `.ait` file of every artboard, a PDF of every artboard with Preserve Editing, also from `document.exportPdf`, the saves and Export for Screens rows) are refused, before any file or folder is written, with an error that names no file or folder, when that document names a linked image or placed file, a kept relative path or a data set's image outside the read roots, or holds a stored brush entry that does not read as a brush; files without the native document are written. Those documents, and the documents Package writes or rewrites, leave out an Export for Screens folder outside the read roots, and Package refuses a linked file it copies as it is whose native document keeps one; the open document keeps its links, data sets and folder. An Export for Screens row that writes one artboard is checked against that artboard's art, and each asset, layer or selected object writes its own native, `.ai` or EPS file. `crates/engine/src/tests/links.rs` (`confined_native_output_refuses_a_linked_image_file_outside_the_read_roots`, `confined_native_output_refuses_a_data_set_image_outside_the_read_roots`, `confined_native_output_leaves_out_an_export_folder_outside_the_read_roots`, `confined_screens_rows_check_the_artboard_each_file_holds`), `crates/engine/src/tests/package.rs` (`a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_the_read_root`), `crates/engine/src/cmd/fileio/tests_screens.rs` (`each_piece_writes_its_own_native_document`). + - Exporter plug-ins and Package's unreadable linked files under `--automation-read-root`: an exporter plug-in's format, whose plug-in is given the native document's JSON, is refused before the plug-in runs when that document links a JavaScript file, a linked image or placed file or a data set's image outside the read roots, and the JSON leaves out an Export for Screens folder outside them; Package refuses, before anything is written, a linked native document, PDF, `.ai` or EPS file whose native document can't be read to check it (a PDF that needs a password to open, damaged editing data), and copies a PDF or EPS file without editing data. Errors name no file or folder, and the person at the keyboard exports and packages as before. `crates/engine/tests/plugin_export.rs` (`a_confined_exporter_is_refused_stored_paths_outside_the_read_roots`), `crates/engine/src/tests/package.rs` (`a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read`). - Linked-file and font-file searches under `--automation-read-root`: `links.findFiles` and `text.findFontFiles` replies, also later polls and stops of a search another client started, leave out the files found, a link's saved path and the folder searched outside the caller's read roots, and a failed search gives its reason without the path; `image.info` gives `link: null` for a linked file outside them; `text.addFontFiles` gives `folder: null` and the copies' file names when the Fonts folder is outside them. `crates/engine/src/tests/linkfiles.rs`, `crates/engine/src/tests/fontfiles.rs`, `crates/engine/tests/font_folder.rs`. - Swatch, brush, symbol and graphic style library lists under `--automation-read-root`: every library stays listed, the paths of library files and the user library folder outside the read roots are `null`, a library loaded from outside them is listed and found as `loaded/` and keeps that id for the session unless a library loaded later without a file shows that id itself, which moves it to the next free `loaded/ (N)`, and the app's own list is not changed. `crates/engine/src/tests/library_roots.rs`. - Preferences commands under `--automation-read-root`: `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show folder preferences outside the read roots as `null` and leave out an export preset's folder outside them, and the preferences are not changed. `crates/engine/src/tests/prefs_roots.rs`. From 69cc81452e229658fa744772ac2e0826b9d8048b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 06:58:12 -0800 Subject: [PATCH 03/33] MCP: a confined package refuses a PDF whose editing file can't be resolved A linked PDF or .ai file that lists the editing file among its attachments, but whose file specification, EF dictionary or F or UF stream can't be resolved, was taken for a file without editing data and copied without its stored paths being checked. Under read roots, file.package now refuses it with the error for editing data that can't be read. Opening such a PDF is unchanged. The plug-in export test removes its folders when it ends. --- crates/engine/src/cmd/package.rs | 12 ++++-- crates/engine/src/tests/package.rs | 9 +++++ crates/engine/tests/plugin_export.rs | 2 + crates/pdf/src/editing.rs | 57 +++++++++++++++++++++++----- crates/pdf/src/pages.rs | 6 +++ crates/pdf/src/tests/editing.rs | 42 ++++++++++++++++++++ 6 files changed, 115 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index 531fbd81a8..99bcf455b7 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -121,8 +121,9 @@ enum Carried { /// The native document, read. Readable(Box), /// The file is a native document, or carries one, that can't be read: a damaged native file, - /// a PDF or `.ai` file that can't be opened without a password or can't be read at all, or - /// editing data that doesn't read as a native document. + /// a PDF or `.ai` file that can't be opened without a password or can't be read at all, a PDF + /// or `.ai` file listing an editing file whose data can't be resolved, or editing data that + /// doesn't read as a native document. Unreadable, } @@ -136,7 +137,12 @@ fn carried_document(name: &str, bytes: &[u8]) -> Carried { if super::place::document::is_pdf(name, bytes) { // A PDF that can't be opened may carry editing data all the same. return match vectorcraft_pdf::open_pdf(bytes, None) { - Ok(opened) => opened.editing().map_or(Carried::Absent, |e| read(&e.data)), + // An editing file listed whose data can't be resolved can't be checked either. + Ok(opened) => match opened.editing() { + Some(e) => read(&e.data), + None if opened.has_editing_file() => Carried::Unreadable, + None => Carried::Absent, + }, Err(_) => Carried::Unreadable, }; } diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index 61a4c64846..1474a84569 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -509,6 +509,15 @@ fn a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read() refused(&mut s, json!({"folder": out})); refused(&mut s, json!({"relink": false})); assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); + // A PDF listing the editing file without its data (`EF` renamed, the same length). + let at = editable.windows(4).position(|w| w.starts_with(b"/EF") && !w[3].is_ascii_alphanumeric()).expect("the editing file's EF"); + let mut detached = editable.clone(); + detached[at..at + 3].copy_from_slice(b"/XF"); + assert!(vectorcraft_pdf::editing(&detached).is_none(), "the editing data can't be resolved"); + write(&pdf, &detached); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"relink": false})); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); // A PDF without editing data. write(&pdf, &plain); assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1); diff --git a/crates/engine/tests/plugin_export.rs b/crates/engine/tests/plugin_export.rs index 1f47b76e52..a8de5429dc 100644 --- a/crates/engine/tests/plugin_export.rs +++ b/crates/engine/tests/plugin_export.rs @@ -388,4 +388,6 @@ fn a_confined_exporter_is_refused_stored_paths_outside_the_read_roots() { let mut found = vec![]; strings_in(&serde_json::from_slice(&std::fs::read(r["files"][0].as_str().unwrap()).unwrap()).unwrap(), &mut found); assert!(!found.contains(&placed), "{found:?}"); + let _ = std::fs::remove_dir_all(&away); + let _ = std::fs::remove_dir_all(&home); } diff --git a/crates/pdf/src/editing.rs b/crates/pdf/src/editing.rs index a8dd48628c..bcdf6a9b1d 100644 --- a/crates/pdf/src/editing.rs +++ b/crates/pdf/src/editing.rs @@ -77,12 +77,33 @@ pub fn editing_with(bytes: &[u8], password: Option<&str>) -> Option { editing_in(&crate::pages::open(bytes, password).ok()?) } +/// The file specification of the editing file among a parsed PDF's attachments, if any, and whether +/// a name tree key names the editing file (set also when its file specification can't be read). +fn editing_file_spec(pdf: &Pdf) -> (Option>, bool) { + let xref = pdf.xref(); + let Some(tree) = xref + .get::>(xref.root_id()) + .and_then(|catalog| catalog.get::>(b"Names")) + .and_then(|names| names.get::>(b"EmbeddedFiles")) + else { + return (None, false); + }; + let mut keyed = false; + let spec = editing_spec(&tree, 0, &mut HashSet::new(), &mut keyed, xref); + (spec, keyed) +} + +/// Does a parsed PDF list the editing file among its attachments, also when [`editing_in`] can't +/// read it (its file specification, its `EF` dictionary or its `F` or `UF` stream can't be +/// resolved)? +pub(crate) fn has_editing_file_in(pdf: &Pdf) -> bool { + let (spec, keyed) = editing_file_spec(pdf); + spec.is_some() || keyed +} + /// [`editing`] of a parsed PDF. pub(crate) fn editing_in(pdf: &Pdf) -> Option { - let xref = pdf.xref(); - let catalog = xref.get::>(xref.root_id())?; - let tree = catalog.get::>(b"Names")?.get::>(b"EmbeddedFiles")?; - let spec = editing_spec(&tree, 0, &mut HashSet::new(), xref)?; + let spec = editing_file_spec(pdf).0?; let files = spec.get::>(b"EF")?; let stream = files.get::>(b"F").or_else(|| files.get::>(b"UF"))?; let data = stream.decoded().map(|d| d.into_owned()).unwrap_or_default(); @@ -98,8 +119,21 @@ pub(crate) fn editing_in(pdf: &Pdf) -> Option { /// The file specification of the editing file in the name tree node `node`. `seen` holds the indirect /// nodes already searched, so a node shared by many `Kids` arrays is searched once, not once per path. -fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet, xref: &'a XRef) -> Option> { +/// `keyed` is set when a key searched names the editing file. +fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet, keyed: &mut bool, xref: &'a XRef) -> Option> { if let Some(names) = node.get::>(b"Names") { + // The keys read as written, so a value that can't be resolved doesn't shift the pairs. + let mut raw = items(&names); + while let (Some(key), Some(_)) = (raw.next(), raw.next()) { + let key = match key { + MaybeRef::NotRef(Object::String(key)) => Some(key), + MaybeRef::Ref(r) => xref.get::>(r.into()), + MaybeRef::NotRef(_) => None, + }; + if key.is_some_and(|key| is_editing_name(&key)) { + *keyed = true; + } + } let mut items = names.iter::>(); while let (Some(_), Some(spec)) = (items.next(), items.next()) { if let Object::Dict(spec) = spec @@ -121,17 +155,20 @@ fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet kid, _ => return None, }; - editing_spec(&kid, depth + 1, seen, xref) + editing_spec(&kid, depth + 1, seen, keyed, xref) }) } /// A file specification naming the editing file (current or legacy name), in any text string /// encoding. fn is_editing_file(spec: &Dict<'_>) -> bool { - [&b"UF"[..], b"F"].into_iter().filter_map(|k| spec.get::>(k)).any(|name| { - let name = text_string(name.as_bytes()); - name == EDITING_FILE || name == LEGACY_EDITING_FILE - }) + [&b"UF"[..], b"F"].into_iter().filter_map(|k| spec.get::>(k)).any(|name| is_editing_name(&name)) +} + +/// A text string that is the editing file's name (current or legacy), in any encoding. +fn is_editing_name(name: &PdfString<'_>) -> bool { + let name = text_string(name.as_bytes()); + name == EDITING_FILE || name == LEGACY_EDITING_FILE } /// The most decoded page content [`page_hash`] reads in all (bytes). diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 683a14d1c3..4d667fa863 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -261,6 +261,12 @@ impl Opened { crate::editing::editing_in(&self.pdf) } + /// Does the PDF list the editing file among its attachments, also when + /// [`editing`](Self::editing) can't read it? + pub fn has_editing_file(&self) -> bool { + crate::editing::has_editing_file_in(&self.pdf) + } + /// The private data of an Illustrator `.ai`, as [`illustrator_data`] reads it. pub fn illustrator_data(&self) -> Option> { private_data(&self.pdf) diff --git a/crates/pdf/src/tests/editing.rs b/crates/pdf/src/tests/editing.rs index c4f2900709..4346bc068d 100644 --- a/crates/pdf/src/tests/editing.rs +++ b/crates/pdf/src/tests/editing.rs @@ -237,3 +237,45 @@ fn a_file_name_written_as_utf16_is_found() { assert_eq!(e.data, b"hello", "/{key}"); } } + +#[test] +fn an_editing_file_whose_data_cannot_be_resolved_is_still_listed() { + // No `EF` dictionary, an `EF` without `F` or `UF`, and an `F` naming no object. + for ef in ["", "/EF << >>", "/EF << /F 9 0 R >>"] { + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [5 0 R] /Count 1 >>".to_string(), + "<< /Names [(a) 4 0 R] >>".to_string(), + format!("<< /Type /Filespec /UF ({EDITING_FILE}) {ef} >>"), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing(), None, "{ef:?}"); + assert!(opened.has_editing_file(), "{ef:?}"); + } + // A name tree key naming it, with a file specification that names no object or isn't one. + for spec in ["9 0 R", "(not a file specification)"] { + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(), + format!("<< /Names [(a) 9 0 R ({EDITING_FILE}) {spec}] >>"), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing(), None, "{spec}"); + assert!(opened.has_editing_file(), "{spec}"); + } + // The key written as an indirect string. + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(), + "<< /Names [5 0 R 9 0 R] >>".to_string(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + format!("({EDITING_FILE})"), + ]; + assert!(open_pdf(&raw_pdf(&objects), None).unwrap().has_editing_file()); + // A PDF without the editing file, and one with it. + assert!(!open_pdf(&export(&doc(), &PdfOptions::default()).unwrap(), None).unwrap().has_editing_file()); + let opened = open_pdf(&pdf_with(Some(b"native"), false).bytes, None).unwrap(); + assert!(opened.editing().is_some() && opened.has_editing_file()); +} From 72a6c4fe012297f8e9cbdd854dababe61e084e4b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 07:56:22 -0800 Subject: [PATCH 04/33] MCP: a confined package searches the whole attachment tree and keeps its read roots when written later The search for a PDF's editing file stopped 16 levels deep in the attachment name tree, so an editing file listed deeper read as absent and a confined package copied the PDF without checking its stored paths. The search now walks the tree at any depth, each indirect node once, up to 65,536 nodes; a tree with more nodes counts as listing the editing file, so a confined package refuses the PDF. A prepared package (Session::prepare_package) now keeps the read roots in force where it was prepared, and Package::write collects under them on any thread. --- crates/engine/src/cmd/package.rs | 12 +++-- crates/engine/src/tests/package.rs | 6 +++ crates/pdf/src/editing.rs | 75 +++++++++++++++++++----------- crates/pdf/src/tests/editing.rs | 34 ++++++++++++++ 4 files changed, 96 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index 99bcf455b7..324b29b20b 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -521,6 +521,9 @@ pub struct Package { root: Option, info: Option, doc: std::sync::Arc, + /// The read roots in force where the package was prepared: [`Package::write`] collects under + /// them. + scope: crate::file_access::ScopeHandle, } impl Session { @@ -567,21 +570,22 @@ fn prepare(s: &mut Session, p: &Value) -> Result { let doc = s.doc()?.doc.clone(); let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc }; let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone()); - Ok(Package { o, doc_path, links_from, stem, name, root, info, doc }) + let scope = crate::file_access::ScopeHandle::capture(); + Ok(Package { o, doc_path, links_from, stem, name, root, info, doc, scope }) } impl Package { /// Collect the linked files and fonts and write the package's files with `write` into /// `folder/name`, making its folders first, or into the zip without a folder → the reply of - /// `file.package`. + /// `file.package`, with the read roots in force where it was prepared, on any thread. pub fn write(self, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { - collect_and_write(self, write) + self.scope.clone().run(|| collect_and_write(self, write)) } } /// [`Package::write`]. fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { - let Package { o, doc_path, links_from, stem, name, root, info, doc: original } = package; + let Package { o, doc_path, links_from, stem, name, root, info, doc: original, scope: _ } = package; let mut doc = (*original).clone(); let doc_name = format!("{stem}.{}", vectorcraft_format::EXTENSION); let base = LinkBase { doc: Some(&doc_path), relative: Some(&links_from) }; diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index 1474a84569..040cd47424 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -508,6 +508,12 @@ fn a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read() write(&pdf, &locked); refused(&mut s, json!({"folder": out})); refused(&mut s, json!({"relink": false})); + // A package prepared in the confined request and written on another thread. + let prepared = crate::file_access::confine(Some(&roots), || s.prepare_package(&json!({"folder": out}))).unwrap(); + let e = + std::thread::spawn(move || prepared.write(&mut |_, _| Ok(())).map(|_| ()).map_err(|e| e.to_string())).join().unwrap().expect_err("refused"); + assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{e}"); + assert!(!std::path::Path::new(&out).exists()); assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); // A PDF listing the editing file without its data (`EF` renamed, the same length). let at = editable.windows(4).position(|w| w.starts_with(b"/EF") && !w[3].is_ascii_alphanumeric()).expect("the editing file's EF"); diff --git a/crates/pdf/src/editing.rs b/crates/pdf/src/editing.rs index bcdf6a9b1d..e19849f0d8 100644 --- a/crates/pdf/src/editing.rs +++ b/crates/pdf/src/editing.rs @@ -27,8 +27,8 @@ const DESCRIPTION: &str = "VectorCraft editing data; page hash "; /// Stands for the hash while the PDF is written: as long as a hash, so writing the hash over it /// keeps every offset. const PLACEHOLDER: &str = "0000000000000000"; -/// Deepest name tree searched for the editing file. -const MAX_DEPTH: usize = 16; +/// The most name tree nodes searched for the editing file. +const MAX_NODES: usize = 1 << 16; /// The native document a PDF carries ([`crate::PdfSettings::preserve_editing`]). #[derive(Clone, Debug, PartialEq, Eq)] @@ -78,7 +78,8 @@ pub fn editing_with(bytes: &[u8], password: Option<&str>) -> Option { } /// The file specification of the editing file among a parsed PDF's attachments, if any, and whether -/// a name tree key names the editing file (set also when its file specification can't be read). +/// the attachments may list it: a name tree key names the editing file (set also when its file +/// specification can't be read), or the name tree has more than [`MAX_NODES`] nodes to search. fn editing_file_spec(pdf: &Pdf) -> (Option>, bool) { let xref = pdf.xref(); let Some(tree) = xref @@ -88,17 +89,17 @@ fn editing_file_spec(pdf: &Pdf) -> (Option>, bool) { else { return (None, false); }; - let mut keyed = false; - let spec = editing_spec(&tree, 0, &mut HashSet::new(), &mut keyed, xref); - (spec, keyed) + let mut maybe = false; + let spec = editing_spec(tree, &mut maybe, xref); + (spec, maybe) } /// Does a parsed PDF list the editing file among its attachments, also when [`editing_in`] can't /// read it (its file specification, its `EF` dictionary or its `F` or `UF` stream can't be -/// resolved)? +/// resolved)? Also true when the name tree is too large to search to its end. pub(crate) fn has_editing_file_in(pdf: &Pdf) -> bool { - let (spec, keyed) = editing_file_spec(pdf); - spec.is_some() || keyed + let (spec, maybe) = editing_file_spec(pdf); + spec.is_some() || maybe } /// [`editing`] of a parsed PDF. @@ -117,10 +118,43 @@ pub(crate) fn editing_in(pdf: &Pdf) -> Option { Some(Editing { data, intact }) } -/// The file specification of the editing file in the name tree node `node`. `seen` holds the indirect -/// nodes already searched, so a node shared by many `Kids` arrays is searched once, not once per path. -/// `keyed` is set when a key searched names the editing file. -fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet, keyed: &mut bool, xref: &'a XRef) -> Option> { +/// The file specification of the editing file in the name tree `tree`, searched in order at any +/// depth, [`MAX_NODES`] nodes at most. An indirect node is searched once, so a node shared by many +/// `Kids` arrays is not searched once per path. `maybe` is set when a key searched names the editing +/// file, or when nodes are left unsearched. +fn editing_spec<'a>(tree: Dict<'a>, maybe: &mut bool, xref: &'a XRef) -> Option> { + let mut seen = HashSet::::new(); + let mut nodes = vec![tree]; + // Nodes still to be searched, counting the ones waiting in `nodes`. + let mut left = MAX_NODES - 1; + while let Some(node) = nodes.pop() { + if let Some(spec) = node_spec(&node, maybe, xref) { + return Some(spec); + } + let Some(kids) = node.get::>(b"Kids") else { continue }; + // Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The + // reference is checked before the kid is read, so a shared kid is read once. + let mut kids: Vec> = items(&kids) + .filter_map(|raw| match raw { + MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::>(r.into()), + MaybeRef::NotRef(Object::Dict(kid)) => Some(kid), + _ => None, + }) + .take(left.saturating_add(1)) + .collect(); + if kids.len() > left { + *maybe = true; + kids.truncate(left); + } + left -= kids.len(); + nodes.extend(kids.into_iter().rev()); + } + None +} + +/// The file specification of the editing file among the name tree node `node`'s own `Names`. +/// `keyed` is set when a key names the editing file. +fn node_spec<'a>(node: &Dict<'a>, keyed: &mut bool, xref: &'a XRef) -> Option> { if let Some(names) = node.get::>(b"Names") { // The keys read as written, so a value that can't be resolved doesn't shift the pairs. let mut raw = items(&names); @@ -143,20 +177,7 @@ fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet= MAX_DEPTH { - return None; - } - let kids = node.get::>(b"Kids")?; - // Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The - // reference is checked before the kid is read, so a shared kid is read once. - items(&kids).find_map(|raw| { - let kid = match raw { - MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::>(r.into())?, - MaybeRef::NotRef(Object::Dict(kid)) => kid, - _ => return None, - }; - editing_spec(&kid, depth + 1, seen, keyed, xref) - }) + None } /// A file specification naming the editing file (current or legacy name), in any text string diff --git a/crates/pdf/src/tests/editing.rs b/crates/pdf/src/tests/editing.rs index 4346bc068d..6417f6b231 100644 --- a/crates/pdf/src/tests/editing.rs +++ b/crates/pdf/src/tests/editing.rs @@ -279,3 +279,37 @@ fn an_editing_file_whose_data_cannot_be_resolved_is_still_listed() { let opened = open_pdf(&pdf_with(Some(b"native"), false).bytes, None).unwrap(); assert!(opened.editing().is_some() && opened.has_editing_file()); } + +#[test] +fn an_editing_file_deep_in_the_name_tree_is_found() { + // Objects 4..=203 are a chain of 200 name tree nodes, each listing the next one; the editing + // file sits in the leaf (object 204), with its data or naming data that can't be resolved. + for ef in ["/EF << /F 206 0 R >>", "/EF << /F 999 0 R >>"] { + let mut objects = vec![ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [207 0 R] /Count 1 >>".to_string(), + "<< /Kids [4 0 R] >>".to_string(), + ]; + for node in 4..=203 { + objects.push(format!("<< /Kids [{} 0 R] >>", node + 1)); + } + objects.push("<< /Names [(a) 205 0 R] >>".to_string()); + objects.push(format!("<< /Type /Filespec /UF ({EDITING_FILE}) {ef} >>")); + objects.push("<< /Length 5 >>\nstream\nhello\nendstream".to_string()); + objects.push("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string()); + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert!(opened.has_editing_file(), "{ef}"); + let data = opened.editing().map(|e| e.data); + assert_eq!(data.as_deref(), ef.contains("206").then_some(&b"hello"[..]), "{ef}"); + } + // A name tree with more nodes than are searched may list it. + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(), + format!("<< /Kids [{}] >>", "<< /Names [] >> ".repeat(70_000)), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing(), None); + assert!(opened.has_editing_file()); +} From 466b93f4d0e5c083fe6b755b551cfcfabe17bce1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 09:25:44 -0800 Subject: [PATCH 05/33] MCP: a confined package refuses a PDF whose attachment search was cut short When a PDF's attachment name tree has more nodes than the editing-file search reads (65,536), a confined package still copied the PDF if the search had found a readable editing file, so attachments past the limit went unchecked. The search now walks on after finding the editing file, reading only the Kids, and records whether nodes were left unsearched. Under read roots, file.package refuses such a PDF with the error for editing data that can't be read, even when an editing file was read. Opening the PDF is unchanged: it reads the first editing file found. --- crates/engine/src/cmd/package.rs | 7 +++- crates/engine/src/tests/package.rs | 40 ++++++++++++++++++++ crates/pdf/src/editing.rs | 59 ++++++++++++++++++++---------- crates/pdf/src/pages.rs | 6 +++ crates/pdf/src/tests/editing.rs | 27 +++++++++++++- 5 files changed, 116 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index 324b29b20b..b79ee49a67 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -122,8 +122,9 @@ enum Carried { Readable(Box), /// The file is a native document, or carries one, that can't be read: a damaged native file, /// a PDF or `.ai` file that can't be opened without a password or can't be read at all, a PDF - /// or `.ai` file listing an editing file whose data can't be resolved, or editing data that - /// doesn't read as a native document. + /// or `.ai` file listing an editing file whose data can't be resolved, a PDF or `.ai` file + /// whose attachments are too many to search to their end, or editing data that doesn't read as + /// a native document. Unreadable, } @@ -137,6 +138,8 @@ fn carried_document(name: &str, bytes: &[u8]) -> Carried { if super::place::document::is_pdf(name, bytes) { // A PDF that can't be opened may carry editing data all the same. return match vectorcraft_pdf::open_pdf(bytes, None) { + // Attachments left unsearched may list another editing file, which can't be checked. + Ok(opened) if opened.editing_search_cut() => Carried::Unreadable, // An editing file listed whose data can't be resolved can't be checked either. Ok(opened) => match opened.editing() { Some(e) => read(&e.data), diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index 040cd47424..6d808c731d 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -528,6 +528,14 @@ fn a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read() write(&pdf, &plain); assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1); std::fs::remove_dir_all(&out).unwrap(); + // A PDF whose attachments are too many to search to their end, with a readable editing file + // listed before the ones left unsearched. + let cut = attachments_cut_short(&vectorcraft_pdf::editing(&editable).unwrap().data); + assert!(vectorcraft_pdf::editing(&cut).is_some(), "the editing data is read"); + write(&pdf, &cut); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"relink": false})); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); // A native document that doesn't load, rewritten or copied as it is. let mut s = poster(&native); write(&native, b"not a document"); @@ -536,6 +544,38 @@ fn a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read() assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); } +/// A one-page PDF carrying `native` as its editing file, listed first in an attachment name tree +/// whose second subtree has 70,000 nodes, more than are searched. +fn attachments_cut_short(native: &[u8]) -> Vec { + let name = vectorcraft_pdf::EDITING_FILE; + let mut stream = format!("<< /Length {} >>\nstream\n", native.len()).into_bytes(); + stream.extend_from_slice(native); + stream.extend_from_slice(b"\nendstream"); + let objects = [ + b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_vec(), + b"<< /Type /Pages /Kids [6 0 R] /Count 1 >>".to_vec(), + format!("<< /Kids [4 0 R << /Kids [{}] >>] >>", "<< /Names [] >> ".repeat(70_000)).into_bytes(), + format!("<< /Names [({name}) << /Type /Filespec /UF ({name}) /EF << /F 5 0 R >> >>] >>").into_bytes(), + stream, + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>".to_vec(), + ]; + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, body) in objects.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(body); + out.extend_from_slice(b"\nendobj\n"); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes()); + for at in &offsets { + out.extend_from_slice(format!("{at:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes()); + out +} + /// A missing link stored as a path relative to the document names a file inside a confined /// request's read root: the package report and Document Info give its stored path. #[test] diff --git a/crates/pdf/src/editing.rs b/crates/pdf/src/editing.rs index e19849f0d8..2fccfb393c 100644 --- a/crates/pdf/src/editing.rs +++ b/crates/pdf/src/editing.rs @@ -77,34 +77,50 @@ pub fn editing_with(bytes: &[u8], password: Option<&str>) -> Option { editing_in(&crate::pages::open(bytes, password).ok()?) } -/// The file specification of the editing file among a parsed PDF's attachments, if any, and whether -/// the attachments may list it: a name tree key names the editing file (set also when its file -/// specification can't be read), or the name tree has more than [`MAX_NODES`] nodes to search. -fn editing_file_spec(pdf: &Pdf) -> (Option>, bool) { +/// What the search of a parsed PDF's attachments for the editing file found ([`editing_file_spec`]). +struct Search<'a> { + /// The editing file's file specification, if one was found. + spec: Option>, + /// A name tree key searched names the editing file (set also when its file specification + /// can't be read). + keyed: bool, + /// The name tree has more than [`MAX_NODES`] nodes, so nodes were left unsearched. + cut: bool, +} + +/// The search of a parsed PDF's attachments for the editing file. +fn editing_file_spec(pdf: &Pdf) -> Search<'_> { let xref = pdf.xref(); let Some(tree) = xref .get::>(xref.root_id()) .and_then(|catalog| catalog.get::>(b"Names")) .and_then(|names| names.get::>(b"EmbeddedFiles")) else { - return (None, false); + return Search { spec: None, keyed: false, cut: false }; }; - let mut maybe = false; - let spec = editing_spec(tree, &mut maybe, xref); - (spec, maybe) + let (mut keyed, mut cut) = (false, false); + let spec = editing_spec(tree, &mut keyed, &mut cut, xref); + Search { spec, keyed, cut } } /// Does a parsed PDF list the editing file among its attachments, also when [`editing_in`] can't /// read it (its file specification, its `EF` dictionary or its `F` or `UF` stream can't be /// resolved)? Also true when the name tree is too large to search to its end. pub(crate) fn has_editing_file_in(pdf: &Pdf) -> bool { - let (spec, maybe) = editing_file_spec(pdf); - spec.is_some() || maybe + let search = editing_file_spec(pdf); + search.spec.is_some() || search.keyed || search.cut +} + +/// Is a parsed PDF's attachment name tree too large to search to its end (more than [`MAX_NODES`] +/// nodes)? It may then list an editing file that [`editing_in`] doesn't find, besides the one it +/// reads. +pub(crate) fn editing_search_cut_in(pdf: &Pdf) -> bool { + editing_file_spec(pdf).cut } /// [`editing`] of a parsed PDF. pub(crate) fn editing_in(pdf: &Pdf) -> Option { - let spec = editing_file_spec(pdf).0?; + let spec = editing_file_spec(pdf).spec?; let files = spec.get::>(b"EF")?; let stream = files.get::>(b"F").or_else(|| files.get::>(b"UF"))?; let data = stream.decoded().map(|d| d.into_owned()).unwrap_or_default(); @@ -118,18 +134,21 @@ pub(crate) fn editing_in(pdf: &Pdf) -> Option { Some(Editing { data, intact }) } -/// The file specification of the editing file in the name tree `tree`, searched in order at any -/// depth, [`MAX_NODES`] nodes at most. An indirect node is searched once, so a node shared by many -/// `Kids` arrays is not searched once per path. `maybe` is set when a key searched names the editing -/// file, or when nodes are left unsearched. -fn editing_spec<'a>(tree: Dict<'a>, maybe: &mut bool, xref: &'a XRef) -> Option> { +/// The first file specification of the editing file in the name tree `tree`, searched in order at +/// any depth, [`MAX_NODES`] nodes at most. After the editing file is found, the walk goes on to the +/// end of the tree, or to the node limit, without reading the nodes' `Names`. An indirect node is +/// searched once, so a node shared by many `Kids` arrays is not searched once per path. `keyed` is +/// set when a key searched names the editing file, and `cut` when nodes are left unsearched. +fn editing_spec<'a>(tree: Dict<'a>, keyed: &mut bool, cut: &mut bool, xref: &'a XRef) -> Option> { let mut seen = HashSet::::new(); let mut nodes = vec![tree]; + let mut found = None; // Nodes still to be searched, counting the ones waiting in `nodes`. let mut left = MAX_NODES - 1; while let Some(node) = nodes.pop() { - if let Some(spec) = node_spec(&node, maybe, xref) { - return Some(spec); + // Once the editing file is found, only the `Kids` are read, to learn whether the tree is cut. + if found.is_none() { + found = node_spec(&node, keyed, xref); } let Some(kids) = node.get::>(b"Kids") else { continue }; // Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The @@ -143,13 +162,13 @@ fn editing_spec<'a>(tree: Dict<'a>, maybe: &mut bool, xref: &'a XRef) -> Option< .take(left.saturating_add(1)) .collect(); if kids.len() > left { - *maybe = true; + *cut = true; kids.truncate(left); } left -= kids.len(); nodes.extend(kids.into_iter().rev()); } - None + found } /// The file specification of the editing file among the name tree node `node`'s own `Names`. diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 4d667fa863..85aafef103 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -267,6 +267,12 @@ impl Opened { crate::editing::has_editing_file_in(&self.pdf) } + /// Is the PDF's attachment name tree too large to search to its end? It may then list an + /// editing file that [`editing`](Self::editing) doesn't find, besides the one it reads. + pub fn editing_search_cut(&self) -> bool { + crate::editing::editing_search_cut_in(&self.pdf) + } + /// The private data of an Illustrator `.ai`, as [`illustrator_data`] reads it. pub fn illustrator_data(&self) -> Option> { private_data(&self.pdf) diff --git a/crates/pdf/src/tests/editing.rs b/crates/pdf/src/tests/editing.rs index 6417f6b231..b58c953c2f 100644 --- a/crates/pdf/src/tests/editing.rs +++ b/crates/pdf/src/tests/editing.rs @@ -311,5 +311,30 @@ fn an_editing_file_deep_in_the_name_tree_is_found() { ]; let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); assert_eq!(opened.editing(), None); - assert!(opened.has_editing_file()); + assert!(opened.has_editing_file() && opened.editing_search_cut()); + // One that lists a readable editing file before the nodes left unsearched and another after + // them: the first is read, and the search reads as cut short. + let leaf = |stream: u32| format!("<< /Names [({EDITING_FILE}) << /Type /Filespec /UF ({EDITING_FILE}) /EF << /F {stream} 0 R >> >>] >>"); + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [8 0 R] /Count 1 >>".to_string(), + format!("<< /Kids [4 0 R {}5 0 R] >>", "<< /Names [] >> ".repeat(70_000)), + leaf(6), + leaf(7), + "<< /Length 5 >>\nstream\nfirst\nendstream".to_string(), + "<< /Length 6 >>\nstream\nsecond\nendstream".to_string(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing().map(|e| e.data).as_deref(), Some(&b"first"[..])); + assert!(opened.has_editing_file() && opened.editing_search_cut()); + // The same, with the nodes past the limit in a subtree after the one holding the first. + let mut objects = objects; + objects[2] = format!("<< /Kids [4 0 R << /Kids [{}5 0 R] >>] >>", "<< /Names [] >> ".repeat(70_000)); + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing().map(|e| e.data).as_deref(), Some(&b"first"[..])); + assert!(opened.has_editing_file() && opened.editing_search_cut()); + // A tree searched to its end. + let opened = open_pdf(&pdf_with(Some(b"native"), false).bytes, None).unwrap(); + assert!(opened.editing().is_some() && !opened.editing_search_cut()); } From 80cf2172f1c258e685d7e3b3162c00f805cba705 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 10:35:53 -0800 Subject: [PATCH 06/33] Tests: drop the confined single-file PDF test of several assets `assets.export` now refuses `pdfs: "single"` with assets, layers and `selection: "each"` before any file is checked or written (70fdab8445 on main), so the test's request no longer reaches the link check and fails with that refusal. A single-file PDF is now written only for artboards, whose items all hold the same document. --- crates/engine/src/tests/links.rs | 28 ---------------------------- 1 file changed, 28 deletions(-) diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 87dd7453f6..313d573206 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -2542,34 +2542,6 @@ fn confined_screens_rows_check_the_artboard_each_file_holds() { } } -/// A confined caller's single-file PDF with Preserve Editing of several assets carries the first -/// asset's document alone, so only that document is checked: an image linked outside the read roots in a later asset does -/// not refuse it, and one in the first asset does. -#[test] -fn confined_single_file_pdf_checks_the_document_it_carries() { - use crate::file_access::{AutomationRoots, confine}; - - let away = Folder::new("single-pdf-away"); - let home = Folder::new("single-pdf-home"); - let photo = away.file("photo.png"); - write(&photo, &png(60, 30, RED)); - let mut s = session(); - let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); - let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap(); - let placed = place(&mut s, &photo); - let mut assets = vec![]; - for id in [rect, placed] { - assets.push(s.execute("assets.add", &json!({"ids": [id.0]})).unwrap()["assets"][0].as_u64().unwrap()); - } - let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); - let p = |ids: &[u64], folder: &str| json!({"assets": ids, "folder": home.file(folder), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]}); - let r = confine(roots.as_ref(), || s.execute("assets.export", &p(&assets, "first-plain"))).unwrap_or_else(|e| panic!("{e}")); - assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{r}"); - let reversed = [assets[1], assets[0]]; - let e = confine(roots.as_ref(), || s.execute("assets.export", &p(&reversed, "first-linked"))).expect_err("first asset links outside").to_string(); - assert!(e.contains("a linked image file is outside the read roots"), "{e}"); -} - /// A confined caller's native outputs (a native file or template, an EPS or `.ai` file, a PDF with /// Preserve Editing, a package's document) carry the document without the Export for Screens /// folder when it is outside the read roots, with the other export settings and the art; the open From 58d53b477a3e1f98513f01893b8999e023c165e3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 11:27:35 -0800 Subject: [PATCH 07/33] Type: the font menu's Document filter counts type in scatter brushes The Document filter listed the families of type in layers, symbols, patterns and graph designs, but not type kept in the art of a stored brush. A scatter brush draws copies of its art along a stroke, type included, so a family used only there was missing from the filter. The filter now reads the stored brush library and counts type in each scatter brush's art. Art and pattern brushes leave type out when they bend their art, so their type is not counted. Malformed library entries are skipped. --- crates/ui-egui/src/font_menu.rs | 16 ++++++--- crates/ui-egui/src/font_menu/tests.rs | 49 +++++++++++++++++++++++++++ docs/target-app-parity.md | 2 +- 3 files changed, 62 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index d5368d1fa4..d5939750f8 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -500,10 +500,10 @@ impl Filters { /// The families the type in `doc` is set in, lowercase and by the name the menu lists them under /// ([`vectorcraft_text::FontDb::canonical`]): the runs of every text object in the layers, symbols, -/// patterns and graph designs, hidden, locked and masked ones included, with a composite font named -/// as such. A pattern being edited is read from its editing layer only. Each run's family is looked -/// up with its style, so a family and style split from a PostScript name (`Honoka`, `Mincho`) find -/// the installed font of that name. Styles no type uses are left out. +/// patterns, graph designs and stored scatter brushes, hidden, locked and masked ones included, with +/// a composite font named as such. A pattern being edited is read from its editing layer only. Each +/// run's family is looked up with its style, so a family and style split from a PostScript name +/// (`Honoka`, `Mincho`) find the installed font of that name. Styles no type uses are left out. fn document_families(db: &vectorcraft_text::FontDb, doc: &vectorcraft_doc::Document) -> HashSet { // Each family and style once, so a document with many runs in a few fonts looks each one up // once. @@ -531,6 +531,14 @@ fn document_families(db: &vectorcraft_text::FontDb, doc: &vectorcraft_doc::Docum for n in doc.layers.iter().map(|l| &**l).chain(doc.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(designs) { vectorcraft_doc::swatches::walk_with_masks(n, &mut add); } + // A scatter brush draws copies of its art's type along a stroke; art and pattern brushes drop + // type when they bend their art. Malformed library entries are skipped. + let brushes = doc.unknown.get(vectorcraft_brush::DOC_KEY).map(vectorcraft_brush::parse_library).unwrap_or_default(); + for b in &brushes { + if let vectorcraft_brush::BrushKind::Scatter(s) = &b.kind { + vectorcraft_doc::swatches::walk_with_masks(&s.art, &mut add); + } + } named.iter().flat_map(|(f, styles)| styles.iter().map(move |s| db.canonical(f, s).0.to_lowercase())).collect() } diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 958a6c1af1..a2417fa502 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -1221,6 +1221,55 @@ fn the_document_filter_counts_type_in_graph_designs() { assert_eq!(names, ["inter", "jetbrains mono"]); } +/// Type in the art of a stored scatter brush counts as the document's type, as a scatter stroke +/// draws it, after a malformed library entry too. Type in an art or pattern brush's art does not, +/// as those brushes leave type out when they bend their art. +#[test] +fn the_document_filter_counts_type_in_scatter_brushes() { + let mut app = app_with_type(&["Inter"]); + let mut art = |font: &str| { + let id = app.run("text.create", serde_json::json!({"x": 20, "y": 90, "text": "Dot", "font": font})).unwrap()["id"].as_u64().unwrap(); + let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().expect("the new type"); + app.run("edit.undo", serde_json::json!({})).unwrap(); + node + }; + let (scatter, bent, tiled) = (art("JetBrains Mono"), art("Source Serif 4"), art("Source Sans 3")); + let brush = |name: &str, kind| serde_json::to_value(vectorcraft_brush::Brush { name: name.into(), kind }).unwrap(); + let library = serde_json::json!([ + {"name": "Broken", "type": "scatter", "art": 7}, + brush("Art", vectorcraft_brush::BrushKind::Art(vectorcraft_brush::ArtBrush { art: bent, ..Default::default() })), + brush("Pattern", vectorcraft_brush::BrushKind::Pattern(vectorcraft_brush::PatternBrush { side: tiled, ..Default::default() })), + brush("Dots", vectorcraft_brush::BrushKind::Scatter(vectorcraft_brush::Scatter { art: scatter, ..Default::default() })), + ]); + let mut doc = (*app.session.active().unwrap().doc).clone(); + doc.unknown.insert(vectorcraft_brush::DOC_KEY.into(), library); + let db = vectorcraft_text::FontDb::global(); + let mut names: Vec<_> = super::document_families(db, &doc).into_iter().collect(); + names.sort(); + assert_eq!(names, ["inter", "jetbrains mono"]); +} + +/// A scatter brush made of type keeps its family in the Document filter after the type is deleted; +/// deleting the brush takes the family out, and undoing the deletion brings it back. +#[test] +fn the_document_filter_follows_a_scatter_brushs_edits_and_undo() { + let mut app = app_with_type(&["Inter"]); + let id = app.run("text.create", serde_json::json!({"x": 20, "y": 90, "text": "Dot", "font": "JetBrains Mono"})).unwrap()["id"].clone(); + let name = app.run("brush.new", serde_json::json!({"type": "scatter", "name": "Type Dots"})).unwrap()["name"].clone(); + app.run("edit.clear", serde_json::json!({"ids": [id]})).unwrap(); + let db = vectorcraft_text::FontDb::global(); + let families = |app: &crate::VectorcraftApp| { + let mut names: Vec<_> = super::document_families(db, &app.session.active().unwrap().doc).into_iter().collect(); + names.sort(); + names + }; + assert_eq!(families(&app), ["inter", "jetbrains mono"], "the brush's type"); + app.run("brush.delete", serde_json::json!({"name": name})).unwrap(); + assert_eq!(families(&app), ["inter"], "the brush deleted"); + app.run("edit.undo", serde_json::json!({})).unwrap(); + assert_eq!(families(&app), ["inter", "jetbrains mono"], "the deletion undone"); +} + /// A run whose family and style were split from a PostScript name (as an importer without the font /// splits one) counts under the family of the installed font of that name, found with its style. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..c86b2b8410 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1883,7 +1883,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Fonts:** a font is found by any of its names (family and style in every language of its name table, legacy family/style pairs, PostScript name), so documents from other apps open with the font they name; Find Font and `text.fonts` say for each font whether it was found exactly, by another name, substituted or missing, and how many glyphs are missing. PDF and `.ai` import brings Japanese text back as live type: CID fonts without a ToUnicode map read through the standard CMaps, vertical columns (WMode 1) as vertical type, letter spacing as tracking; a glyph is live type only when the installed font (in the closest style of its family) draws the same glyph, and text in a font that isn't installed comes in as live type shown in the fallback font until the font is installed (exports that draw it — PDF, EPS, EMF/WMF, raster, SVG outlines or embedded fonts — warn that they wrote the fallback font, and Print and Print Preview warn about the type that prints in it; `textAs: outlines` keeps the PDF's embedded glyphs). Two installed versions of one family and style (a font library keeping an old file beside a new one) both load, the first staying the one the family and style resolve to; PDF and `.ai` import tries each version when the glyphs differ, and type set in a version other than that one names it (`CharStyle::font_version`), which layout, the substituted-glyph highlight, Find Font, Package and Document Info follow. Fonts outside the font folders are listed too: those font services such as Adobe Fonts load on Windows, through DirectWrite and, for those only GDI lists, through GDI (#1258), and those apps and font managers register with CoreText on macOS (#579). When a document opens with fonts that aren't available, fonts used only in symbols included, a Missing Fonts dialog lists them after the linked-file questions, with Find Fonts (Type › Find Font on them) and Close. Its Find in Folder… (in Find Font too) searches a folder on several threads, reads only what the font scan reads of font files and skips app packages, the Program Files and ProgramData folders, the system's folders and the app data folders in a home folder; Add Fonts copies the font files the user chooses, suitcase fonts with their resource fork, into VectorCraft's own Fonts folder, which the desktop app and `vectorcraft-cli` read (`text.missingFonts`, `text.findFontFiles`, `text.addFontFiles`). 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). A variable font's type gets one slider and field per variation axis under the Character panel's Variable Font button, each named as the font names the axis (Weight, Width), so the type can be set between or past its named instances: the settings stay with the characters (`CharStyle::font_axes`, `text.setFormat {fontAxes}` and `text.setRangeStyle {fontAxes}`, clamped to each axis's range; `text.fontList {family, style}` lists the axes), and layout, outlines, the substituted-glyph highlight and PDF and SVG export (`font-variation-settings`, embedded fonts) use the font instanced at them. Another font or style clears them; legacy `.ai` export writes the style and warns that they are left out. The font menu's Font Technology › Variable (under the kind filter, as [Find, apply, and adjust variable fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-apply-and-adjust-variable-fonts.html) places Variable in the classification filter's Font Technology section) lists only the families with variation axes, a family with a variable file beside static ones included, and works together with the script, kind, ★ and search filters; it stays set from one opening to the next. Measured by `font_menu::tests::the_variable_filter_lists_only_variable_families`, `font_menu::tests::the_variable_filter_is_named_as_fonts_are`, `tests_axes::a_family_with_variation_axes_is_variable` and `tests_sysfonts::a_family_with_a_variable_file_beside_static_ones_is_variable`. - The font menu's Document filter (beside ★) lists only the families that type in the current document is set in, as the quick filter for fonts used in the document does on the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html). It works together with the search, script, kind, Variable and ★ filters, Recent Fonts and Show Similar Fonts, steers the closed field's wheel, follows edits and undo while the menu is open, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: hidden, locked, masked, symbol, pattern and graph design type counts, styles no type uses do not, a composite font lists under its own name, a family the document names but this computer lacks is not listed (Find Font reports it), a document without available fonts lists nothing with its own message, and with no document open the filter is unavailable. Measured by `font_menu::tests::the_document_filter_lists_the_families_the_documents_type_uses`, `font_menu::tests::the_document_filter_combines_with_the_others_and_follows_edits`, `font_menu::tests::the_document_filter_counts_type_in_graph_designs` and `font_menu::tests::the_document_filter_on_an_empty_document_or_none`. + The font menu's Document filter (beside ★) lists only the families that type in the current document is set in, as the quick filter for fonts used in the document does on the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html). It works together with the search, script, kind, Variable and ★ filters, Recent Fonts and Show Similar Fonts, steers the closed field's wheel, follows edits and undo while the menu is open, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: hidden, locked, masked, symbol, pattern and graph design type counts, as does type in the art of a stored scatter brush (art and pattern brushes leave type out when they bend their art, so their type does not count), styles no type uses do not, a composite font lists under its own name, a family the document names but this computer lacks is not listed (Find Font reports it), a document without available fonts lists nothing with its own message, and with no document open the filter is unavailable. Measured by `font_menu::tests::the_document_filter_lists_the_families_the_documents_type_uses`, `font_menu::tests::the_document_filter_combines_with_the_others_and_follows_edits`, `font_menu::tests::the_document_filter_counts_type_in_graph_designs`, `font_menu::tests::the_document_filter_counts_type_in_scatter_brushes`, `font_menu::tests::the_document_filter_follows_a_scatter_brushs_edits_and_undo` and `font_menu::tests::the_document_filter_on_an_empty_document_or_none`. The font menu's Recently Added filter (on its own row under Font Technology) lists only the installed families added in the last 30 days, the newest at the top, as the [user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=486) and the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) describe it (`vectorcraft_text::FontDb::recently_added`). It works together with the search, script, kind, Variable, ★ and Document filters, lists only the families every active filter matches, steers the closed field's wheel, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: a family is dated by the creation time of its newest font file on this computer (a file the file system keeps no creation time for, or one dated in the future, does not count), the 30th day is included, families added at the same instant are in name order, the recently used families appear in that order without the Recent Fonts section, Show Similar Fonts orders only the families the filter lists, a family leaves the list when its 30 days end while the menu is open, an empty list keeps the filter on and says no fonts match, and fonts bundled with the app or loaded from documents are never listed. Measured by `font_menu::tests::the_recently_added_filter_lists_new_families_newest_first`, `font_menu::tests::the_recently_added_filter_drops_families_as_their_30_days_end`, `font_menu::tests::the_recently_added_filter_lists_a_font_installed_just_now`, `tests::recently_added::families_added_in_the_last_30_days_are_listed_newest_first`, `tests::recently_added::a_family_is_dated_by_its_newest_valid_file` and `tests::sysfonts::installed_fonts_are_recently_added_by_their_files_creation_time`. The font database looks up a name that is neither a loaded nor an installed family among the other names of the loaded and installed fonts once for each style it is asked in, and keeps the answer until fonts are added or rescanned. Laying out a story of 1,000 paragraphs set in a font that is not installed, with 400 more fonts loaded, takes a median of 56 to 71 ms instead of 409 to 507 ms on Windows 11 (`CRAFT_FONTS_DIR= cargo test --release -p vectorcraft-text --lib missing_font_story_layout_timing -- --ignored --nocapture`). A font family removed while the app runs leaves the font menus when the app scans the font folders again (when its window comes to the front after a font folder changed, or Refresh Font List), also when type had used it: that type then draws in the fallback font and Find Font lists the font as missing, until the font is installed again and the folders are scanned. From a1e3d6b5bbb533efc91be3aea4794aa46900876c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 11:31:04 -0800 Subject: [PATCH 08/33] Graphic Styles: a style dropped on another with Alt replaces that style A graphic style dragged onto another style in the Graphic Styles panel with Alt held gives that style the dragged style's look. The replaced style keeps its name, place and id, and the art still linked to it takes the new look in one undo step; the dragged style and its art stay as they are. Without Alt the style moves, as before. graphicStyle.redefine takes {name, from} for this. A style dropped on itself, or on a style with the same look, records nothing. A `from` that names no style or is not a string, or `from` with `id`, is an error. --- crates/engine/src/cmd/style.rs | 63 ++++++++---- crates/engine/src/tests/styles.rs | 62 ++++++++++++ crates/ui-egui/src/panels/graphic_styles.rs | 105 +++++++++++++++++++- crates/ui-egui/src/widgets/drag.rs | 3 +- docs/mcp.md | 10 +- docs/target-app-parity.md | 1 + 6 files changed, 217 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 76287e490d..1b5fec0a3b 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -76,7 +76,7 @@ pub fn specs() -> Vec { "Redefine Graphic Style", ["Window", "Appearance"], None, - "{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}", + "{name?, id?} | {name, from} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. With `from`, the style takes the look of the style named `from` (its fills, strokes, effects, opacity, blend mode, isolate and knockout) and keeps its own name and place; `from` and the objects linked to it stay as they are, `from` naming the style itself or a style with the same look changes nothing, and `from` with `id` is an error. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}", has_doc, style_redefine ), @@ -489,22 +489,43 @@ pub(crate) fn style_json(g: &GraphicStyle) -> Value { fn style_redefine(s: &mut Session, p: &Value) -> Result { let cmd = "graphicStyle.redefine"; - let (src, n) = source(s, p, cmd)?; - let d = &s.doc()?.doc; - // A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links. - let n = super::appearance::look_holder(d, n); - let src = if n.id == src { src } else { n.id }; - let i = match str_param(p, "name") { - Some(name) => style_index(d, name)?, - None => n - .extras() - .graphic_style - .and_then(|id| d.graphic_style_by_id(id)) - .and_then(|g| d.graphic_style_index(&g.name)) - .ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?, + // The style to replace, its new look, and the object that look comes from (none for another style's look). + let (i, look, src) = match p.get("from") { + Some(from) => { + let from = from.as_str().ok_or_else(|| bad(cmd, "`from` must be a graphic style name"))?; + if p.get("id").is_some() { + return Err(bad(cmd, "pass `id` or `from`, not both")); + } + let name = str_param(p, "name").ok_or_else(|| bad(cmd, "missing name (the style `from` replaces)"))?; + let d = &s.doc()?.doc; + let (i, j) = (style_index(d, name)?, style_index(d, from)?); + // A style dropped on itself, or on a style with the same look, stays as it is. + let target = &d.graphic_styles[i]; + let look = GraphicStyle { name: target.name.clone(), id: target.id, ..d.graphic_styles[j].clone() }; + if i == j || look == *target { + return Ok(json!({ "name": name })); + } + (i, look, None) + } + None => { + let (src, n) = source(s, p, cmd)?; + let d = &s.doc()?.doc; + // A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links. + let n = super::appearance::look_holder(d, n); + let src = if n.id == src { src } else { n.id }; + let i = match str_param(p, "name") { + Some(name) => style_index(d, name)?, + None => n + .extras() + .graphic_style + .and_then(|id| d.graphic_style_by_id(id)) + .and_then(|g| d.graphic_style_index(&g.name)) + .ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?, + }; + (i, GraphicStyle::of(String::new(), captured(n), n), Some(src)) + } }; - let look = GraphicStyle::of(String::new(), captured(n), n); - let name = d.graphic_styles[i].name.clone(); + let name = s.doc()?.doc.graphic_styles[i].name.clone(); let chars = s.prefs.override_char_color; let before = s.doc()?.doc.clone(); s.edit_named("Redefine Graphic Style “{name}”", &name, false, |d, _| { @@ -513,7 +534,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { // Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the // source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the // source or as a linked object: the graph draws it again from the design. - let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && n.id != src); + let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src); let (follow, edited): (Vec, Vec) = linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old))); set_link(d, &edited, None); @@ -521,7 +542,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { // goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look. let mut follow_marks = super::graph::series_group_marks(d, &follow); let edited: HashSet = edited.into_iter().collect(); - follow_marks.retain(|nid| *nid != src && !edited.contains(nid)); + follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid)); super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks)); let g = d.graphic_styles[i].clone(); let mut shared = None; @@ -530,8 +551,10 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { } super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true); super::graph::capture_label_rows(d, &follow_marks); - let link = (!super::graph::is_design_art(d, src)).then_some(id); - set_link(d, &[src], link); + if let Some(src) = src { + let link = (!super::graph::is_design_art(d, src)).then_some(id); + set_link(d, &[src], link); + } Ok(()) })?; Ok(json!({ "name": name })) diff --git a/crates/engine/src/tests/styles.rs b/crates/engine/src/tests/styles.rs index 6f0242c662..dd5ca1d9f8 100644 --- a/crates/engine/src/tests/styles.rs +++ b/crates/engine/src/tests/styles.rs @@ -299,6 +299,68 @@ fn redefine_shares_one_appearance() { assert!(!Shared::ptr_eq(&node(&s, d).appearance, &nb.appearance)); } +/// Redefine with `from` gives a style another style's look: the style keeps its name, place and id, +/// its objects still linked follow, edited ones are unlinked, and `from` and its objects stay as +/// they are, in one undo step. A style replaced by itself or by a style with the same look records +/// nothing, and bad parameters are errors that change nothing. +#[test] +fn redefine_from_a_style_gives_the_style_that_look() { + let mut s = session(); + let (a, b, c) = linked_three(&mut s); + let d = rect(&mut s, 300.0); + set_fill(&mut s, d, "#0000ff"); + run(&mut s, "transparency.set", json!({"item": null, "opacity": 50, "blend": "multiply"})); + run(&mut s, "graphicStyle.new", json!({"name": "Blue"})); + set_fill(&mut s, c, "#00ff00"); + let names = |s: &Session| s.doc().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect::>(); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let (old, blue, order, before) = (style(&s, "S"), style(&s, "Blue"), names(&s), steps(&s)); + assert_eq!(run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "Blue"}))["name"], "S"); + assert_eq!(style(&s, "S"), GraphicStyle { name: "S".into(), id: old.id, ..blue.clone() }); + assert_eq!(names(&s), order); + let blue_paint = Paint::solid(Color::from_hex("#0000ff").unwrap()); + for id in [a, b] { + let n = node(&s, id); + assert_eq!((n.appearance.fill_paint(), n.opacity, n.blend), (blue_paint.clone(), 0.5, BlendMode::Multiply)); + } + assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]); + // The edited object keeps its look and is unlinked; Blue and its object are as they were. + assert_eq!(fill(&s, c), Paint::solid(Color::from_hex("#00ff00").unwrap())); + assert_eq!(node(&s, c).extras().graphic_style, None); + assert_eq!(style(&s, "Blue"), blue); + assert_eq!(linked(&mut s, "Blue"), vec![d.0]); + let step = s.doc().unwrap().history.undo.last().unwrap().clone(); + assert_eq!((step.label.as_str(), steps(&s)), ("Redefine Graphic Style “S”", before + 1)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(style(&s, "S"), old); + assert_eq!((fill(&s, a), fill(&s, b)), (Paint::solid(Color::WHITE), Paint::solid(Color::WHITE))); + assert_eq!(node(&s, c).extras().graphic_style, Some(old.id)); + run(&mut s, "edit.redo", json!({})); + assert_eq!(style(&s, "S").appearance, blue.appearance); + assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]); + run(&mut s, "edit.undo", json!({})); + + // A style replaced by itself, or by a copy with the same look, records nothing. + run(&mut s, "graphicStyle.duplicate", json!({"name": "Blue"})); + let before = steps(&s); + run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "S"})); + run(&mut s, "graphicStyle.redefine", json!({"name": "Blue copy", "from": "Blue"})); + assert_eq!(steps(&s), before); + assert_eq!(style(&s, "S"), old); + + // A style that does not exist, a `from` that is not a name, `from` with `id` and a missing `name` are errors. + for p in [ + json!({"name": "S", "from": "nope"}), + json!({"name": "nope", "from": "Blue"}), + json!({"name": "S", "from": 3}), + json!({"name": "S", "from": "Blue", "id": a.0}), + json!({"from": "Blue"}), + ] { + assert!(s.execute("graphicStyle.redefine", &p).is_err(), "{p}"); + } + assert_eq!((steps(&s), style(&s, "S")), (before, old)); +} + #[test] fn deleting_a_style_unlinks_and_renaming_keeps_links() { let mut s = session(); diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 6ff2243cfb..74e10d5ed5 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -3,7 +3,8 @@ //! shows the shape outlined in black and filled with white, under a red slash. Clicking a style applies it to the //! selection (Alt-click adds it on top); Shift-click adds to the panel's selection every style from //! the last one clicked without Shift through this one; Cmd/Ctrl-click adds or removes one; -//! double-click opens Graphic Style Options. Dragging a style moves it in the list, applies it +//! double-click opens Graphic Style Options. Dragging a style moves it in the list (dropped on +//! another style with Alt held, replaces that style with its look), applies it //! to the art it is dropped on (`canvas::panel_drop`), or, dropped on New Graphic Style, adds a //! copy of it and of the styles highlighted with it at the end of the list; art dragged off the //! canvas or the Appearance panel's thumbnail dropped on the panel becomes a new style, and @@ -368,6 +369,8 @@ struct Events { new_from: Option, /// Art or an appearance dropped on a style with Alt held: the style takes this object's look. replaced: Option<(String, NodeId)>, + /// A style dropped on another with Alt held: the second (`.0`) takes the first's (`.1`) look. + restyled: Option<(String, String)>, /// The style the right button is held on. large: Option, /// A style is dragged over a tile or row. @@ -387,7 +390,8 @@ fn clicked(ui: &Ui, resp: &Response, name: &str) -> Option { /// Clicks, drags and the right button on the tile or row `resp` of style `i` of `d` (`list`: rows /// stack downwards). A drag from it carries the style ([`PanelDrag::GraphicStyle`]); a style -/// dragged over it lands before or after it by the pointer's half. Art (its first object) or the +/// dragged over it lands before or after it by the pointer's half, or with Alt held outlines it +/// and, released there, replaces it with the dragged style's look. Art (its first object) or the /// Appearance panel's thumbnail held over it with Alt outlines it, and released there replaces the /// style with that object's look; without Alt it is left to the list ([`zone_input`]). fn cell_input(ui: &Ui, resp: &Response, d: &Document, i: usize, list: bool, ev: &mut Events) { @@ -414,6 +418,11 @@ fn cell_input(ui: &Ui, resp: &Response, d: &Document, i: usize, list: bool, ev: if moving == name { // Dropped on itself: it stays where it is. resp.dnd_release_payload::(); + } else if alt_held(ui) { + widgets::drop_target_outline(ui, resp.rect); + if resp.dnd_release_payload::().is_some() { + ev.restyled = Some((name.clone(), moving.clone())); + } } else { let r = resp.rect; let at = ui.input(|i| i.pointer.interact_pos()).unwrap_or(r.center()); @@ -531,6 +540,9 @@ fn act(app: &mut VectorcraftApp, ui: &Ui, s: &Shown, ev: Events, picker: bool) { { run(app, "graphicStyle.redefine", json!({ "name": name, "id": id.0 })); } + if let Some((name, from)) = ev.restyled { + run(app, "graphicStyle.redefine", json!({ "name": name, "from": from })); + } match ev.click { Some(Click::Pick(name, _)) if picker => { app.run("graphicStyle.apply", json!({"name": name, "add": alt_held(ui)})).ok(); @@ -1535,10 +1547,10 @@ mod tests { assert_eq!(doc(&app).graphic_style("Red").unwrap().appearance, red.appearance, "{view:?}"); app.run("edit.undo", json!({})).unwrap(); - // A style dragged onto Red with Alt moves and replaces nothing. + // A style dragged onto Red without Alt moves and replaces nothing. let last = n.last().unwrap().clone(); egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle(last.clone())); - frame_at(&mut app, at, release(at, alt), alt); + frame_at(&mut app, at, release(at, none), none); assert_eq!(names(&app)[0], last, "{view:?}"); assert_eq!(doc(&app).graphic_style("Red").unwrap().appearance, red.appearance, "{view:?}"); app.run("edit.undo", json!({})).unwrap(); @@ -1557,6 +1569,91 @@ mod tests { } } + /// A style dropped on another with Alt held replaces that style's look with its own: the + /// replaced style keeps its name, place and id, and its art follows, in one undo step; the + /// dragged style and its art stay as they are. Without Alt the style moves; dropped on itself + /// it does nothing. + #[test] + fn a_style_dropped_on_another_with_alt_replaces_that_style() { + let mut app = app(); + let rect = app.session.active().unwrap().doc.layers[0].children().unwrap()[0].id; + app.run("paint.setFill", json!({"color": "#ff0000", "ids": [rect.0]})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Red", "id": rect.0})).unwrap(); + app.run("graphicStyle.move", json!({"name": "Red", "to": 0})).unwrap(); + app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 20, "height": 20})).unwrap(); + let oval = app.session.active().unwrap().selection.objects[0]; + app.run("paint.setFill", json!({"color": "#00ff00", "ids": [oval.0]})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Green", "id": oval.0})).unwrap(); + let ctx = egui::Context::default(); + let screen = Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(260.0, 600.0))); + // One frame of the panel with `events` and `modifiers` held: whether a drop-target outline + // the size of one style's tile or row is drawn around `at`. + let frame_at = |app: &mut VectorcraftApp, at: egui::Pos2, events: Vec, modifiers: egui::Modifiers| { + let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect(); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: screen, events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + let accent = Tokens::get(&ctx).accent; + out.shapes.iter().any(|c| match &c.shape { + egui::Shape::Rect(r) => r.stroke.width == 1.5 && r.stroke.color == accent && r.rect.contains(at) && r.rect.height() < 45.0, + _ => false, + }) + }; + let release = |at: egui::Pos2, modifiers: egui::Modifiers| { + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers }; + vec![egui::Event::PointerMoved(at), up] + }; + let (none, alt) = (egui::Modifiers::default(), egui::Modifiers::ALT); + let doc = |app: &VectorcraftApp| app.session.active().unwrap().doc.clone(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let (red, green) = (doc(&app).graphic_style("Red").unwrap().clone(), doc(&app).graphic_style("Green").unwrap().clone()); + let (red_fill, green_fill) = (red.appearance.fill_paint(), green.appearance.fill_paint()); + assert_ne!(red_fill, green_fill); + // The first style: the top of the list's first row, or its first tile. + for (view, at) in [(View::SmallList, pos2(60.0, 9.0)), (View::Thumbnail, pos2(20.0, 20.0))] { + app.ui.graphic_styles_view = view; + frame_at(&mut app, at, vec![], none); + let n = names(&app); + assert_eq!(n[0], "Red", "{view:?}"); + let before = steps(&app); + // Held over Red with Alt it is outlined; without Alt it is not (the insertion marker shows instead). + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle("Green".into())); + assert!(!frame_at(&mut app, at, vec![egui::Event::PointerMoved(at)], none), "{view:?}: no outline without Alt"); + assert!(frame_at(&mut app, at, vec![egui::Event::PointerMoved(at)], alt), "{view:?}: outlined with Alt"); + assert_eq!((names(&app), steps(&app)), (n.clone(), before), "{view:?}: holding it there changes nothing"); + + // Released there with Alt: Red takes Green's look and keeps its name, place and id. + frame_at(&mut app, at, release(at, alt), alt); + let d = doc(&app); + assert_eq!(names(&app), n, "{view:?}: no style moves"); + let g = d.graphic_style("Red").unwrap(); + assert_eq!((g.id, &g.appearance), (red.id, &green.appearance), "{view:?}"); + assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), green_fill, "{view:?}: the linked rectangle follows"); + assert_eq!(d.node(rect).unwrap().extras().graphic_style, Some(red.id), "{view:?}"); + assert_eq!(d.graphic_style("Green").unwrap(), &green, "{view:?}: Green stays as it was"); + assert_eq!(d.node(oval).unwrap().extras().graphic_style, Some(green.id), "{view:?}: the oval stays linked to Green"); + assert_eq!(steps(&app), before + 1, "{view:?}: one undo step"); + app.run("edit.undo", json!({})).unwrap(); + let d = doc(&app); + assert_eq!(d.graphic_style("Red").unwrap(), &red, "{view:?}: undo restores the style"); + assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), red_fill, "{view:?}"); + assert_eq!(d.node(rect).unwrap().extras().graphic_style, Some(red.id), "{view:?}"); + + // Red dropped on itself with Alt changes nothing and records nothing. + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle("Red".into())); + frame_at(&mut app, at, release(at, alt), alt); + assert_eq!((names(&app), steps(&app)), (n.clone(), before), "{view:?}"); + assert_eq!(doc(&app).graphic_style("Red").unwrap(), &red, "{view:?}"); + + // Without Alt, Green moves before Red and Red keeps its look. + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle("Green".into())); + frame_at(&mut app, at, release(at, none), none); + assert_eq!(names(&app)[0], "Green", "{view:?}"); + assert_eq!(doc(&app).graphic_style("Red").unwrap(), &red, "{view:?}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(names(&app), n, "{view:?}"); + } + } + #[test] fn shift_click_selects_a_range_and_cmd_click_adds_or_removes_one_style() { let mut app = app(); diff --git a/crates/ui-egui/src/widgets/drag.rs b/crates/ui-egui/src/widgets/drag.rs index d801bcfa14..e98619cb7f 100644 --- a/crates/ui-egui/src/widgets/drag.rs +++ b/crates/ui-egui/src/widgets/drag.rs @@ -17,7 +17,8 @@ pub enum PanelDrag { /// replaces the style it is dropped on with it (`graphicStyle.redefine`). Appearance(vectorcraft_doc::NodeId), /// A Graphic Styles panel style: art it is dropped on takes it (`graphicStyle.apply` with its - /// `ids`); the panel moves it to where it is dropped. + /// `ids`); the panel moves it to where it is dropped, or with Alt held replaces the style it is + /// dropped on with its look (`graphicStyle.redefine` with `from`). GraphicStyle(String), /// The selected art, dragged off the canvas with the Selection tool: the Graphic Styles panel /// makes a style of the first object (`graphicStyle.new`), or with Alt held replaces the style diff --git a/docs/mcp.md b/docs/mcp.md index 211e172c7f..b95eb48433 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4313,8 +4313,14 @@ object's, type its characters'). `graphicStyle.apply {name, ids?}` gives the obj style's look: editing their appearance or transparency breaks the link, and `graphicStyle.redefine {name?, id?}` updates only the objects still linked. Art dragged off the canvas, or the Appearance panel's thumbnail, dropped on a style in the Graphic Styles panel with Alt held runs `graphicStyle.redefine` with that style's `name` and the object's -`id` (the first object of the art); an object already linked to the style with its look changes nothing. The art of a -column or marker design in a graph series is never linked: +`id` (the first object of the art); an object already linked to the style with its look changes nothing. +`graphicStyle.redefine {name, from}` gives the style `name` the look of the style `from` instead (fills, strokes, +effects, opacity, blend mode, isolate and knockout): `name` keeps its name, place and id, its objects still linked +follow in one undo step, and `from` and its objects stay as they are. `from` naming the same style, or a style with +the same look, records nothing; a `from` that names no style or is not a string, or `from` with `id`, is an error. A +style dragged onto another in the Graphic Styles panel with Alt held runs it with the dragged style as `from`; +without Alt the style moves (`graphicStyle.move`). The art of a column or marker design in a graph series is never +linked: `graphicStyle.new` can make a style from it, and `graphicStyle.redefine` leaves its look as it was and unlinks it, whether it is the source or a linked object. `graphicStyle.list` returns each style with the ids linked to it and the style of the first selected object; `select.same.graphicStyle` selects an object's fellow users. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2193a988ed..54b645d021 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1845,6 +1845,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A graphic style dragged onto the Graphic Styles panel's New Graphic Style button is duplicated, as the panel menu's Duplicate Graphic Style does, and both put the copy at the end of the list, as the help page describes ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=391)). VectorCraft's own rules: the button takes the drop with no art selected; a dragged style that is highlighted brings the other highlighted styles, copied in panel order in one undo step, and the copies are highlighted; the copy is named ` copy`, with a number when that is taken, and no art is linked to it (`a_style_dropped_on_new_graphic_style_is_duplicated_at_the_end` in `crates/ui-egui/src/panels/graphic_styles.rs`, `tests::styles::duplicate_puts_the_copy_at_the_end_of_the_list_in_one_undo_step`). A graphic style dragged onto the Graphic Styles panel's Delete Graphic Style button is deleted, which the help page gives as another way to delete a style besides the panel menu's Delete Graphic Style; art that used the style keeps its look and is no longer linked to it ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=392)). VectorCraft's own rules: the drop asks first as the button does, and with Alt held it deletes without asking; the button takes the drop with no style highlighted; a dragged style that is highlighted brings the other highlighted styles, deleted in one undo step (`a_style_dropped_on_delete_graphic_style_is_deleted_as_the_button_deletes` in `crates/ui-egui/src/panels/graphic_styles.rs`). The Appearance panel's thumbnail dropped on a graphic style with Alt held replaces that style with the look of the object the panel shows; the style keeps its name and the art that uses it takes the new look, as the help page describes ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=568)). VectorCraft's own rules: art dragged off the canvas does the same with its first object; the style keeps its place in the list, is outlined while one is held over it with Alt, and the replacement is one undo step; an object already linked to the style with its look changes nothing; without Alt the drop makes a new style (`art_or_an_appearance_dropped_on_a_style_with_alt_replaces_that_style` in `crates/ui-egui/src/panels/graphic_styles.rs`). + A graphic style dragged onto another style in the Graphic Styles panel with Alt held gives that style the dragged style's look; the replaced style keeps its name and the art that uses it takes the new look, as the help page describes ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=568)). VectorCraft's own rules: the dragged style and the art linked to it stay as they are; the replaced style keeps its place in the list and is outlined while a style is held over it with Alt; the replacement is one undo step; a style dropped on itself, or on a style with the same look, changes nothing and records no undo step; without Alt the style moves (`graphicStyle.redefine {name, from}`, `a_style_dropped_on_another_with_alt_replaces_that_style` in `crates/ui-egui/src/panels/graphic_styles.rs`, `tests::styles::redefine_from_a_style_gives_the_style_that_look`). In the Graphic Styles panel's thumbnail and list views, a style with no fill and no stroke, one with only effects or transparency included, shows its preview shape with a black outline, a white fill and a red slash, as the help page describes for the panel's thumbnails ([Graphic styles](https://helpx.adobe.com/illustrator/using/graphic-styles.html)); its effects still draw on that shape. The Control bar's Style picker and chip, graphic style library panels and the large preview on the selected object show the same marker. A fill or stroke row that paints None does not count as a fill or stroke, and a hidden row or one with zero opacity does; these rules, the marker outside the panel's thumbnails and the slash's direction and size are VectorCraft's own (`a_style_with_no_fill_and_no_stroke_shows_an_outlined_shape_and_a_red_slash` in `crates/ui-egui/src/panels/graphic_styles.rs`). Applying a style to several objects, and Redefine Graphic Style, give the objects one shared copy of the style's appearance instead of a copy each; an object that is edited later gets its own copy, and an object whose placed gradients are fitted to its own bounds gets its own. The undo history's memory estimate counts a shared appearance once. Saved files are unchanged (`crates/engine/src/tests/styles.rs`). - **Several text styles at once:** in the Character Styles and Paragraph Styles panels, Shift-click highlights a range of styles and Ctrl/Cmd-click adds or removes one, without applying them; the panel menu's Select All Unused (`charStyle.unused`, `paraStyle.unused`) highlights the styles no type uses (in the layers, opacity masks, symbols, graph designs, pattern tiles and the art of brushes), never the Normal style; Delete, the button or the menu item, deletes every highlighted style but Normal in one undo step (`charStyle.delete {names}`, `paraStyle.delete {names}`). The menu's Duplicate copies every highlighted style in one undo step and highlights the copies. A highlighted row dragged onto Create New Style or Delete carries every highlighted style: dropped on Create New Style it copies them all and highlights the copies, and dropped on Delete it deletes them all but Normal and clears the highlight; a row from outside the highlight carries only its own style. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). From 0ab5451f78d024360f6183046aaf464fcaef97cf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 12:34:44 -0800 Subject: [PATCH 09/33] .ai save: gradient and pattern definitions are found by name and by gradient Each gradient fill or stroke, and each gradient swatch, looked for its definition by comparing its gradient with every definition written so far, and each new definition's name was checked against every other name. A document with thousands of distinct gradients spent most of the editing data's time in these comparisons. The writer now keeps the definitions' names in a map and the definitions no swatch names under a key made from every field of their gradient (a zero of either sign giving the same key). Each candidate under a key is still compared in full, the first in definition order is used, and a style that isn't written frees the names and keys of the definitions it added. Pattern definitions are found by name the same way. The written program is unchanged, byte for byte. --- crates/eps/src/ai_editing/tests.rs | 136 +++++++++++ crates/eps/src/ai_editing/writer.rs | 11 +- crates/eps/src/ai_editing/writer/paints.rs | 250 +++++++++++++++++++-- 3 files changed, 376 insertions(+), 21 deletions(-) diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 47c4b57f39..dd24dbf9fc 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -3191,6 +3191,142 @@ fn many_gradient_definitions_take_distinct_names_in_order() { assert_eq!(text, program(&doc)); } +/// The program written from `doc`, with the gradient and pattern definitions found by comparing +/// each in turn (`scanned`) or through their indexes. +fn program_scanned(doc: &Document, scanned: bool) -> Vec { + writer::SCANNED_DEFINITIONS.with(|s| s.set(scanned)); + let out = export_ai_editing(doc, &opts()); + writer::SCANNED_DEFINITIONS.with(|s| s.set(false)); + out.unwrap().program +} + +/// [`gradients_and_patterns`] with more rectangles, each filled with a gradient: `distinct` with +/// gradients of their own; `reused` with one of `ramps` gradients in turn; one for each of +/// `swatches` new gradient swatches, linked to it, with the swatch's gradient for every other one +/// and another gradient for the rest; one with the gradient of an object whose style isn't written +/// (an even-odd fill with a drop shadow), after that object; and two whose gradients +/// differ only in the sign of a zero offset. +fn many_gradients(distinct: u16, reused: u16, ramps: u16, swatches: u16) -> Document { + let mut doc = gradients_and_patterns(); + let two = |a: Color, b: Color| ramp(GradientKind::Linear, &[(0.0, a, 1.0, 0.5), (1.0, b, 1.0, 0.5)]); + let shade = |i: u16, n: u16| f32::from(i) / f32::from(n.max(1)); + let swatch_gradient = |i: u16| two(Color::gray(shade(i, swatches)), Color::rgb(1.0, 0.0, 0.0)); + let more = (0..swatches) + .map(|i| Swatch { name: format!("Ramp {i}"), paint: gradient_paint(swatch_gradient(i), None, None), global: false, spot: false }) + .collect(); + swatches_plus(&mut doc, more); + let mut paints = vec![]; + for i in 0..distinct { + paints.push(gradient_paint(two(Color::rgb(shade(i, distinct), 0.5, 0.0), Color::rgb(0.0, 0.0, 1.0)), None, None)); + } + for i in 0..reused { + paints.push(gradient_paint(two(Color::rgb(0.0, shade(i % ramps.max(1), ramps), 0.5), Color::WHITE), None, None)); + } + for i in 0..swatches { + let g = if i % 2 == 0 { swatch_gradient(i) } else { two(Color::gray(shade(i, swatches)), Color::rgb(0.0, 1.0, 0.0)) }; + paints.push(gradient_paint(g, None, Some(&format!("Ramp {i}")))); + } + // The reader wouldn't read an even-odd fill with the style, so the style isn't written. + let unstyled = two(Color::WHITE, Color::BLACK); + let ap = Appearance { + items: vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(unstyled.clone(), None, None)))], + effects: vec![fx("stylize.dropShadow", serde_json::json!({}))], + contents_index: None, + }; + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap); + if let NodeKind::Path { rule, .. } = &mut n.kind { + *rule = FillRule::EvenOdd; + } + put(&mut doc, n); + paints.push(gradient_paint(unstyled, None, None)); + let zero = |o: f32| ramp(GradientKind::Linear, &[(o, Color::rgb(0.2, 0.3, 0.4), 1.0, 0.5), (1.0, Color::BLACK, 1.0, 0.5)]); + paints.extend([gradient_paint(zero(0.0), None, None), gradient_paint(zero(-0.0), None, None)]); + for (i, p) in (0u16..).zip(paints) { + let (x, y) = (f64::from(i % 60) * 5.0, f64::from(i / 60 % 40) * 5.0); + let n = painted(&mut doc, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), vec![AppearanceItem::Fill(FillLayer::new(p))]); + put(&mut doc, n); + } + doc +} + +/// Gradient and pattern definitions found through their indexes are those found by comparing each +/// in turn: the program is the same, byte for byte. A swatch's definition serves a paint linked to +/// it only with the swatch's gradient; a gradient defined for a style that isn't written leaves its +/// name free; gradients that differ only in the sign of a zero share a definition. +#[test] +fn indexed_definitions_write_the_same_program() { + let doc = many_gradients(300, 300, 7, 6); + let (indexed, scanned) = (program_scanned(&doc, false), program_scanned(&doc, true)); + let differ = indexed.iter().zip(&scanned).position(|(a, b)| a != b); + assert!(indexed == scanned, "the programs differ from byte {differ:?} ({} and {} bytes)", indexed.len(), scanned.len()); + let text = String::from_utf8(indexed).unwrap(); + let names: Vec<&str> = text.lines().filter_map(|l| l.strip_prefix("%AI5_BeginGradient: ")).collect(); + // `gradients_and_patterns`'s 5, then 300 + 7 + 6 swatches' + 3 others linked to swatches + 1 + // after the style + 1 for both signs of zero. + assert_eq!(names.len(), 5 + 300 + 7 + 6 + 3 + 1 + 1, "{names:?}"); + assert_eq!(names.iter().collect::>().len(), names.len(), "{names:?}"); + assert_eq!(text.matches("%AI3_BeginPattern: (Dots)").count(), 1); +} + +/// A gradient paint is matched with the definitions of the same gradient, not with each +/// definition: 1,000 gradients of their own and 1,000 paints of 10 others take a few comparisons +/// each, where comparing each definition in turn takes hundreds of thousands. +#[test] +fn gradient_definitions_are_found_without_comparing_each() { + let doc = many_gradients(1000, 1000, 10, 0); + let comparisons = |scanned: bool| { + writer::GRADIENT_COMPARISONS.with(|c| c.set(0)); + program_scanned(&doc, scanned); + writer::GRADIENT_COMPARISONS.with(std::cell::Cell::get) + }; + let (indexed, scanned) = (comparisons(false), comparisons(true)); + assert!(indexed <= 2 * 2010, "{indexed} comparisons through the index"); + assert!(scanned > 100 * indexed, "{scanned} comparisons scanning, {indexed} through the index"); +} + +/// The time this thread has run, and how it was measured. +fn thread_time() -> (std::time::Duration, &'static str) { + if let Some(ns) = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse::().ok()) { + return (std::time::Duration::from_nanos(ns), "thread CPU time"); + } + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + (START.get_or_init(std::time::Instant::now).elapsed(), "wall-clock time") +} + +/// The time to write 5,000 rectangles with gradients of their own, 5,000 with 50 others and 20 +/// gradient swatches, with the definitions found by comparing each in turn and through their +/// indexes: the median of 7 runs of each, alternating, with the programs compared. Run with +/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture gradient_definitions_timing`. +#[test] +#[ignore = "timing"] +fn gradient_definitions_timing() { + let doc = many_gradients(5000, 5000, 50, 20); + let mut times = [vec![], vec![]]; + let mut programs: [Option>; 2] = [None, None]; + let mut how = ""; + for _ in 0..7 { + for (k, scanned) in [true, false].into_iter().enumerate() { + let (start, h) = thread_time(); + let program = program_scanned(&doc, scanned); + times[k].push(thread_time().0.saturating_sub(start)); + how = h; + programs[k].get_or_insert(program); + } + } + assert_eq!(programs[0], programs[1]); + for t in &mut times { + t.sort(); + } + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + println!("median of 7 runs ({how}):"); + println!("| definitions found | median (ms) | runs (ms) |"); + println!("|---|---:|---|"); + for (k, label) in ["by comparing each", "through the indexes"].into_iter().enumerate() { + let runs: Vec = times[k].iter().map(|d| format!("{:.1}", ms(*d))).collect(); + println!("| {label} | {:.1} | {} |", ms(times[k][3]), runs.join(", ")); + } +} + /// A hard edge: a linear gradient whose stops all lie at one place is written from its last stop, /// and reads back with each stop on its side. #[test] diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index cc44503373..dfb1cd75aa 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -45,7 +45,8 @@ pub(super) use images::PAYLOAD; pub(super) use images::{IMAGE_DEPTH, IMAGES, LINKS_EMBEDDED}; #[cfg(test)] pub(super) use paints::{ - GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name, + GRADIENT_COMPARISONS, GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, SCANNED_DEFINITIONS, STOP_LINKS, + SWATCH_PLACEMENT, free_gradient_name, }; #[cfg(test)] pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS}; @@ -200,11 +201,11 @@ pub(super) struct Writer<'a> { /// pattern's definition, the pattern's space turned y up. canvas: Affine, /// The gradient definitions, in the order they are first used. - gradients: Vec, + gradients: paints::GradientDefs, /// The number the next new gradient definition's name tries first (1 is `Gradient`). next_gradient: u64, /// The pattern definitions written, each after those its art uses. - patterns: Vec, + patterns: paints::PatternDefs, /// The patterns whose definitions are being written. defining: Vec, /// Writing the palette: the definitions it adds are for its swatches only. @@ -357,9 +358,9 @@ impl<'a> Writer<'a> { grad_space: to_art, tile_grad_space: Affine::translate((-origin.0, origin.1)), canvas: Affine::new([1.0, 0.0, 0.0, -1.0, origin.0, origin.1]) * to_art, - gradients: vec![], + gradients: paints::GradientDefs::default(), next_gradient: 1, - patterns: vec![], + patterns: paints::PatternDefs::default(), defining: vec![], in_palette: false, canvas_origin: origin, diff --git a/crates/eps/src/ai_editing/writer/paints.rs b/crates/eps/src/ai_editing/writer/paints.rs index d9dc31a717..075f761a7e 100644 --- a/crates/eps/src/ai_editing/writer/paints.rs +++ b/crates/eps/src/ai_editing/writer/paints.rs @@ -1,7 +1,9 @@ //! Gradients and patterns: their definitions in the setup, gradient instances on paths and the //! pattern operators (see [`crate::ai_editing`] for the form). +use std::collections::HashMap; use std::fmt::Write; +use std::hash::{Hash, Hasher}; use vectorcraft_color::gradient::GradientGeom; use vectorcraft_color::swatch::REGISTRATION; @@ -46,6 +48,134 @@ pub(super) struct PatternOut { used: bool, } +#[cfg(test)] +thread_local! { + /// Whether [`GradientDefs`] and [`PatternDefs`] find definitions on this thread by comparing + /// the gradient or name with each definition in turn. + pub(in crate::ai_editing) static SCANNED_DEFINITIONS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// How many times [`GradientDefs::find`] has compared two gradients on this thread. + pub(in crate::ai_editing) static GRADIENT_COMPARISONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Are gradients `a` and `b` the same? +fn same_gradient(a: &Gradient, b: &Gradient) -> bool { + #[cfg(test)] + GRADIENT_COMPARISONS.with(|c| c.set(c.get() + 1)); + a == b +} + +/// A key of `g` for [`GradientDefs`]: the same gradients have the same key (each number by its +/// bits, with -0 as 0); different gradients may share one. +fn gradient_key(g: &Gradient) -> u64 { + let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() }; + let mut h = std::hash::DefaultHasher::new(); + std::mem::discriminant(&g.kind).hash(&mut h); + std::mem::discriminant(&g.method).hash(&mut h); + (g.dither, g.spread, g.repeats, g.stops.len()).hash(&mut h); + for s in &g.stops { + let (model, c) = match s.color { + Color::Rgb { r, g, b } => (0u8, [r, g, b, 0.0]), + Color::Cmyk { c, m, y, k } => (1, [c, m, y, k]), + Color::Gray { k } => (2, [k, 0.0, 0.0, 0.0]), + Color::Lab { l, a, b } => (3, [l, a, b, 0.0]), + }; + (model, c.map(bits), [s.offset, s.opacity, s.midpoint, s.tint].map(bits)).hash(&mut h); + (&s.swatch, s.plates.map(|p| p.map(bits))).hash(&mut h); + } + h.finish() +} + +/// The gradient definitions, in the order they are first used, found by name and by gradient +/// without comparing each one. +#[derive(Default)] +pub(super) struct GradientDefs { + list: Vec, + /// Each definition's place in `list`, by its name (no two definitions share one). + names: HashMap, + /// The places in `list` of the definitions no swatch names, in order, by their gradient's key + /// ([`gradient_key`]). + ramps: HashMap>, +} + +impl GradientDefs { + /// Is `name` a definition's name? + fn has_name(&self, name: &str) -> bool { + #[cfg(test)] + if SCANNED_DEFINITIONS.with(std::cell::Cell::get) { + return self.list.iter().any(|d| d.name == name); + } + self.names.contains_key(name) + } + + /// The place of the definition of `g`: the swatch `swatch` names when it is a gradient swatch + /// of the same gradient, else the first definition of the same gradient that no swatch names. + fn find(&self, g: &Gradient, swatch: Option<&str>) -> Option { + #[cfg(test)] + if SCANNED_DEFINITIONS.with(std::cell::Cell::get) { + return swatch + .and_then(|s| self.list.iter().position(|d| d.swatch && d.name == s && same_gradient(&d.gradient, g))) + .or_else(|| self.list.iter().position(|d| !d.swatch && same_gradient(&d.gradient, g))); + } + let held = |i: &usize, swatch: bool| self.list.get(*i).is_some_and(|d| d.swatch == swatch && same_gradient(&d.gradient, g)); + swatch + .and_then(|s| self.names.get(s).copied().filter(|i| held(i, true))) + .or_else(|| self.ramps.get(&gradient_key(g))?.iter().copied().find(|i| held(i, false))) + } + + /// Add `d`, whose name no definition has. + fn push(&mut self, d: GradientDef) { + let i = self.list.len(); + if !d.swatch { + self.ramps.entry(gradient_key(&d.gradient)).or_default().push(i); + } + self.names.insert(d.name.clone(), i); + self.list.push(d); + } + + /// Keep the first `len` definitions; the names of those removed are free again. + fn truncate(&mut self, len: usize) { + while self.list.len() > len { + let Some(d) = self.list.pop() else { break }; + self.names.remove(&d.name); + if !d.swatch { + // Places are added in order, so the removed definition's is the last of its key's. + let key = gradient_key(&d.gradient); + if let Some(places) = self.ramps.get_mut(&key) { + places.pop(); + if places.is_empty() { + self.ramps.remove(&key); + } + } + } + } + } +} + +/// The pattern definitions written, each after those its art uses, found by name. +#[derive(Default)] +pub(super) struct PatternDefs { + list: Vec, + /// Each definition's place in `list`, by its name (no two definitions share one). + names: HashMap, +} + +impl PatternDefs { + /// The place of pattern `name`'s definition. + fn find(&self, name: &str) -> Option { + #[cfg(test)] + if SCANNED_DEFINITIONS.with(std::cell::Cell::get) { + return self.list.iter().position(|p| p.name == name); + } + self.names.get(name).copied() + } + + /// Add `p`, whose name no definition has. + fn push(&mut self, p: PatternOut) { + self.names.insert(p.name.clone(), self.list.len()); + self.list.push(p); + } +} + pub(in crate::ai_editing) const DIAMOND: &str = "diamond gradients are written as radial gradients through their corners, with the same stops, in the editing data for other apps"; pub(in crate::ai_editing) const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (at most 256 stops, padding past them) in the editing data for other apps"; @@ -118,7 +248,7 @@ impl Writer<'_> { && let stops = curve_as_stops(&g.gradient) && let gradient = stops.unrolled_within(crate::import::MAX_GRADIENT_STOPS) && writable_gradient(&gradient) - && !self.gradients.iter().any(|d| d.name == sw.name) + && !self.gradients.has_name(&sw.name) { self.gradients.push(GradientDef { name: sw.name.clone(), gradient: gradient.into_owned(), swatch: true, used: false }); } @@ -131,17 +261,14 @@ impl Writer<'_> { /// swatch or a pattern). fn define_gradient(&mut self, g: &Gradient, swatch: Option<&str>) -> String { let used = !self.in_palette; - let found = swatch - .and_then(|s| self.gradients.iter().position(|d| d.swatch && d.name == s && d.gradient == *g)) - .or_else(|| self.gradients.iter().position(|d| !d.swatch && d.gradient == *g)); - if let Some(d) = found.and_then(|i| self.gradients.get_mut(i)) { + let found = self.gradients.find(g, swatch); + if let Some(d) = found.and_then(|i| self.gradients.list.get_mut(i)) { d.used |= used; return d.name.clone(); } let (doc, gradients) = (self.doc, &self.gradients); - let name = free_gradient_name(&mut self.next_gradient, |name| { - gradients.iter().any(|d| d.name == name) || doc.swatch(name).is_some() || doc.pattern(name).is_some() - }); + let name = + free_gradient_name(&mut self.next_gradient, |name| gradients.has_name(name) || doc.swatch(name).is_some() || doc.pattern(name).is_some()); self.gradients.push(GradientDef { name: name.clone(), gradient: g.clone(), swatch: false, used }); name } @@ -149,14 +276,14 @@ impl Writer<'_> { /// The gradient definitions' state, for [`Self::gradient_rollback`]: their count, which ones the /// art uses, and the next name's number. pub(super) fn gradient_mark(&self) -> (usize, Vec, u64) { - (self.gradients.len(), self.gradients.iter().map(|d| d.used).collect(), self.next_gradient) + (self.gradients.list.len(), self.gradients.list.iter().map(|d| d.used).collect(), self.next_gradient) } /// The gradient definitions as they were at `mark` ([`Self::gradient_mark`]). pub(super) fn gradient_rollback(&mut self, mark: (usize, Vec, u64)) { let (len, used, next) = mark; self.gradients.truncate(len); - for (d, u) in self.gradients.iter_mut().zip(used) { + for (d, u) in self.gradients.list.iter_mut().zip(used) { d.used = u; } self.next_gradient = next; @@ -476,7 +603,7 @@ impl Writer<'_> { if !self.defining.is_empty() || self.nest >= MAX_NEST || self.in_symbol { return false; } - if self.patterns.iter().any(|p| p.name == name) { + if self.patterns.find(name).is_some() { return true; } self.doc.pattern(name).is_some_and(tile_holds_art) @@ -492,7 +619,7 @@ impl Writer<'_> { return false; } let used = !self.in_palette; - if let Some(p) = self.patterns.iter_mut().find(|p| p.name == name) { + if let Some(p) = self.patterns.find(name).and_then(|i| self.patterns.list.get_mut(i)) { p.used |= used; return true; } @@ -582,7 +709,7 @@ impl Writer<'_> { /// uses). pub(in crate::ai_editing) fn definitions(&mut self, s: &mut String) { let defs = std::mem::take(&mut self.gradients); - let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.iter().partition(|d| d.used); + let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.list.iter().partition(|d| d.used); let _ = writeln!(s, "{} Bn", used.len()); for d in &used { self.gradient_def(s, d); @@ -595,12 +722,12 @@ impl Writer<'_> { s.push_str("%AI5_End_NonPrinting--\n"); } self.gradients = defs; - for p in self.patterns.iter().filter(|p| p.used) { + for p in self.patterns.list.iter().filter(|p| p.used) { s.push_str(&p.text); } - if self.patterns.iter().any(|p| !p.used) { + if self.patterns.list.iter().any(|p| !p.used) { s.push_str("%AI5_Begin_NonPrinting\nNp\n"); - for p in self.patterns.iter().filter(|p| !p.used) { + for p in self.patterns.list.iter().filter(|p| !p.used) { s.push_str(&p.text); } s.push_str("%AI5_End_NonPrinting--\n"); @@ -729,3 +856,94 @@ fn tile_holds_art(def: &PatternDef) -> bool { b.x0 >= room.x0 && b.y0 >= room.y0 && b.x1 <= room.x1 && b.y1 <= room.y1 }) } + +#[cfg(test)] +mod tests { + use super::*; + + fn two(a: f32, b: Color) -> Gradient { + Gradient::new(GradientKind::Linear, vec![GradientStop::new(a, Color::rgb(0.2, 0.4, 0.6)), GradientStop::new(1.0, b)]) + } + + fn def(name: &str, gradient: Gradient, swatch: bool) -> GradientDef { + GradientDef { name: name.into(), gradient, swatch, used: true } + } + + /// The same gradients have the same key, a zero of either sign included. + #[test] + fn a_zero_of_either_sign_gives_the_same_key() { + assert_eq!(gradient_key(&two(0.0, Color::BLACK)), gradient_key(&two(-0.0, Color::BLACK))); + assert_eq!(two(0.0, Color::BLACK), two(-0.0, Color::BLACK)); + assert_ne!(gradient_key(&two(0.0, Color::BLACK)), gradient_key(&two(0.0, Color::WHITE))); + } + + /// Definitions whose gradients share a key are told apart by their gradients, the first of the + /// same gradient found; a gradient that isn't equal to itself is found in none. + #[test] + fn definitions_that_share_a_key_are_told_apart() { + let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE)); + let mut defs = GradientDefs::default(); + defs.push(def("Gradient", white.clone(), false)); + defs.push(def("Gradient 2", black.clone(), false)); + defs.push(def("Gradient 3", black.clone(), false)); + // Every definition under the black gradient's key, as if the keys of both were the same. + defs.ramps = HashMap::from([(gradient_key(&black), vec![0, 1, 2])]); + assert_eq!(defs.find(&black, None), Some(1)); + assert_eq!(defs.find(&white, None), None); + defs.ramps.insert(gradient_key(&white), vec![0, 1, 2]); + assert_eq!(defs.find(&white, None), Some(0)); + let nan = two(f32::NAN, Color::BLACK); + defs.push(def("Gradient 4", nan.clone(), false)); + assert_eq!(defs.find(&nan, None), None); + } + + /// A swatch's definition is found by the swatch's name and gradient; a definition that no + /// swatch names, for the same gradient without the name or with another. + #[test] + fn a_swatch_definition_is_found_by_its_name_and_gradient() { + let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE)); + let mut defs = GradientDefs::default(); + defs.push(def("Ramp", black.clone(), true)); + assert_eq!(defs.find(&black, Some("Ramp")), Some(0)); + assert_eq!(defs.find(&black, None), None); + assert_eq!(defs.find(&white, Some("Ramp")), None); + defs.push(def("Gradient", black.clone(), false)); + defs.push(def("Gradient 2", white.clone(), false)); + assert_eq!(defs.find(&black, Some("Ramp")), Some(0)); + assert_eq!(defs.find(&black, None), Some(1)); + assert_eq!(defs.find(&white, Some("Ramp")), Some(2)); + assert_eq!(defs.find(&black, Some("Other")), Some(1)); + } + + /// Definitions removed leave their names free and are no longer found; those kept still are. + #[test] + fn removed_definitions_free_their_names() { + let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE)); + let mut defs = GradientDefs::default(); + defs.push(def("Ramp", white.clone(), true)); + defs.push(def("Gradient", black.clone(), false)); + defs.push(def("Gradient 2", white.clone(), false)); + defs.push(def("Gradient 3", black.clone(), false)); + defs.truncate(2); + assert!(defs.has_name("Ramp") && defs.has_name("Gradient")); + assert!(!defs.has_name("Gradient 2") && !defs.has_name("Gradient 3")); + assert_eq!(defs.find(&black, None), Some(1)); + assert_eq!(defs.find(&white, None), None); + assert_eq!(defs.ramps.values().map(Vec::len).sum::(), 1); + defs.push(def("Gradient 2", white.clone(), false)); + assert_eq!(defs.find(&white, None), Some(2)); + defs.truncate(0); + assert!(defs.list.is_empty() && defs.names.is_empty() && defs.ramps.is_empty()); + } + + /// A pattern's definition is found by its name. + #[test] + fn pattern_definitions_are_found_by_name() { + let mut defs = PatternDefs::default(); + assert_eq!(defs.find("Dots"), None); + for name in ["Dots", "Checks"] { + defs.push(PatternOut { name: name.into(), text: String::new(), used: false }); + } + assert_eq!((defs.find("Dots"), defs.find("Checks"), defs.find("Stripes")), (Some(0), Some(1), None)); + } +} From cc4ce97fc31891d6ef7f3df3e2109dff3b481487 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 12:48:20 -0800 Subject: [PATCH 10/33] Symbols: Shift with New Symbol keeps the art as ordinary art Making a new symbol from the selected art with Shift held now adds the symbol and leaves the art as ordinary art, as the Create a symbol section of the help page describes (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=192). Without Shift the art still becomes an instance. - symbol.new takes keepArt (default false). With true the art keeps its ids, layer and stacking position and stays selected, apart from art that cannot be selected, frames of threaded text stay in their thread, and the result's id is null. A keepArt that is not true or false is an error. - The Symbols panel's New Symbol button and its New Symbol... menu item read Shift when clicked and carry it through Symbol Options' OK; Shift with Alt on the button makes the symbol at once and keeps the art. Art dragged onto the panel reads Shift as it is released. - ui.symbolOptions takes keepArt for a new symbol and refuses it when editing a symbol. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/symbols.rs | 14 +- crates/engine/src/cmd/threads/tests.rs | 25 ++++ crates/engine/src/tests/brushsym.rs | 87 +++++++++++ crates/ui-egui/src/dialogs/symbol_options.rs | 22 ++- crates/ui-egui/src/menus/run.rs | 9 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/symbols.rs | 144 +++++++++++++++++-- docs/mcp.md | 10 +- docs/target-app-parity.md | 1 + 10 files changed, 293 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index b68d7e0600..86577512f0 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -202,7 +202,7 @@ pub fn specs() -> Vec { "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, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} 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 of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}", + "{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), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid), keepArt?: false} make a symbol from the selection and replace it with an instance, or with keepArt: true leave the selection as ordinary art where it is, still selected, with id null; a frame of threaded text in the selection that becomes an instance 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 of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}", has_selection, symbol_new ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 98e3ce714b..f5245bc9af 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -253,6 +253,9 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { let nine = nine_slice_param(p, C, None)?.flatten(); let dynamic = type_param(p, C)?.unwrap_or(false); let pixel = pixel_grid_param(p, C)?.unwrap_or(false); + // `keepArt` leaves the art as ordinary art instead of replacing it with an instance. + let keep_art = switch_or(p, "keepArt", false, C)?; + let iso = s.doc()?.isolation; // 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| { @@ -264,13 +267,20 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { d.set_symbol_export_type(&name, export); d.set_symbol_nine_slice(&name, nine); d.set_symbol_pixel_aligned(&name, pixel); + if keep_art { + // The art stays where it is and stays selected, apart from art that is hidden or + // locked, in a hidden or locked group or layer, or on a locked artboard. + let locks = d.locked_artboards(); + sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i))); + return Ok(None); + } let id = instance_in_place(d, &ids, &name, place)?; sel.set([id]); - Ok(id) + Ok(Some(id)) })?; Ok(json!({ "name": name, - "id": id.0, + "id": id.map(|i| i.0), "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value), diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index 82ac2f9f76..7e0d790568 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -1991,6 +1991,31 @@ fn frames_made_into_a_symbol_leave_their_thread_with_their_text() { } } +/// New Symbol and Redefine Symbol with `keepArt: true` on a frame of threaded text leave the +/// thread as it was: every frame stays a frame of the thread with the text it holds, and the +/// symbol's art holds a copy of the text the frame shows. +#[test] +fn frames_kept_as_art_by_a_new_or_redefined_symbol_stay_in_their_thread() { + for command in ["symbol.new", "symbol.update"] { + let (mut s, frames) = three_frames(&TEXT.repeat(4), 200.0); + let shown = frames.map(|id| text(&s, id)); + let name = if command == "symbol.update" { + let mark = new_id(s.execute("shape.rectangle", &json!({"x": 400, "y": 200, "width": 20, "height": 20})).unwrap()); + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("symbol.new", &json!({"name": "Mark"})).unwrap(); + "Mark" + } else { + "Story" + }; + s.execute("select.set", &json!({"ids": [frames[1]]})).unwrap(); + let r = s.execute(command, &json!({"name": name, "keepArt": true})).unwrap(); + assert!(r["id"].is_null(), "{command}: {r}"); + assert_eq!(threads(&s), [frames], "{command}: the thread is as it was"); + assert_eq!(frames.map(|id| text(&s, id)), shown, "{command}: each frame keeps its text"); + assert_eq!(symbol_texts(&s, name), [shown[1].clone()], "{command}: the symbol's art holds the text the frame shows"); + } +} + /// A frame of a numbered thread pasted while an opacity mask is edited numbers from 1 in the /// mask art too. #[test] diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index c45bcfdb00..ef443ae285 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1931,6 +1931,93 @@ fn redefine_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch() } } +/// The number of symbol instances in the document. +fn instance_count(s: &Session) -> usize { + let mut n = 0; + s.doc().unwrap().doc.walk(|c| n += usize::from(matches!(c.kind, NodeKind::SymbolInstance { .. }))); + n +} + +/// New Symbol with `keepArt: true` makes a symbol of the selection and makes it the current +/// symbol, and the selected art stays ordinary art in its place, with its ids, still selected; the +/// result has no instance id and nothing places the symbol. One undo step takes the symbol away +/// and redo makes it again. Without `keepArt`, or with false, the art becomes an instance. +#[test] +fn new_symbol_with_keep_art_leaves_the_art_as_ordinary_art() { + let mut s = session(); + let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0); + let b = rect(&mut s, 100.0, 200.0, 40.0, 50.0); + let spot = |s: &Session, id: NodeId| s.doc().unwrap().doc.position(id).map(|(p, i, _)| (p, i)); + let before = (node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)); + let steps = s.doc().unwrap().history.undo.len(); + select(&mut s, &[a, b]); + let r = s.execute("symbol.new", &json!({"name": "Kept", "keepArt": true})).unwrap(); + assert_eq!((&r["name"], &r["id"]), (&json!("Kept"), &Value::Null), "{r}"); + assert_eq!((node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)), before, "the art is unchanged and in its place"); + assert_eq!(s.doc().unwrap().selection.objects, vec![a, b], "the art stays selected"); + assert_eq!(instance_count(&s), 0, "no instance"); + let list = s.execute("symbol.list", &json!({})).unwrap(); + assert_eq!((&list["current"], &list["symbols"][0]["name"], &list["symbols"][0]["instances"]), (&json!("Kept"), &json!("Kept"), &json!(0))); + // The symbol's art is the pair: an instance placed from it is 120 × 50. + let placed = NodeId(s.execute("symbol.place", &json!({"name": "Kept"})).unwrap()["id"].as_u64().unwrap()); + let w = bounds(&s, placed); + assert!((w.width() - 120.0).abs() < 1e-6 && (w.height() - 50.0).abs() < 1e-6, "{w:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "New Symbol is one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.symbols.is_empty(), "undo takes the symbol away"); + assert_eq!((node(&s, a), node(&s, b)), (before.0.clone(), before.1.clone()), "and leaves the art"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.execute("symbol.list", &json!({})).unwrap()["current"], json!("Kept"), "redo"); + assert_eq!(instance_count(&s), 0, "redo places no instance"); + // false, like no keepArt, makes the art an instance. + for p in [json!({"name": "Plain", "ids": [a.0], "keepArt": false}), json!({"name": "Plain", "ids": [b.0]})] { + let r = s.execute("symbol.new", &p).unwrap(); + let id = NodeId(r["id"].as_u64().expect("an instance id")); + assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "{p}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![id], "{p}"); + } + assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_none()); +} + +/// New Symbol with `keepArt: true` and explicit ids keeps the named art selected only where it +/// can be selected: locked or hidden art is left out. A symbol instance in the art stays the +/// instance it was. A `keepArt` that is not true or false is refused, with no symbol, no change and +/// no undo step. +#[test] +fn new_symbol_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch() { + let mut s = session(); + let (inst, _, _) = make_symbol(&mut s); + let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0); + let locked = rect(&mut s, 100.0, 200.0, 40.0, 50.0); + let hidden = rect(&mut s, 200.0, 200.0, 40.0, 50.0); + { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.node_mut(locked).unwrap().locked = true; + doc.node_mut(hidden).unwrap().visible = false; + } + for bad in [json!("true"), json!(1), json!([true])] { + let before = s.doc().unwrap().doc.clone(); + let steps = s.doc().unwrap().history.undo.len(); + let e = s.execute("symbol.new", &json!({"name": "Bad", "ids": [a.0], "keepArt": bad})).unwrap_err(); + assert!(e.to_string().contains("`keepArt` must be true or false"), "{bad}: {e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{bad}: the document is unchanged"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{bad}: no undo step"); + } + select(&mut s, &[]); + let symbols = s.doc().unwrap().doc.symbols.len(); + let ids = [a.0, locked.0, hidden.0, inst.0]; + s.execute("symbol.new", &json!({"name": "Kept", "ids": ids, "keepArt": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.symbols.len(), symbols + 1); + let selected = &s.doc().unwrap().selection.objects; + assert!(selected.len() == 2 && selected.contains(&a) && selected.contains(&inst), "only the selectable art is selected: {selected:?}"); + for id in [a, locked, hidden] { + assert!(matches!(node(&s, id).kind, NodeKind::Path { .. }), "{id:?} stays ordinary art"); + } + assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }), "the instance stays an instance"); + assert_eq!(instance_count(&s), 1, "no new instance"); +} + /// Redefine Symbol refuses art that holds an instance of the symbol it redefines, directly, in a /// group, in an opacity mask, or through the art of another symbol it holds an instance of, and /// then changes nothing and adds no undo step. An instance of an unrelated symbol still redefines diff --git a/crates/ui-egui/src/dialogs/symbol_options.rs b/crates/ui-egui/src/dialogs/symbol_options.rs index 146e02c6eb..9d73ad769d 100644 --- a/crates/ui-egui/src/dialogs/symbol_options.rs +++ b/crates/ui-egui/src/dialogs/symbol_options.rs @@ -8,7 +8,8 @@ //! `exportType` (`movieClip` | `graphic`), `type` (`dynamic` | //! `static`; a new symbol is dynamic), `registration` (0..8, the 9-point grid; //! 4 = centre), `alignToPixelGrid` (bool, off for a new symbol), `__edit` (true when editing an -//! existing symbol). Help: +//! existing symbol), `__keepArt` (true when a new symbol leaves the selection as ordinary art). +//! Help: //! . use serde_json::{Map, Value, json}; @@ -69,15 +70,23 @@ const EXPORT_TYPES: [(&str, &str); 2] = [("movieClip", "Movie Clip"), ("graphic" pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Symbol Options").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM }; -/// Open Symbol Options to name a new symbol made from the selection. -pub fn open(app: &mut VectorcraftApp) -> Result { +/// Open Symbol Options to name a new symbol made from the selection. With `keep_art`, OK leaves +/// the selection as ordinary art instead of replacing it with an instance. +pub fn open(app: &mut VectorcraftApp, keep_art: bool) -> Result { let st = app.session.active().ok_or("no document open")?; if st.selection.is_empty() { return Err("nothing selected".into()); } let name = st.doc.unique_symbol_name("New Symbol"); - let mut fields = - json!({ "name": name, "exportType": "movieClip", "type": "dynamic", "registration": 4, "alignToPixelGrid": false, "__edit": false }); + let mut fields = json!({ + "name": name, + "exportType": "movieClip", + "type": "dynamic", + "registration": 4, + "alignToPixelGrid": false, + "__edit": false, + "__keepArt": keep_art, + }); if let Some(o) = fields.as_object_mut() { o.extend(slice_fields(None)); } @@ -193,6 +202,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } else { let mut params = json!({ "name": name, "exportType": export, "type": kind, "registration": registration, "alignToPixelGrid": pixel }); merge(&mut params, slice_params(d)); + if d.bool("__keepArt") { + params["keepArt"] = json!(true); + } app.run("symbol.new", params) }; if r.is_ok() { diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index b4e1c668ac..d5923e842a 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -781,10 +781,17 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option edit.unwrap_or(false), Err(e) => return Some(Err(e)), }; + let keep_art = match opt_bool(p, "keepArt") { + Ok(keep) => keep.unwrap_or(false), + Err(e) => return Some(Err(e)), + }; if edit || name.is_some() { + if keep_art { + return Some(Err("`keepArt` applies only to a new symbol".into())); + } crate::dialogs::symbol_options::open_edit(app, name.as_deref()) } else { - crate::dialogs::symbol_options::open(app) + crate::dialogs::symbol_options::open(app, keep_art) } } "ui.newBrush" => crate::dialogs::new_brush::open(app, p.get("ids").cloned()), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 677b804720..faa14fa697 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -974,7 +974,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.symbolOptions", "Symbol Options…", "F8", - "{name?} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}. With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}", + "{name?, edit?, keepArt?: false} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}, with keepArt: true when it was opened with keepArt: true (the selection stays ordinary art). With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}; keepArt: true is then an error", ), ( "tool.options", diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 13e4f172e6..01399b1da8 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -380,11 +380,15 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.min_rect() }); let zone = ui.interact(list_rect, ui.scope_id().with("symbols-drop"), Sense::hover()); - if !over_symbol - && let Some(ids) = widgets::art_drop(ui, &zone) - && let Err(e) = app.run("symbol.new", json!({ "ids": ids, "type": "dynamic" })) - { - app.status(e); + if !over_symbol && let Some(ids) = widgets::art_drop(ui, &zone) { + // Shift held at the release keeps the dropped art as ordinary art. + let mut p = json!({ "ids": ids, "type": "dynamic" }); + if modifiers_at_release(ui).shift { + p["keepArt"] = json!(true); + } + if let Err(e) = app.run("symbol.new", p) { + app.status(e); + } } // Redefine Symbol with the dropped art, which becomes an instance of it, in one undo step. if let Some((name, ids)) = redefine @@ -426,8 +430,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } else if new.clicked() { // 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!({})) }; + // dialog's default. Shift keeps the selected art as ordinary art, with or without Alt. + let m = ui.input(|i| i.modifiers); + let (cmd, mut p) = if m.alt { ("symbol.new", json!({"type": "dynamic"})) } else { ("ui.symbolOptions", json!({})) }; + if m.shift { + p["keepArt"] = json!(true); + } app.run(cmd, p).ok(); } // Alt deletes an unused symbol without asking; a symbol with instances still asks. @@ -452,9 +460,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let inst = has_instances_selected(app); let name = json!({"name": sel}); // Shift keeps the selected art as ordinary art instead of making it an instance. - let redefine = if ui.input(|i| i.modifiers.shift) { json!({"name": sel, "keepArt": true}) } else { name.clone() }; + let shift = ui.input(|i| i.modifiers.shift); + let redefine = if shift { json!({"name": sel, "keepArt": true}) } else { name.clone() }; + let new = if shift { json!({"keepArt": true}) } else { json!({}) }; let items: [(&str, bool, &str, Value); 3] = [ - (tl!("New Symbol…"), has_sel, "ui.symbolOptions", json!({})), + (tl!("New Symbol…"), has_sel, "ui.symbolOptions", new), (tl!("Redefine Symbol"), has_sel && sel.is_some(), "symbol.update", redefine), (tl!("Duplicate Symbol"), sel.is_some(), "symbol.duplicate", name.clone()), ]; @@ -573,14 +583,20 @@ fn art_redefine_drop(ui: &Ui, item: &egui::Response, doc: &Document, uid: Option /// Whether Alt (Option) is held for a drop: when the primary button went up in this frame, as it /// went up, else now. fn alt_at_release(ui: &Ui) -> bool { + modifiers_at_release(ui).alt +} + +/// The modifiers held for a drop: when the primary button went up in this frame, as it went up, +/// else now. +fn modifiers_at_release(ui: &Ui) -> egui::Modifiers { ui.input(|i| { i.events .iter() .find_map(|e| match e { - egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } => Some(modifiers.alt), + egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } => Some(*modifiers), _ => None, }) - .unwrap_or(i.modifiers.alt) + .unwrap_or(i.modifiers) }) } @@ -928,6 +944,112 @@ mod tests { assert_eq!(art(&app, "Dot"), (1, 0), "without Shift the rectangle becomes an instance"); } + /// `leaf_and_dot` with a selected 60 × 20 rectangle; returns its id. + fn leaf_dot_and_rect() -> (VectorcraftApp, NodeId) { + let mut app = leaf_and_dot(); + let rect = NodeId(app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [rect.0]})).unwrap(); + (app, rect) + } + + /// New Symbol… in the panel menu with Shift held opens Symbol Options, and its OK makes the + /// symbol and leaves the selected art as ordinary art, still selected, in one undo step, though + /// Shift is let go before OK; Cancel makes no symbol. Without Shift, OK makes the art an + /// instance. + #[test] + fn shift_new_symbol_in_the_menu_keeps_the_art_as_ordinary_art() { + let (mut app, rect) = leaf_dot_and_rect(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + click_menu_held(&ctx, &mut app, "New Symbol…", egui::Modifiers::SHIFT); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_options::KIND)); + crate::dialogs::cancel(&mut app); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "Cancel makes no symbol"); + click_menu_held(&ctx, &mut app, "New Symbol…", egui::Modifiers::SHIFT); + menu_frame(&ctx, &mut app, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + let undo = undo_len(&app); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(symbols(&mut app), ["Leaf", "Dot", "New Symbol"]); + assert_eq!(art(&app, "New Symbol"), (0, 1), "the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect], "and stays selected"); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + click_menu_held(&ctx, &mut app, "New Symbol…", egui::Modifiers::NONE); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(art(&app, "New Symbol 2"), (1, 0), "without Shift the rectangle becomes an instance"); + } + + /// Clicks the panel's New Symbol button with `modifiers` held. + fn click_new(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 == "New Symbol").expect("a New 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); + } + + /// The New Symbol button with Shift held opens Symbol Options, whose OK keeps the selected art + /// as ordinary art; with Shift and Alt it makes the symbol at once under the default name and + /// keeps the art. Alt alone still makes the art an instance at once. + #[test] + fn shift_new_symbol_button_keeps_the_art_with_or_without_alt() { + let (mut app, rect) = leaf_dot_and_rect(); + click_new(&mut app, egui::Modifiers::SHIFT); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_options::KIND)); + assert_eq!(symbols(&mut app).len(), 2, "no symbol before OK"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(art(&app, "New Symbol"), (0, 1), "Shift: the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect]); + let undo = undo_len(&app); + click_new(&mut app, egui::Modifiers::SHIFT | egui::Modifiers::ALT); + assert_eq!(dialog_kind(&app), None, "Alt skips Symbol Options"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot", "New Symbol", "New Symbol 2"]); + assert_eq!(art(&app, "New Symbol 2"), (0, 1), "Shift and Alt: the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect]); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + click_new(&mut app, egui::Modifiers::ALT); + assert_eq!(art(&app, "New Symbol 3"), (1, 0), "Alt alone: the rectangle becomes an instance"); + } + + /// Art dropped on the panel with Shift held as the primary button goes up becomes a new + /// symbol and stays ordinary art, still selected, though Shift is let go later in the same + /// frame; dropped without Shift, it becomes an instance. + #[test] + fn shift_art_drop_on_the_panel_keeps_the_art_as_ordinary_art() { + let (mut app, rect) = leaf_dot_and_rect(); + let ctx = egui::Context::default(); + let at = pos2(180.0, 60.0); + let release = |modifiers| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers }; + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![rect]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::SHIFT); + let undo = undo_len(&app); + let let_go = egui::Event::ModifiersChanged(egui::Modifiers::NONE); + frame_held(&ctx, &mut app, vec![release(egui::Modifiers::SHIFT), let_go], egui::Modifiers::SHIFT); + assert_eq!(symbols(&mut app).len(), 3, "a new symbol"); + assert_eq!(art(&app, "New Symbol"), (0, 1), "the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect], "and stays selected"); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![rect]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::NONE); + frame_held(&ctx, &mut app, vec![release(egui::Modifiers::NONE)], egui::Modifiers::NONE); + assert_eq!(art(&app, "New Symbol 2"), (1, 0), "without Shift the rectangle becomes an instance"); + } + + /// `ui.symbolOptions` takes `keepArt` only as true or false, and only for a new symbol. + #[test] + fn symbol_options_checks_keep_art() { + let (mut app, _) = leaf_dot_and_rect(); + for bad in [json!("yes"), json!(1)] { + let e = app.run("ui.symbolOptions", json!({ "keepArt": bad })).unwrap_err(); + assert!(e.contains("`keepArt` must be true or false"), "{bad}: {e}"); + } + let e = app.run("ui.symbolOptions", json!({"edit": true, "name": "Dot", "keepArt": true})).unwrap_err(); + assert!(e.contains("only to a new symbol"), "{e}"); + assert_eq!(dialog_kind(&app), None); + app.run("ui.symbolOptions", json!({"edit": true, "name": "Dot", "keepArt": false})).unwrap(); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_options::KIND)); + } + /// #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] diff --git a/docs/mcp.md b/docs/mcp.md index 1f01b5aeea..b869052906 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3434,7 +3434,13 @@ already walks Image Trace. Short agent entry points: - Symbols: `symbol.list` (each row includes `registration` 0..8, `exportType`: `movieClip`|`graphic`, `type`: `static`|`dynamic` and `alignToPixelGrid`), - `symbol.new {name?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, alignToPixelGrid?, ids?}`, + `symbol.new {name?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, alignToPixelGrid?, ids?, keepArt?: false}` + (New Symbol: the selection, or `ids`, becomes the symbol's art and an instance of it in one undo step; with + `keepArt: true` the art stays ordinary art in its place, with its ids, and stays selected unless it is hidden or + locked, and the result's `id` is null; a `keepArt` other than true or false is an error; the Symbols panel sends + `keepArt: true` when its New Symbol button, with or without Alt, or its New Symbol… menu item is used with Shift + held, through Symbol Options' OK (`ui.symbolOptions {keepArt: true}`), and when art dragged off the canvas is + released on the panel with Shift held), `symbol.options {name?, newName?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, alignToPixelGrid?}` (`nineSlice` bool turns 9-slice guides on or off; `nineSliceGuides` is `[left, top, right, bottom]`, fractions of the symbol size in from each edge, each -16..16 with `left + right < 1` and `top + bottom < 1`, a quarter each when none are given; below 0 @@ -9756,7 +9762,7 @@ thread. When `effect.expandAppearance` keeps a frame as type in a group (type wi effects are shadows, outer glows or Crop Marks), the type stays in the thread in the frame's place. Object › Expand (`object.expand`) outlines type with these two commands. `object.flattenTransparency` takes each frame of threaded text that it outlines (`textToOutlines`) or turns into flat regions or an image out of its thread in the same way. -`symbol.new` (New Symbol) and `symbol.update` (Redefine Symbol, without `keepArt: true`) take each frame of threaded text in the selection out +`symbol.new` (New Symbol) and `symbol.update` (Redefine Symbol), without `keepArt: true`, take each frame of threaded text in the selection out of its thread in the same way, and the symbol's art holds a copy of the frame with the text it shows. When every frame of a thread goes into the symbol, the copy of the last frame keeps the text it has no room for. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 375c2fe958..85c06770ef 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1095,6 +1095,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Drag a symbol onto Delete Symbol to delete it** ([the tutorial](https://shop.smashingmagazine.com/2011/09/an-in-depth-study-of-symbols-in-illustrator-cs5/), [Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): a symbol dragged from the Symbols panel, in thumbnail view or a list view, and released on the Delete Symbol button is deleted as a click on the button deletes it (`symbol.delete`): an unused symbol asks "Delete the selected symbol?", a symbol with placed instances asks with Expand Instances, Delete Instances and Cancel, and Alt held at the release deletes an unused symbol without asking. VectorCraft's own rules: the dragged symbol is deleted, not the current one, in one undo step; a symbol that Select All Unused picked deletes every picked symbol still unused, after one question, and a symbol outside the pick is deleted on its own; the button is outlined while a symbol of the document is held over it; a library symbol, art, a name the document no longer has or a symbol dragged from another document is ignored. Tests: `panels::symbols::tests::symbol_dropped_on_delete_button_deletes_the_dragged_symbol_in_both_views`, `a_picked_symbol_dropped_on_delete_deletes_the_picked_symbols`, `delete_symbol_button_ignores_other_drops_and_releases_outside`. - **Alt-drag art onto a symbol to redefine it** ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=194), Modify a symbol instance section): art dragged off the canvas and released on a symbol in the Symbols panel with Alt (Option on macOS) held replaces that symbol's art, and every instance of the symbol updates, as Redefine Symbol does (`symbol.update` with the dragged art's `ids`). Released without Alt, the art still becomes a new symbol. VectorCraft's own rules: the symbol under the pointer is redefined, not the current one, in thumbnail view and both list views; the art becomes an instance of it, in one undo step; only that tile or row is outlined while the art is held over it with Alt; art of another document, objects the document no longer has and art that holds an instance of the symbol (directly, in an opacity mask or through the symbols it nests, which Redefine Symbol from the menu also refuses) change nothing. Tests: `panels::symbols::tests::alt_art_drop_on_a_symbol_redefines_that_symbol_in_one_step`, `alt_let_go_after_the_release_in_the_same_frame_still_redefines`, `a_plain_art_drop_on_a_symbol_makes_a_new_symbol`, `an_alt_art_drop_that_cannot_redefine_changes_nothing`, `a_secondary_button_release_drops_no_art`, `tests::brushsym::redefine_refuses_art_holding_an_instance_of_the_symbol`. - **Shift with Redefine Symbol keeps the art** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html), Redefine a symbol with another object section): Redefine Symbol chosen from the Symbols panel menu with Shift held updates the symbol and every instance of it from the selected art, and the selected art stays ordinary art instead of becoming an instance (`symbol.update {keepArt: true}`). Chosen without Shift, the art still becomes an instance. VectorCraft's own rules: the art keeps its ids, layer and place in the stacking order and stays selected, apart from art that is hidden or locked; the result has no instance id; the redefine is one undo step and, for the symbol being edited, also leaves symbol editing mode; `keepArt` defaults to false, and a value other than true or false is an error. Tests: `panels::symbols::tests::shift_redefine_symbol_in_the_menu_keeps_the_art_as_ordinary_art`, `tests::brushsym::redefine_with_keep_art_leaves_the_art_as_ordinary_art`, `redefine_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch`, `tests::symboledit::redefining_the_symbol_being_edited_with_keep_art_leaves_the_art_and_the_mode`. + - **Shift with New Symbol keeps the art** ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=192), Create a symbol section): holding Shift while making a new symbol from the selected art, with the Symbols panel's New Symbol button, its New Symbol… menu item or by dragging the art onto the panel, adds the symbol and leaves the art as ordinary art instead of turning it into an instance (`symbol.new {keepArt: true}`). Without Shift, the art still becomes an instance. VectorCraft's own rules: Shift is read when the button or menu item is clicked, or when the dragged art is released, and Symbol Options' OK uses it even if Shift has been let go; Shift with Alt on the button makes the symbol without Symbol Options and keeps the art; the art keeps its ids, layer and place in the stacking order and stays selected, apart from art that cannot be selected (hidden or locked art, art in a hidden or locked group or layer, template art, art outside an isolated group, art on a locked artboard); frames of threaded text stay in their thread; the result has no instance id; the new symbol becomes the current symbol in one undo step; `keepArt` defaults to false, and a value other than true or false is an error. Tests: `panels::symbols::tests::shift_new_symbol_in_the_menu_keeps_the_art_as_ordinary_art`, `shift_new_symbol_button_keeps_the_art_with_or_without_alt`, `shift_art_drop_on_the_panel_keeps_the_art_as_ordinary_art`, `symbol_options_checks_keep_art`, `tests::brushsym::new_symbol_with_keep_art_leaves_the_art_as_ordinary_art`, `new_symbol_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch`, `cmd::threads::tests::frames_kept_as_art_by_a_new_or_redefined_symbol_stay_in_their_thread`. - **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`. - **Symbols › Sort by Name and the list views** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Sort by Name puts the symbols in alphabetical order (`symbol.sortByName`), and its Thumbnail View, Small List View and Large List View show them as thumbnails, in a compact list or in a list with larger thumbnails. VectorCraft's own rules: the sort ignores case and keeps names that differ only in case in their order; it changes the document's order, which `symbol.list` reports, as one undo step, keeps the current symbol and adds no undo step when the symbols are already in order; Thumbnail View is the default, Small List View has 18-point rows with 14-point thumbnails and Large List View 26-point rows with 22-point thumbnails, and a click or double-click on a symbol does the same in every view. `ui.panelView` sets the view of the Symbols panel, and of the Swatches and Graphic Styles panels, as their panel menus do. Tests: `tests::brushsym::symbol_sort_by_name_orders_the_symbols_in_one_undo_step`, `panels::symbols::tests::sort_by_name_and_the_small_and_large_list_views`, `panels::symbols::tests::panel_view_sets_the_view_of_each_panel`. - **The Symbols panel reads its current symbol from the document:** the Symbols panel and its panel menu read the current symbol on each frame without running `symbol.list`, which counts every symbol's instances by walking the whole document. The current symbol they show and act on is the one `symbol.list` reports, and an idle frame of the panel or its menu runs no command, so on macOS the native menu is not brought up to date on every frame while the panel is open. In a document with 200 symbols and 50,000 objects, the read takes 0.035 µs instead of 48.5 ms in a release build (thread CPU time on Linux, median of 7 runs); in a small document the difference is too small to notice. Tests: `tests::brushsym::current_symbol_is_the_current_symbol_list_answers`, `panels::symbols::tests::current_is_the_current_symbol_list_answers`, `panels::symbols::tests::idle_frames_of_the_panel_and_its_menu_run_no_command`; the timing probe is `panels::symbols::tests::current_symbol_read_timing`. From 6a1be1e26e69df463d167e740a98084f437df309 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 14:02:54 -0800 Subject: [PATCH 11/33] Symbols: the bottom bar's Symbol Options button edits the current symbol MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Symbols panel's bottom bar gets a Symbol Options button between Break Link to Symbol and New Symbol. A click, with or without Alt, opens Symbol Options on the current symbol, as the panel menu's Symbol Options… does (`ui.symbolOptions {edit: true}`). The button is disabled while the document has no current symbol, and it uses the Swatch Options icon. --- crates/ui-egui/src/panels/symbols.rs | 57 ++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 2 files changed, 58 insertions(+) diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 01399b1da8..6b2f6f8d39 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -420,6 +420,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if widgets::icon_button_enabled(ui, "link-2-off", tl!("Break Link to Symbol"), false, inst, 24.0).clicked() { app.run("symbol.breakLink", json!({})).ok(); } + // Opens Symbol Options on the current symbol, as the panel menu's Symbol Options… does; + // Alt does the same. + if widgets::icon_button_enabled(ui, "dc-options", tl!("Symbol Options"), false, sel.is_some(), 24.0).clicked() { + app.run("ui.symbolOptions", json!({"edit": true, "name": sel})).ok(); + } ui.add_space((ui.available_width() - 2.0 * 28.0).max(0.0)); let new = widgets::icon_button_enabled(ui, "dc-new-item", tl!("New Symbol"), false, has_sel, 24.0); // A symbol dragged from the panel and dropped on New Symbol is duplicated, with or without @@ -1011,6 +1016,58 @@ mod tests { assert_eq!(art(&app, "New Symbol 3"), (1, 0), "Alt alone: the rectangle becomes an instance"); } + /// The center of the panel's Symbol Options button, and of Break Link to Symbol and New Symbol + /// beside it, in a frame of `app`. + fn options_button(app: &mut VectorcraftApp) -> (Pos2, Pos2, Pos2) { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let found = clickable(&frame_held(&ctx, app, vec![], egui::Modifiers::NONE)); + let at = |label: &str| found.iter().find(|(l, _)| l == label).unwrap_or_else(|| panic!("a {label} button")).1; + (at("Break Link to Symbol"), at("Symbol Options"), at("New Symbol")) + } + + /// Clicks the panel at `at` with `modifiers` held. + fn click_at(app: &mut VectorcraftApp, at: Pos2, modifiers: egui::Modifiers) { + let ctx = egui::Context::default(); + frame_held(&ctx, app, vec![], modifiers); + 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); + } + + /// The bottom bar's Symbol Options button sits between Break Link to Symbol and New Symbol and + /// opens Symbol Options on the current symbol, as the panel menu's item does, with or without + /// Alt, and adds no undo step; in a document without symbols it is disabled and opens nothing. + #[test] + fn symbol_options_button_edits_the_current_symbol() { + let mut app = leaf_and_dot(); + app.run("select.all", json!({})).unwrap(); + let (break_link, options, new) = options_button(&mut app); + assert!(break_link.x < options.x && options.x < new.x, "Break Link, Symbol Options, New Symbol: {break_link:?} {options:?} {new:?}"); + let undo = undo_len(&app); + for (current, modifiers) in [("Dot", egui::Modifiers::NONE), ("Leaf", egui::Modifiers::ALT)] { + app.run("symbol.setCurrent", json!({ "name": current })).unwrap(); + click_at(&mut app, options, modifiers); + let d = app.ui.dialog.as_ref().expect("Symbol Options opens"); + assert_eq!(d.kind, crate::dialogs::symbol_options::KIND); + assert_eq!((d.fields.get("name"), d.fields.get("__edit")), (Some(&json!(current)), Some(&json!(true))), "{modifiers:?}"); + crate::dialogs::cancel(&mut app); + } + assert_eq!(undo_len(&app), undo, "opening the dialog adds no undo step"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"]); + let mut empty = VectorcraftApp::new(Session::new(), Default::default()); + empty.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + for (app, disabled) in [(&mut app, false), (&mut empty, true)] { + let out = frame_held(&ctx, app, vec![], egui::Modifiers::NONE); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let button = &nodes.iter().find(|(_, n)| n.label().is_some_and(|l| l.trim() == "Symbol Options")).expect("a Symbol Options button").1; + assert_eq!(button.is_disabled(), disabled, "disabled without a current symbol"); + } + click_at(&mut empty, options, egui::Modifiers::NONE); + assert_eq!(dialog_kind(&empty), None, "no symbol, no dialog"); + } + /// Art dropped on the panel with Shift held as the primary button goes up becomes a new /// symbol and stays ordinary art, still selected, though Shift is let go later in the same /// frame; dropped without Shift, it becomes an instance. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 804364be5e..233d715794 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1101,6 +1101,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Alt-drag art onto a symbol to redefine it** ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=194), Modify a symbol instance section): art dragged off the canvas and released on a symbol in the Symbols panel with Alt (Option on macOS) held replaces that symbol's art, and every instance of the symbol updates, as Redefine Symbol does (`symbol.update` with the dragged art's `ids`). Released without Alt, the art still becomes a new symbol. VectorCraft's own rules: the symbol under the pointer is redefined, not the current one, in thumbnail view and both list views; the art becomes an instance of it, in one undo step; only that tile or row is outlined while the art is held over it with Alt; art of another document, objects the document no longer has and art that holds an instance of the symbol (directly, in an opacity mask or through the symbols it nests, which Redefine Symbol from the menu also refuses) change nothing. Tests: `panels::symbols::tests::alt_art_drop_on_a_symbol_redefines_that_symbol_in_one_step`, `alt_let_go_after_the_release_in_the_same_frame_still_redefines`, `a_plain_art_drop_on_a_symbol_makes_a_new_symbol`, `an_alt_art_drop_that_cannot_redefine_changes_nothing`, `a_secondary_button_release_drops_no_art`, `tests::brushsym::redefine_refuses_art_holding_an_instance_of_the_symbol`. - **Shift with Redefine Symbol keeps the art** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html), Redefine a symbol with another object section): Redefine Symbol chosen from the Symbols panel menu with Shift held updates the symbol and every instance of it from the selected art, and the selected art stays ordinary art instead of becoming an instance (`symbol.update {keepArt: true}`). Chosen without Shift, the art still becomes an instance. VectorCraft's own rules: the art keeps its ids, layer and place in the stacking order and stays selected, apart from art that is hidden or locked; the result has no instance id; the redefine is one undo step and, for the symbol being edited, also leaves symbol editing mode; `keepArt` defaults to false, and a value other than true or false is an error. Tests: `panels::symbols::tests::shift_redefine_symbol_in_the_menu_keeps_the_art_as_ordinary_art`, `tests::brushsym::redefine_with_keep_art_leaves_the_art_as_ordinary_art`, `redefine_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch`, `tests::symboledit::redefining_the_symbol_being_edited_with_keep_art_leaves_the_art_and_the_mode`. - **Shift with New Symbol keeps the art** ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=192), Create a symbol section): holding Shift while making a new symbol from the selected art, with the Symbols panel's New Symbol button, its New Symbol… menu item or by dragging the art onto the panel, adds the symbol and leaves the art as ordinary art instead of turning it into an instance (`symbol.new {keepArt: true}`). Without Shift, the art still becomes an instance. VectorCraft's own rules: Shift is read when the button or menu item is clicked, or when the dragged art is released, and Symbol Options' OK uses it even if Shift has been let go; Shift with Alt on the button makes the symbol without Symbol Options and keeps the art; the art keeps its ids, layer and place in the stacking order and stays selected, apart from art that cannot be selected (hidden or locked art, art in a hidden or locked group or layer, template art, art outside an isolated group, art on a locked artboard); frames of threaded text stay in their thread; the result has no instance id; the new symbol becomes the current symbol in one undo step; `keepArt` defaults to false, and a value other than true or false is an error. Tests: `panels::symbols::tests::shift_new_symbol_in_the_menu_keeps_the_art_as_ordinary_art`, `shift_new_symbol_button_keeps_the_art_with_or_without_alt`, `shift_art_drop_on_the_panel_keeps_the_art_as_ordinary_art`, `symbol_options_checks_keep_art`, `tests::brushsym::new_symbol_with_keep_art_leaves_the_art_as_ordinary_art`, `new_symbol_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch`, `cmd::threads::tests::frames_kept_as_art_by_a_new_or_redefined_symbol_stay_in_their_thread`. + - **Symbol Options button** ([Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [Create and place symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)): the help pages list a Symbol Options control among the Symbols panel's buttons, after Break Link to Symbol and before New Symbol, and it opens the settings of the chosen symbol. The panel's bottom bar has that button, and a click opens Symbol Options on the current symbol, as the panel menu's Symbol Options… does (`ui.symbolOptions {edit: true}`). VectorCraft's own rules: the button is disabled while the document has no current symbol, Alt-click does the same as a plain click, opening the dialog adds no undo step, and the icon is the one Swatch Options uses. Tests: `panels::symbols::tests::symbol_options_button_edits_the_current_symbol`. - **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`. - **Symbols › Sort by Name and the list views** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Sort by Name puts the symbols in alphabetical order (`symbol.sortByName`), and its Thumbnail View, Small List View and Large List View show them as thumbnails, in a compact list or in a list with larger thumbnails. VectorCraft's own rules: the sort ignores case and keeps names that differ only in case in their order; it changes the document's order, which `symbol.list` reports, as one undo step, keeps the current symbol and adds no undo step when the symbols are already in order; Thumbnail View is the default, Small List View has 18-point rows with 14-point thumbnails and Large List View 26-point rows with 22-point thumbnails, and a click or double-click on a symbol does the same in every view. `ui.panelView` sets the view of the Symbols panel, and of the Swatches and Graphic Styles panels, as their panel menus do. Tests: `tests::brushsym::symbol_sort_by_name_orders_the_symbols_in_one_undo_step`, `panels::symbols::tests::sort_by_name_and_the_small_and_large_list_views`, `panels::symbols::tests::panel_view_sets_the_view_of_each_panel`. - **The Symbols panel reads its current symbol from the document:** the Symbols panel and its panel menu read the current symbol on each frame without running `symbol.list`, which counts every symbol's instances by walking the whole document. The current symbol they show and act on is the one `symbol.list` reports, and an idle frame of the panel or its menu runs no command, so on macOS the native menu is not brought up to date on every frame while the panel is open. In a document with 200 symbols and 50,000 objects, the read takes 0.035 µs instead of 48.5 ms in a release build (thread CPU time on Linux, median of 7 runs); in a small document the difference is too small to notice. Tests: `tests::brushsym::current_symbol_is_the_current_symbol_list_answers`, `panels::symbols::tests::current_is_the_current_symbol_list_answers`, `panels::symbols::tests::idle_frames_of_the_panel_and_its_menu_run_no_command`; the timing probe is `panels::symbols::tests::current_symbol_read_timing`. From 681830b35db6a34b49785a32c9a221d454465d7d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 14:43:49 -0800 Subject: [PATCH 12/33] Symbols: the headless UI catalog lists Symbol Options' edit and keepArt parameters crates/mcp/src/ui_catalog.rs is generated from the desktop UI command table, and was not regenerated after symbolOptions gained edit and keepArt. cargo xtask ui-commands regenerates it, and cargo xtask ui-commands --check passes. --- crates/mcp/src/ui_catalog.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index b6da21331e..d2d3c71df4 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -973,7 +973,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.symbolOptions", "Symbol Options…", "F8", - "{name?} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}. With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}", + "{name?, edit?, keepArt?: false} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}, with keepArt: true when it was opened with keepArt: true (the selection stays ordinary art). With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}; keepArt: true is then an error", ), ( "tool.options", From b4d5d192ba13541c4c9e5b761e2367392cc509be Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 15:57:45 -0800 Subject: [PATCH 13/33] Shear: angles from -359 to 359 shear by their own tangent instead of stopping at 89 object.shear clamped its angle to -89..89 without an error, so any angle past 89 sheared by 89. It now takes the Shear dialog's documented range of -359 to 359 degrees and shears by the angle's tangent, so 120 slants as -60. An angle outside that range, and +-90 and +-270 (within 1e-9 degrees), where the tangent is unbounded, return an error naming `angle`; nothing moves and no undo step is recorded. Docs: params text, docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/cmd/object/transform.rs | 14 ++++++- crates/engine/src/tests/xform.rs | 46 +++++++++++++++++++++++ docs/mcp.md | 6 ++- docs/target-app-parity.md | 2 +- 5 files changed, 66 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 0c638ceb5e..e17d9ef634 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -61,7 +61,7 @@ pub fn specs() -> Vec { "Shear…", ["Object", "Transform"], None, - "{ids?: [id…] (selected first; default: the selection), angle: deg (positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\", origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), angle: deg (-359 to 359, sheared by its tangent, so 120 slants as -60; ±90 and ±270 are an error; positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\", origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection, shear ), diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 25a831622e..881776cc3a 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -414,12 +414,24 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { apply_transform(s, "Reflect", ids, about(o, m), p, true) } +/// Angles closer than this many degrees to ±90 or ±270 count as those angles. It is far above the +/// rounding error of an angle up to 359° and below any angle a field shows. +const SHEAR_ANGLE_TOLERANCE: f64 = 1e-9; + pub(super) fn shear(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["angle"], "object.shear")?; check_switches(p, &TRANSFORM_SWITCHES, "object.shear")?; + let angle = f64_or(p, "angle", 0.0); + if !(-359.0..=359.0).contains(&angle) { + return Err(bad("object.shear", format!("`angle` must be from -359 to 359 degrees, not {angle}"))); + } + // ±90 and ±270 slant an edge onto the shear axis: their tangent is unbounded. + if (angle.rem_euclid(180.0) - 90.0).abs() < SHEAR_ANGLE_TOLERANCE { + return Err(bad("object.shear", format!("`angle` cannot be {angle}: ±90 and ±270 degrees have no shear"))); + } let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - let t = f64_or(p, "angle", 0.0).clamp(-89.0, 89.0).to_radians().tan(); + let t = angle.to_radians().tan(); let vertical = choice(p, "object.shear", "axis", &["horizontal", "vertical"])? == Some("vertical"); let m = if vertical { Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]) } else { Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]) }; apply_transform(s, "Shear", ids, about(o, m), p, true) diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index 4e13e5fe02..7c6a53d27e 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -511,6 +511,52 @@ fn reflect_and_shear_reject_unknown_axes_without_changing_state() { assert!((b.y0 + 30.0).abs() < 1e-6 && (b.y1 + 20.0).abs() < 1e-6 && b.width() > 30.0, "along the horizontal axis: {b:?}"); } +/// Shear takes an angle from -359 to 359 degrees and shears by its tangent: 60 and -60 slant +/// opposite ways, and 120 and 300 slant as -60 does. +#[test] +fn shear_angles_slant_by_their_tangent() { + let run = 100.0 * 60f64.to_radians().tan(); + for (angle, want) in [ + (60.0, Rect::new(-run, 0.0, 100.0, 100.0)), + (-60.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)), + (120.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)), + (300.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)), + (-359.0, Rect::new(-100.0 * 1f64.to_radians().tan(), 0.0, 100.0, 100.0)), + ] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("object.shear", &json!({"angle": angle, "origin": [0, 0]})).unwrap(); + assert!(close(bounds(&s, a), want), "{angle}: {:?}, want {want:?}", bounds(&s, a)); + } +} + +/// Shear returns an error for an angle outside -359 to 359 and for ±90 and ±270, which have no +/// finite shear (within a billionth of a degree too); nothing moves and no undo step is recorded. +#[test] +fn shear_rejects_angles_with_no_shear_or_out_of_range() { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0); + let n = undo_len(&s); + let none = |v: f64| format!("invalid parameters for `object.shear`: `angle` cannot be {v}: ±90 and ±270 degrees have no shear"); + let range = |v: f64| format!("invalid parameters for `object.shear`: `angle` must be from -359 to 359 degrees, not {v}"); + for (angle, msg) in [ + (90.0, none(90.0)), + (-90.0, none(-90.0)), + (270.0, none(270.0)), + (-270.0, none(-270.0)), + (90.0 + 1e-12, none(90.0 + 1e-12)), + (360.0, range(360.0)), + (-359.5, range(-359.5)), + (1e300, range(1e300)), + ] { + let e = s.execute("object.shear", &json!({"angle": angle})).expect_err(&angle.to_string()); + assert_eq!(e.to_string(), msg); + } + assert!(s.execute("object.shear", &json!({"angle": "45"})).is_err(), "a string is not an angle"); + assert!(close(bounds(&s, a), Rect::new(10.0, 20.0, 40.0, 30.0)), "nothing moved: {:?}", bounds(&s, a)); + assert_eq!(undo_len(&s), n, "no undo step"); +} + #[test] fn distort_command_maps_corners() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 4c1b661f42..6d973eeb44 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6842,7 +6842,11 @@ wide. `object.align` needs `horizontal` or `vertical`. The three Align commands, `object.reflect` and `object.shear` return an error that lists the choices of a `horizontal`, `vertical`, `to`, `axis` or `bounds` param given another value (`object.reflect` also takes an angle and names the value given), and one for a `spacing` that is not a number; nothing -moves. +moves. `object.shear` takes an `angle` from -359 to 359 degrees, the range of the +[Shear dialog](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html), +and shears by its tangent, so 120 slants as -60. It returns an error for an angle outside that range, and, as +VectorCraft's own rule, for ±90 and ±270 (within 1e-9 degrees), which have no finite shear; nothing moves and no undo +step is recorded. ## Glyph bounds for type diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..ea540d6390 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1277,7 +1277,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The settled part of that outline is kept in paths of up to 64 pieces each. A path is shared from one frame to the next until a piece in it changes, and the canvas keeps the triangles it drew the path with while the view stays the same, so a frame does not copy, flatten or tessellate a settled path again; a pan, zoom or rotation draws each one once more. This is VectorCraft's own rule. The line that a drag of more than 64 segments shows with a round Eraser tip, the Knife, the Path Eraser or the Pencil with Live preview off is kept the same way, in pieces of 64 segments: a frame builds again only the last piece, and the Knife's dashes run on from one piece to the next. With the Eraser's Size set to a mode that follows the pen, each step of such a drag is kept as its own path and a frame builds only a new step. A smoothing drag's band is kept until it changes. The canvas still copies the kept triangles of every piece into each frame. - **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). A Reshape drag stretches part of a path from the dragged point without losing the path's general form, as [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) has it. On an open path the stretch reaches both ends: the end anchors stay in place, each anchor between moves less the nearer it lies to an end, and the handles of a smooth anchor stay in line (`path.reshape`; the reach and the shares are VectorCraft's own rule, in `docs/mcp.md`). A click sets a focal point and a click on a segment adds a highlighted anchor there; Shift-click adds more, and a drag from any of them moves them all. The anchors that are not direct-selected stay in place and a closed path selected whole moves whole (VectorCraft's own rule, in `docs/mcp.md`). - 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). + 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. Shear takes an angle from -359° to 359° and shears by its tangent, so 120° slants as -60°; an angle outside that range, and ±90° and ±270° (VectorCraft's own rule), return an error ([shear objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html); `shear_angles_slant_by_their_tangent`, `shear_rejects_angles_with_no_shear_or_out_of_range`). 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). Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with (kept with the UI state; Copy never is), and its Copy button, left of Cancel, transforms a copy of each object as the [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html) help page has it; the Copy checkbox is gone (#1732; the remembered values follow a maintainer comment on the issue, not the help page). Its Scale section has the Relative and Absolute radio buttons the same page describes: percentages of each object's size, or the width and height it becomes (`object.transformEach` `relative`, which Transform Again repeats); Absolute measures each object's own box, and the scales act along its axes about that box's reference point, so a turned shape keeps its shape and objects of different sizes come out alike; the fields show the width and height the selected objects share and read "Mixed" when they differ or a side is 0 (a line's), each object measured by its own box, rotated with it, as the Transform panel and the Control bar show it (sizes they show alike count as the same), and a size typed into them sets every object to it (a side left Mixed keeps its size), our choices where the page leaves them open; a live Repeat scales its spacing by the geometric mean of the two factors, so its Absolute size is approximate. The link beside the two scales keeps them in proportion, as the shape dialogs' Width and Height link does (`__constrain`, kept with the dialog's values; where it sits is our choice, the public pages don't establish it). The panel lists Scale, Move and Rotate, then the Options in two columns (Transform Objects, Transform Patterns, Scale Strokes & Effects, Scale Corners; Reflect X, Reflect Y, Random), the Reference Point, and Preview at the left of the button row, level with Copy, Cancel and OK. Transform Again uses the Copy, Transform Patterns, Scale Strokes & Effects and Scale Corners choices of the transform it repeats; after a bounding-box handle drag on area type, it resizes the type area again and the type keeps its size (`object.transformAgain`). With anchors selected with Direct Selection, Move, Rotate, Scale, Reflect, Shear and Transform Again (the commands, their dialogs and the four tools' drags) transform only those anchors, their handles with them, about the centre of the box around them unless a point was clicked; a copy still copies the whole object (#1408; behaviour reference: [adjust path segments](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html); the default reference point and the copy are our choices). The Move, Rotate, Scale, Reflect and Shear dialogs have a Preview checkbox, off when they open: while it is on the canvas follows the values, Cancel rolls it back and OK is still one undo step; Up/Down step the Rotate and Shear angles and the Scale percentages by 1, Shift by 10 (#1412). The five dialogs and Transform Each have Transform Objects beside Transform Patterns: off, the art stays and only its pattern tiles transform (`objects` on the transform commands), and Transform Again repeats the choice (#1448; behaviour reference: [scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html); the checkboxes are always enabled and the Scale page's pair is applied to all of them, our choices). Reflect's axis is Horizontal, Vertical or an angle (#1460; [reflect objects along an axis](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-objects-along-an-axis.html)). - **Pen:** Alt pressed in the middle of dragging out an anchor splits its handles and keeps the curve already shaped into it (only the outgoing handle follows the pointer); Space held while dragging out an anchor moves it, handles and all. A press on the first anchor of the path being drawn closes it whatever the drag then does: the drag shapes the closing curve and the release closes the path wherever it ends (#501). The first anchor's incoming handle mirrors the pointer, and a click leaves it retracted and the anchor a corner. Its outgoing handle stays where it is on a corner, so the first segment keeps its shape, and on a smooth anchor it turns to stay in line at its own length; Alt makes the anchor a corner and leaves the outgoing handle where it was when Alt went down. The Smart Pen's closing drag does the same (fixes #6634; `path.close`'s `in` and `out`; behavior reference: [draw with the Pen, Curvature, or Pencil tool](https://web.archive.org/web/20220614224656/https://helpx.adobe.com/illustrator/using/drawing-pen-curvature-or-pencil.html), where a click or drag on the first anchor closes the path and Alt breaks the pairing of the closing anchor's handles; which handles the drag sets are our choices). Space held during the Pen's closing drag moves the first anchor, handles and all, as that page also describes (`path.close`'s `at`). Clicking the last anchor of the path being drawn retracts its outgoing handle (convert cursor), and dragging from it pulls out a new one on its own. Auto Add/Delete: over a selected path, a click on a segment adds an anchor and a click on an anchor deletes it (add and delete cursors); Shift held, or Preferences › General › Disable Auto Add/Delete, starts a new path instead. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles, dragging a segment reshapes it; drawing then goes on. Cmd (Ctrl) held drags with the selection tool chosen last, Direct Selection until one is (handles, anchors and segments of the path being drawn or another), and the Pen then goes on drawing its path while that stays selected; the pointer shows that tool's while Cmd is held. The same holds for agents (`pointer_gesture` with `mods.cmd`), as the borrowing now lives in the engine (#494). A drag's preview (the Pen's, the Anchor Point tool's, Direct Selection's handles and anchors) follows every position the pointer is seen at (#834): the canvas sends the tool a drag whenever the pointer's document position differs from the last one it sent, not only when egui's frame delta is non-zero (zero when a compositor coalesces motion and in the frame the pointer comes back into the window after leaving it), and a move that arrives in the release's own frame shapes the preview before the release commits it, once the press has dragged. With the Pen, a press that moves under 3 screen pixels is a click (a corner without handles), and a Precise Cursors command toggles the existing preference and can take a shortcut (#1663). From e7428b7cd35f9e12763fd23462ea218484043196 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 16:31:44 -0800 Subject: [PATCH 14/33] Rerun CI From 5ed88cecc9efbaf3d5f4bf03462c3eb25396c306 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 16:31:55 -0800 Subject: [PATCH 15/33] Rerun CI From cd259b9fa8ff82f8ba0bf785ba4ca389ea3a9d42 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 17:04:12 -0800 Subject: [PATCH 16/33] Shear: 180 and -180 leave the art unchanged The tangent of 180 degrees in radians is about 1e-16, not 0, so a shear by 180 or -180 moved coordinates very slightly and recorded an undo step. Angles within 1e-9 degrees of 0, 180 or -180 now shear by 0: without `copy`, nothing moves and no undo step is recorded. Docs: params text, docs/mcp.md. --- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/cmd/object/transform.rs | 8 +++++--- crates/engine/src/tests/xform.rs | 17 +++++++++++++++++ docs/mcp.md | 3 ++- 4 files changed, 25 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index e17d9ef634..fd7c1a5794 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -61,7 +61,7 @@ pub fn specs() -> Vec { "Shear…", ["Object", "Transform"], None, - "{ids?: [id…] (selected first; default: the selection), angle: deg (-359 to 359, sheared by its tangent, so 120 slants as -60; ±90 and ±270 are an error; positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\", origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), angle: deg (-359 to 359, sheared by its tangent, so 120 slants as -60; 0 and ±180 have no slant and, without copy, change nothing; ±90 and ±270 are an error; positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\", origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection, shear ), diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 881776cc3a..f5fb74cd1a 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -414,8 +414,8 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { apply_transform(s, "Reflect", ids, about(o, m), p, true) } -/// Angles closer than this many degrees to ±90 or ±270 count as those angles. It is far above the -/// rounding error of an angle up to 359° and below any angle a field shows. +/// Angles closer than this many degrees to ±90 or ±270, or to 0 or ±180, count as those angles. It +/// is far above the rounding error of an angle up to 359° and below any angle a field shows. const SHEAR_ANGLE_TOLERANCE: f64 = 1e-9; pub(super) fn shear(s: &mut Session, p: &Value) -> Result { @@ -431,7 +431,9 @@ pub(super) fn shear(s: &mut Session, p: &Value) -> Result { } let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - let t = angle.to_radians().tan(); + // 0 and ±180 have no slant, but the tangent of ±180° in radians is about 1e-16, not 0. + let flat = angle.rem_euclid(180.0); + let t = if flat < SHEAR_ANGLE_TOLERANCE || 180.0 - flat < SHEAR_ANGLE_TOLERANCE { 0.0 } else { angle.to_radians().tan() }; let vertical = choice(p, "object.shear", "axis", &["horizontal", "vertical"])? == Some("vertical"); let m = if vertical { Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]) } else { Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]) }; apply_transform(s, "Shear", ids, about(o, m), p, true) diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index 7c6a53d27e..0bae55a3de 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -557,6 +557,23 @@ fn shear_rejects_angles_with_no_shear_or_out_of_range() { assert_eq!(undo_len(&s), n, "no undo step"); } +/// Shear by 0, 180 or -180 degrees, along either axis, has no slant: the art keeps its exact +/// coordinates and no undo step is recorded. +#[test] +fn shear_by_0_and_180_changes_nothing() { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0); + let before = bounds(&s, a); + let n = undo_len(&s); + for angle in [180.0, -180.0, 0.0, 180.0 + 1e-12, -180.0 - 1e-12] { + for axis in ["horizontal", "vertical"] { + s.execute("object.shear", &json!({"angle": angle, "axis": axis})).unwrap(); + assert_eq!(bounds(&s, a), before, "{angle} {axis}"); + assert_eq!(undo_len(&s), n, "{angle} {axis}: no undo step"); + } + } +} + #[test] fn distort_command_maps_corners() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 6d973eeb44..f535ab2b28 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6844,7 +6844,8 @@ an error that lists the choices of a `horizontal`, `vertical`, `to`, `axis` or ` (`object.reflect` also takes an angle and names the value given), and one for a `spacing` that is not a number; nothing moves. `object.shear` takes an `angle` from -359 to 359 degrees, the range of the [Shear dialog](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html), -and shears by its tangent, so 120 slants as -60. It returns an error for an angle outside that range, and, as +and shears by its tangent, so 120 slants as -60. An angle of 0 or ±180 (within 1e-9 degrees) has no slant: without +`copy`, nothing moves and no undo step is recorded, and with `copy` the copies keep the art's place. It returns an error for an angle outside that range, and, as VectorCraft's own rule, for ±90 and ±270 (within 1e-9 degrees), which have no finite shear; nothing moves and no undo step is recorded. From 9f84820d888728b45c23df02cb1092420f85bcc3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 17:42:44 -0800 Subject: [PATCH 17/33] MCP: transform checks scale, reflect and shear before any step runs The transform tool runs move, rotate, scale, reflect and shear as separate commands. A shear angle that object.shear refuses, such as 90, a reflect axis other than vertical or horizontal, or a scale of 0 failed only after the earlier steps had changed the art and recorded undo steps. The tool now checks those params first with the rules the commands use (scale_factors, reflect_axis and shear_tangent, shared with object.scale, object.reflect and object.shear), so a refused request changes nothing and records no undo step. --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/object.rs | 1 + crates/engine/src/cmd/object/transform.rs | 71 ++++++++++++++--------- crates/mcp/src/tests.rs | 27 +++++++++ crates/mcp/src/tools/definitions.rs | 2 +- crates/mcp/src/tools/handlers.rs | 24 ++++++-- docs/mcp.md | 2 +- 7 files changed, 97 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c4a86dd3a5..99dedd5bda 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -827,6 +827,8 @@ pub use docmenu::guide_indexes; pub(crate) use edit::{settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; +/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with. +pub use object::{reflect_axis, scale_factors, shear_tangent}; pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys}; pub use select::SIMILAR; pub(crate) use vectorcraft_doc::range::parse_range; diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index a58f206c84..fd0aece164 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -42,3 +42,4 @@ pub(crate) use pixelgrid::{ }; pub(super) use shape::recut; pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; +pub use transform::{reflect_axis, scale_factors, shear_tangent}; diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index f5fb74cd1a..3eb9482692 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -360,15 +360,22 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.scale")?; let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - let sx = f64_req(p, "sx", "object.scale")? / 100.0; - let sy = f64_or(p, "sy", sx * 100.0) / 100.0; - if sx == 0.0 || sy == 0.0 { - return Err(bad("object.scale", "scale must be non-zero")); - } + let sx = f64_req(p, "sx", "object.scale")?; + let (sx, sy) = scale_factors(sx, f64_or(p, "sy", sx)).map_err(|e| bad("object.scale", e))?; let frame = basis_frame(s, p, "object.scale", &ids)?; apply_transform(s, "Scale", ids, about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), p, true) } +/// The factors `object.scale` applies for `sx` and `sy` in percent, or the error it returns when +/// either factor is 0. +pub fn scale_factors(sx: f64, sy: f64) -> std::result::Result<(f64, f64), String> { + let (sx, sy) = (sx / 100.0, sy / 100.0); + if sx == 0.0 || sy == 0.0 { + return Err("scale must be non-zero".into()); + } + Ok((sx, sy)) +} + /// The frame that `object.scale` and a named `object.reflect` act in, from the `basis` param: /// `"box"` (the default) is the bounding box of `ids`, turned with rotated objects until Reset /// Bounding Box ([`Document::bbox_angle`]); `"page"` is the page's axes. Anchors selected with @@ -393,16 +400,7 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; // A named axis is the bounding box's own (see [`basis_frame`]); an angle is a line on the page. - let named = match p.get("axis") { - Some(Value::String(a)) if a == "horizontal" => Some(Affine::scale_non_uniform(1.0, -1.0)), - Some(Value::Number(_)) => None, - None | Some(Value::Null) => Some(Affine::scale_non_uniform(-1.0, 1.0)), - Some(Value::String(a)) if a == "vertical" => Some(Affine::scale_non_uniform(-1.0, 1.0)), - Some(v) => { - let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); - return Err(bad("object.reflect", format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`"))); - } - }; + let named = reflect_axis(p.get("axis")).map_err(|e| bad("object.reflect", e))?; let m = match named { Some(m) => basis_frame(s, p, "object.reflect", &ids)?.conjugate(m), None => { @@ -414,26 +412,47 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { apply_transform(s, "Reflect", ids, about(o, m), p, true) } +/// The reflection `object.reflect` applies for its `axis` param: the matrix for a named axis +/// (`"vertical"`, the default, or `"horizontal"`), in the bounding box's frame; `None` for an angle, +/// which is a line on the page; or the error for any other value. +pub fn reflect_axis(axis: Option<&Value>) -> std::result::Result, String> { + match axis { + Some(Value::String(a)) if a == "horizontal" => Ok(Some(Affine::scale_non_uniform(1.0, -1.0))), + Some(Value::Number(_)) => Ok(None), + None | Some(Value::Null) => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))), + Some(Value::String(a)) if a == "vertical" => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))), + Some(v) => { + let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); + Err(format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`")) + } + } +} + /// Angles closer than this many degrees to ±90 or ±270, or to 0 or ±180, count as those angles. It /// is far above the rounding error of an angle up to 359° and below any angle a field shows. const SHEAR_ANGLE_TOLERANCE: f64 = 1e-9; +/// The slant `object.shear` applies for `angle` in degrees: its tangent, and 0 for 0 and ±180. An +/// angle outside -359 to 359, or ±90 or ±270, is an error. +pub fn shear_tangent(angle: f64) -> std::result::Result { + if !(-359.0..=359.0).contains(&angle) { + return Err(format!("`angle` must be from -359 to 359 degrees, not {angle}")); + } + // ±90 and ±270 slant an edge onto the shear axis: their tangent is unbounded. + let flat = angle.rem_euclid(180.0); + if (flat - 90.0).abs() < SHEAR_ANGLE_TOLERANCE { + return Err(format!("`angle` cannot be {angle}: ±90 and ±270 degrees have no shear")); + } + // 0 and ±180 have no slant, but the tangent of ±180° in radians is about 1e-16, not 0. + Ok(if flat < SHEAR_ANGLE_TOLERANCE || 180.0 - flat < SHEAR_ANGLE_TOLERANCE { 0.0 } else { angle.to_radians().tan() }) +} + pub(super) fn shear(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["angle"], "object.shear")?; check_switches(p, &TRANSFORM_SWITCHES, "object.shear")?; - let angle = f64_or(p, "angle", 0.0); - if !(-359.0..=359.0).contains(&angle) { - return Err(bad("object.shear", format!("`angle` must be from -359 to 359 degrees, not {angle}"))); - } - // ±90 and ±270 slant an edge onto the shear axis: their tangent is unbounded. - if (angle.rem_euclid(180.0) - 90.0).abs() < SHEAR_ANGLE_TOLERANCE { - return Err(bad("object.shear", format!("`angle` cannot be {angle}: ±90 and ±270 degrees have no shear"))); - } + let t = shear_tangent(f64_or(p, "angle", 0.0)).map_err(|e| bad("object.shear", e))?; let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - // 0 and ±180 have no slant, but the tangent of ±180° in radians is about 1e-16, not 0. - let flat = angle.rem_euclid(180.0); - let t = if flat < SHEAR_ANGLE_TOLERANCE || 180.0 - flat < SHEAR_ANGLE_TOLERANCE { 0.0 } else { angle.to_radians().tan() }; let vertical = choice(p, "object.shear", "axis", &["horizontal", "vertical"])? == Some("vertical"); let m = if vertical { Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]) } else { Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]) }; apply_transform(s, "Shear", ids, about(o, m), p, true) diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index a6d1fe6c5d..89299c484c 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1634,6 +1634,33 @@ fn doc_json(s: &mut Server) -> Value { serde_json::from_str(&text_of(&r)).unwrap() } +#[test] +fn transform_refused_by_a_later_operation_changes_nothing() { + let mut s = server(); + let count = |s: &mut Server| -> u64 { + let r = call(s, 90, "inspect_document", json!({})); + serde_json::from_str::(&text_of(&r)).unwrap()["objects"].as_u64().unwrap() + }; + let base = count(&mut s); + let r = id_of(&call(&mut s, 1, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 100, "height": 50}))); + let before = doc_json(&mut s); + for (id, args, says) in [ + (2, json!({"ids": [r], "scale": 50, "shear": 90}), "object.shear"), + (3, json!({"ids": [r], "dx": 10, "rotate": 30, "shear": -270}), "object.shear"), + (4, json!({"ids": [r], "scale": 50, "shear": 400}), "object.shear"), + (5, json!({"ids": [r], "scale": 50, "reflect": "diagonal"}), "object.reflect"), + (6, json!({"ids": [r], "dx": 10, "rotate": 30, "scaleX": 0}), "object.scale"), + ] { + let t = call(&mut s, id, "transform", args.clone()); + assert_eq!(t["isError"], true, "{args}: {t}"); + assert!(text_of(&t).contains(says), "{args}: {t}"); + assert_eq!(doc_json(&mut s), before, "{args}"); + } + // No undo step was recorded: one undo removes the rectangle. + assert_eq!(call(&mut s, 7, "undo", json!({}))["isError"], false); + assert_eq!(count(&mut s), base, "one undo removes the rectangle"); +} + #[test] fn text_effect_pathfinder_transform_graph_and_wrap_tools() { let mut s = server(); diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 1b86095c6e..d730f8deaf 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -466,7 +466,7 @@ pub fn tool_definitions() -> Vec { tool( "transform", "Transform", - "Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy.", + "Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy. A scale, reflect or shear its command refuses returns that error before any step runs, and nothing changes.", obj( json!({ "ids": {"type": "array", "items": {"type": "integer"}}, diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index 717c641e19..381cc93e44 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -292,6 +292,24 @@ pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result { } pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result { + // Each operation is its own command: check the params the later ones refuse before the first + // runs, so a refused request changes nothing. + fn bad(cmd: &'static str) -> impl Fn(String) -> String { + move |e| format!("invalid parameters for `{cmd}`: {e}") + } + let s = a.get("scale").and_then(Value::as_f64); + let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s)); + if sx.is_some() || sy.is_some() { + vectorcraft_engine::cmd::scale_factors(sx.unwrap_or(100.0), sy.unwrap_or(100.0)).map_err(bad("object.scale"))?; + } + let reflect = a.get("reflect").and_then(Value::as_str); + if let Some(axis) = reflect { + vectorcraft_engine::cmd::reflect_axis(Some(&json!(axis))).map_err(bad("object.reflect"))?; + } + let shear = a.get("shear").and_then(Value::as_f64); + if let Some(sh) = shear { + vectorcraft_engine::cmd::shear_tangent(sh).map_err(bad("object.shear"))?; + } select_ids(b, a)?; // With `copy`, the first operation duplicates and the rest transform the copy (the new selection). let copy = std::cell::Cell::new(a.get("copy").and_then(Value::as_bool).unwrap_or(false)); @@ -312,17 +330,15 @@ pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result exec(b, "object.rotate", with(json!({"angle": r})))?; done.push("rotate"); } - let s = a.get("scale").and_then(Value::as_f64); - let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s)); if sx.is_some() || sy.is_some() { exec(b, "object.scale", with(json!({"sx": sx.unwrap_or(100.0), "sy": sy.unwrap_or(100.0)})))?; done.push("scale"); } - if let Some(axis) = a.get("reflect").and_then(Value::as_str) { + if let Some(axis) = reflect { exec(b, "object.reflect", with(json!({"axis": axis})))?; done.push("reflect"); } - if let Some(sh) = a.get("shear").and_then(Value::as_f64) { + if let Some(sh) = shear { exec(b, "object.shear", with(json!({"angle": sh})))?; done.push("shear"); } diff --git a/docs/mcp.md b/docs/mcp.md index f535ab2b28..3a076b314f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -696,7 +696,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `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`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning); `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. | | `apply_effect` | `{effect?, params?, ids?}` | Appends a live effect. Without `effect`, returns the effect catalogue with parameters and defaults. | | `pathfinder` | `{operation, ids?}` | `unite`, `minusFront`, `intersect`, `exclude`, `divide`, `trim`, `merge`, `crop`, `outline`, `minusBack`. For a live version, apply the `pathfinder.*` effect to a group (`effect.apply` groups several loose selected objects first). In remote desktop mode, `run_command` and `invoke_menu` can both call `pathfinder.repeat` with `{}`. Successful panel operations, direct `object.pathfinder.*` commands, and `command.batch` steps (including Actions panel playback) set its history. Repeat applies it to the current selection using current Pathfinder Options. Trap, compound-shape edits, live effects and `action.batch` do not set history. With no history it returns "no Pathfinder operation applied yet". | -| `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. | +| `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. A `scale`, `reflect` or `shear` that its command would refuse returns that error before any step runs; nothing changes and no undo step is recorded. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | | `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | | `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy` and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | From dedc6a543344ba29f9be7608308a67db5f7cbe82 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:24:53 -0800 Subject: [PATCH 18/33] Rerun CI From a83354cd9968c5af775390e24d58d258bc75011d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:43:10 -0800 Subject: [PATCH 19/33] Type: the scatter-brush Document filter test reads through the menu's cache The test keeps one menu state with the Document filter on, so the deletion and its undo have to replace the cached families. --- crates/ui-egui/src/font_menu/tests.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index a2417fa502..415440fcc1 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -1258,8 +1258,11 @@ fn the_document_filter_follows_a_scatter_brushs_edits_and_undo() { let name = app.run("brush.new", serde_json::json!({"type": "scatter", "name": "Type Dots"})).unwrap()["name"].clone(); app.run("edit.clear", serde_json::json!({"ids": [id]})).unwrap(); let db = vectorcraft_text::FontDb::global(); - let families = |app: &crate::VectorcraftApp| { - let mut names: Vec<_> = super::document_families(db, &app.session.active().unwrap().doc).into_iter().collect(); + // One menu state throughout, so each edit has to get past the families it keeps. + let mut st = super::MenuState { document_only: true, ..Default::default() }; + let mut families = |app: &crate::VectorcraftApp| { + let used = super::used_families(db, &mut st, super::MenuLook::of(app)).expect("a document is open"); + let mut names: Vec<_> = used.iter().cloned().collect(); names.sort(); names }; From 46dd113eaa1c70aff4426c5a858c98acffcfd292 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:41:32 -0800 Subject: [PATCH 20/33] EPS import: token and search read a string in place instead of copying it `token` on a string copied everything left in the string before scanning one object, and `search` and `anchorsearch` copied both strings before comparing them. A program that walks a string by what each call leaves copied the rest of it on every call. All three now read the strings in place and release the borrow before the scanned object is checked against the budget and before the results are pushed. Results, errors and the operations charged against the budget are the same as before. Walking a 512 KiB string takes 16 ms instead of 518 ms with `token` and 1.0 ms instead of 27 ms with `search` (release build on Linux under load from other builds, median of 7 alternating runs); on a 4 KiB string the difference is under 0.1 ms. Tests in tests_strings.rs compare each operator with the copying code on the same operands (stack, error and operations left after every call), check that the results see later writes to the string, and check that no string is copied. --- crates/eps/src/import.rs | 2 + crates/eps/src/import/data/ops.rs | 22 +- crates/eps/src/import/interp.rs | 20 +- crates/eps/src/import/obj.rs | 7 +- crates/eps/src/import/tests_strings.rs | 306 +++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 6 files changed, 342 insertions(+), 16 deletions(-) create mode 100644 crates/eps/src/import/tests_strings.rs diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 0d451ec9da..7313b2c7ff 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -70,6 +70,8 @@ mod tests_native; #[cfg(test)] mod tests_reads; #[cfg(test)] +mod tests_strings; +#[cfg(test)] mod tests_type1; #[cfg(test)] mod tests_type42; diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index c4fc09e0b0..cca8bb50ea 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -146,13 +146,21 @@ impl Interp<'_> { fn token(&mut self) -> Res { match self.pop()? { Obj::Str(s) => { - let bytes = s.to_vec(); - let mut lex = Lexer::new(&bytes); - let Some(o) = lex.next()? else { return self.push(Obj::Bool(false)) }; - let o = self.scanned(o, lex.immediate)?; - // The whitespace after the token is read with it. - let used = bytes.len() - lex.data().len(); - self.push_interval(Obj::Str(s), used, bytes.len() - used)?; + // The scanner reads the string in place. The borrow ends before `scanned`, which + // can fail or charge the budget, and before the results are pushed. + let read = { + let bytes = s.borrow(); + let mut lex = Lexer::new(&bytes); + // The whitespace after the token is read with it. + lex.next()?.map(|o| { + let immediate = lex.immediate; + let rest = lex.data().len(); + (o, immediate, bytes.len() - rest, rest) + }) + }; + let Some((o, immediate, used, rest)) = read else { return self.push(Obj::Bool(false)) }; + let o = self.scanned(o, immediate)?; + self.push_interval(Obj::Str(s), used, rest)?; self.push(o)?; } Obj::File { stream: f, .. } => { diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index 43346988ff..8d883a0bff 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -753,21 +753,25 @@ impl<'a> Interp<'a> { } fn search_string(&mut self, op: Op) -> Res { - let seek = self.pop_str()?.to_vec(); + let seek = self.pop_str()?; let s = self.pop_str()?; - let text = s.to_vec(); - self.spend((text.len() / 64) as u64)?; - let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) }; + // Both strings are read in place, and the borrows end before the results are pushed. + let (len, n, at) = { + let (text, seek) = (s.borrow(), seek.borrow()); + self.spend((text.len() / 64) as u64)?; + let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) }; + (text.len(), seek.len(), at) + }; match at { Some(i) => { let o = Obj::Str(s); if op == Op::Search { - self.push_interval(o.clone(), i + seek.len(), text.len() - i - seek.len())?; - self.push_interval(o.clone(), i, seek.len())?; + self.push_interval(o.clone(), i + n, len - i - n)?; + self.push_interval(o.clone(), i, n)?; self.push_interval(o, 0, i)?; } else { - self.push_interval(o.clone(), seek.len(), text.len() - seek.len())?; - self.push_interval(o, 0, seek.len())?; + self.push_interval(o.clone(), n, len - n)?; + self.push_interval(o, 0, n)?; } self.push(Obj::Bool(true))?; } diff --git a/crates/eps/src/import/obj.rs b/crates/eps/src/import/obj.rs index 2b3ae92c73..1fcd41dd85 100644 --- a/crates/eps/src/import/obj.rs +++ b/crates/eps/src/import/obj.rs @@ -49,6 +49,8 @@ thread_local! { /// Tests: the arrays of the list last released on this thread that were still alive after it /// (the ones the interpreter itself still held). pub(crate) static ARRAYS_LEFT: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many values [`Shared::to_vec`] has copied on this thread. + pub(crate) static VALUES_COPIED: std::cell::Cell = const { std::cell::Cell::new(0) }; } thread_local! { @@ -340,7 +342,10 @@ impl Shared { } pub fn to_vec(&self) -> Vec { - self.borrow().to_vec() + let v = self.borrow().to_vec(); + #[cfg(test)] + VALUES_COPIED.with(|n| n.set(n.get() + v.len())); + v } /// `n` values from `at`, sharing the storage (`getinterval`); `None` past the end. diff --git a/crates/eps/src/import/tests_strings.rs b/crates/eps/src/import/tests_strings.rs new file mode 100644 index 0000000000..2a07dafd7c --- /dev/null +++ b/crates/eps/src/import/tests_strings.rs @@ -0,0 +1,306 @@ +//! `token` on a string, `search` and `anchorsearch` (PLRM 3rd ed., pp. 702-703, 655 and 529) read +//! their strings in place. The tests run them next to reference readers that copy the strings +//! first, on the same operands in the same interpreter state: the operand stack, the error and the +//! operations spent must agree. + +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::time::{Duration, Instant}; + +use vectorcraft_doc::Document; +use vectorcraft_geom::{Affine, Rect}; + +use super::graphics::{GState, Out}; +use super::interp::Interp; +use super::lex::Lexer; +use super::obj::{Obj, Op, PsError, Res, Shared, VALUES_COPIED}; + +/// An interpreter that has run `src`, with the operands it left. +fn after(src: &[u8]) -> Interp<'_> { + let mut doc = Document::new(100.0, 100.0); + doc.layers.clear(); + let page = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]); + let mut it = Interp::new(src, GState::default(), Out::new(doc, page, Rect::new(0.0, 0.0, 100.0, 100.0))); + assert_eq!(it.run(), Ok(()), "{}", String::from_utf8_lossy(src)); + it +} + +/// The reference `token`: the string copied before it is scanned. +fn token_by_copy(it: &mut Interp) -> Res { + match it.pop()? { + Obj::Str(s) => { + let bytes = s.to_vec(); + let mut lex = Lexer::new(&bytes); + let Some(o) = lex.next()? else { return it.push(Obj::Bool(false)) }; + let o = it.scanned(o, lex.immediate)?; + let used = bytes.len() - lex.data().len(); + it.push_interval(Obj::Str(s), used, bytes.len() - used)?; + it.push(o)?; + } + Obj::File { stream: f, .. } => { + let (o, immediate) = it.next_in(&f)?; + let Some(o) = o else { return it.push(Obj::Bool(false)) }; + let o = it.scanned(o, immediate)?; + it.push(o)?; + } + _ => return Err(PsError::Ps("typecheck", "token".into())), + } + it.push(Obj::Bool(true)) +} + +/// The reference `search` and `anchorsearch`: both strings copied before they are compared. +fn search_by_copy(it: &mut Interp, op: Op) -> Res { + let seek = it.pop_str()?.to_vec(); + let s = it.pop_str()?; + let text = s.to_vec(); + it.spend((text.len() / 64) as u64)?; + let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) }; + match at { + Some(i) => { + let o = Obj::Str(s); + if op == Op::Search { + it.push_interval(o.clone(), i + seek.len(), text.len() - i - seek.len())?; + it.push_interval(o.clone(), i, seek.len())?; + it.push_interval(o, 0, i)?; + } else { + it.push_interval(o.clone(), seek.len(), text.len() - seek.len())?; + it.push_interval(o, 0, seek.len())?; + } + it.push(Obj::Bool(true))?; + } + None => { + it.push(Obj::Str(s))?; + it.push(Obj::Bool(false))?; + } + } + Ok(()) +} + +fn by_copy(it: &mut Interp, op: Op) -> Res { + if op == Op::Token { token_by_copy(it) } else { search_by_copy(it, op) } +} + +/// The error's name, or the limit reached. +fn outcome(r: Res) -> Result<(), String> { + r.map_err(|e| match e { + PsError::Ps(name, _) => name.to_string(), + e => format!("{e:?}"), + }) +} + +/// Everything the operator left: the operand stack with each string's storage, offset and length, +/// and the operations spent. +fn state(it: &Interp) -> (String, u64) { + (format!("{:?}", it.stack), it.ops_left()) +} + +/// Run `op` on the operands `src` leaves, in place and by copy, `steps` times (a walk that feeds +/// each call the string the last one left), and check that the two agree after every call. +fn agree(src: &str, op: Op, steps: usize) { + let (mut new, mut old) = (after(src.as_bytes()), after(src.as_bytes())); + // `search` and `anchorsearch` look for the same string on each call. + let seeks = [new.stack.last().cloned(), old.stack.last().cloned()]; + for step in 0..steps { + let (a, b) = (outcome(new.op(op)), outcome(by_copy(&mut old, op))); + assert_eq!(a, b, "{src} {op:?}, call {step}"); + assert_eq!(state(&new), state(&old), "{src} {op:?}, call {step}"); + // Keep walking while the operator answered true, with the string it left. + let more = matches!(new.stack.last(), Some(Obj::Bool(true))); + if a.is_err() || !more { + break; + } + for (it, seek) in [&mut new, &mut old].into_iter().zip(&seeks) { + it.stack.pop(); + // `token` leaves the rest under the object; `search` leaves it under match and pre + // (and `anchorsearch` under the match). + let keep = it.stack.len() - if op == Op::Search { 2 } else { 1 }; + it.stack.truncate(keep); + // The string to look for again, or the file `token` reads on from. + if op != Op::Token || matches!(seek, Some(Obj::File { .. })) { + it.stack.extend(seek.clone()); + } + } + } + new.release(); + old.release(); +} + +#[test] +fn token_and_search_agree_with_copying_readers() { + let tokens = [ + "()", + "( )", + "(\r\n\t )", + "(12)", + "(12 34)", + "(12 34)", + "(12\r\n34)", + "(/x {a b} (s) <41> 1.5 x)", + "(1 {)", + "( [ 1 ] )", + "/x 7 def (//x {//x} y)", + "(xx12 34 56) 2 7 getinterval", + "(%comment only)", + "5", + "(12 /x {a}) /ReusableStreamDecode filter", + "currentfile", + ]; + for src in tokens { + agree(src, Op::Token, 16); + } + let searches = [ + "(abcabc) (bc)", + "(abc) (x)", + "(abc) ()", + "() ()", + "() (a)", + "(ab) (abc)", + "(a\nb\nc\n) (\n)", + "/s (aa) def s s", + "(xxab cd ef) 2 8 getinterval ( )", + "(abc) 5", + "5 (abc)", + ]; + for src in searches { + agree(src, Op::Search, 8); + agree(src, Op::AnchorSearch, 8); + } + // Over the operation budget: the same error, with the same operands popped. + let big = "/h 65536 string def h (\\001)"; + let (mut new, mut old) = (after(big.as_bytes()), after(big.as_bytes())); + for it in [&mut new, &mut old] { + let left = it.ops_left(); + assert_eq!(it.spend(left.saturating_sub(10)), Ok(())); + } + let (a, b) = (outcome(new.op(Op::Search)), outcome(by_copy(&mut old, Op::Search))); + assert!(a.as_ref().is_err_and(|e| e.contains("too long")), "{a:?}"); + assert_eq!((a, state(&new)), (b, state(&old))); + new.release(); + old.release(); +} + +/// The results share the string's storage: a write to the string after `token` or `search` shows +/// in what they left. +#[test] +fn token_and_search_results_see_later_writes() { + let check = super::tests::check; + check("/s (12 34) def s token pop pop /post exch def s 3 57 put post token pop exch pop 94 eq"); + check("/s (ab cd) def s ( ) search pop /pre exch def pop /post exch def s 0 120 put s 4 121 put pre (xb) eq post (cy) eq and"); + check("/s (ab cd) def s (ab) anchorsearch pop pop /post exch def s 4 122 put post ( cz) eq"); + check("/s (xx12 34) def s 2 5 getinterval token pop pop /post exch def s 5 57 put post token pop exch pop 94 eq"); +} + +/// `token` on a string, `search` and `anchorsearch` copy neither string. +#[test] +fn token_and_search_copy_no_string() { + for (src, op) in [ + ("(12 34 56 78)", Op::Token), + ("(abc def ghi) ( )", Op::Search), + ("(abc def ghi) (xyz)", Op::Search), + ("(abc def ghi) (abc)", Op::AnchorSearch), + ("(abc def ghi) (def)", Op::AnchorSearch), + ] { + let mut it = after(src.as_bytes()); + VALUES_COPIED.with(|n| n.set(0)); + assert_eq!(it.op(op), Ok(()), "{src} {op:?}"); + assert_eq!(VALUES_COPIED.with(std::cell::Cell::get), 0, "{src} {op:?}"); + it.release(); + } +} + +/// The median of `runs`. +fn median(runs: &[Duration]) -> Duration { + let mut sorted = runs.to_vec(); + sorted.sort(); + sorted.get(sorted.len() / 2).copied().unwrap_or_default() +} + +/// What a walk records of each result: a string's length and first bytes, any other object whole. +fn mark(o: &Obj, h: &mut impl Hasher) { + match o { + Obj::Str(s) => { + s.len().hash(h); + s.borrow().iter().take(16).for_each(|b| b.hash(h)); + } + o => format!("{o:?}").hash(h), + } +} + +/// Walk `data` with `op` and `seek` (none for `token`) until the operator answers false, by copy +/// or in place: how long it took, the calls made, and a hash of every result and of the operations +/// spent. The interpreter is made before the clock starts. +fn walk(data: &[u8], op: Op, seek: Option<&[u8]>, copy: bool) -> (Duration, usize, u64) { + let mut it = after(b""); + it.stack.push(Obj::Str(Shared::new(data.to_vec()))); + let mut calls = 0; + let mut h = DefaultHasher::new(); + let start = Instant::now(); + loop { + if let Some(seek) = seek { + it.stack.push(Obj::Str(Shared::new(seek.to_vec()))); + } + let r = if copy { by_copy(&mut it, op) } else { it.op(op) }; + assert_eq!(r, Ok(())); + calls += 1; + if !matches!(it.stack.pop(), Some(Obj::Bool(true))) { + break; + } + let keep = it.stack.len() - if op == Op::Search { 2 } else { 1 }; + it.stack.iter().for_each(|o| mark(o, &mut h)); + it.stack.truncate(keep); + } + let took = start.elapsed(); + it.stack.iter().for_each(|o| mark(o, &mut h)); + it.ops_left().hash(&mut h); + it.release(); + (took, calls, h.finish()) +} + +/// Time both readers on `data` in 7 runs, alternating which goes first, check that they leave the +/// same, and print every run and the medians. +fn compare(what: &str, data: &[u8], op: Op, seek: Option<&[u8]>) { + let (mut old, mut new) = (vec![], vec![]); + let mut calls = 0; + for run in 0..7 { + let order: [bool; 2] = if run % 2 == 0 { [true, false] } else { [false, true] }; + let mut got = vec![]; + for copy in order { + let (took, n, last) = walk(data, op, seek, copy); + if copy { + old.push(took) + } else { + new.push(took) + } + calls = n; + got.push((n, last)); + } + assert!(got.first() == got.get(1), "{what}: the readers differ"); + } + let ms = |d: &Duration| format!("{:.2}", d.as_secs_f64() * 1000.0); + println!("{what}: {} bytes, {calls} calls", data.len()); + println!(" by copy, ms: {}", old.iter().map(ms).collect::>().join(" ")); + println!(" in place, ms: {}", new.iter().map(ms).collect::>().join(" ")); + let (o, w) = (median(&old), median(&new)); + println!(" median: by copy {} ms, in place {} ms, {:.1}x", ms(&o), ms(&w), o.as_secs_f64() / w.as_secs_f64().max(1e-9)); +} + +/// Times `token` and `search` walking a string by what each call leaves, against the copying +/// reference readers, in one process: strings of 4 KiB, 64 KiB and 512 KiB, of numbers and names +/// for `token` and of 128-byte lines for `search`. Run it in release: +/// `cargo test --release -p vectorcraft-eps --lib tests_strings::string_walks_timed -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn string_walks_timed() { + for kib in [4, 64, 512] { + let size = kib * 1024; + let mut words = Vec::with_capacity(size + 16); + let mut i = 0u32; + while words.len() < size { + let w = if i.is_multiple_of(2) { format!("{} ", i.wrapping_mul(2_654_435_761) % 100_000) } else { format!("/n{i} ") }; + words.extend_from_slice(w.as_bytes()); + i += 1; + } + compare(&format!("token, {kib} KiB"), &words, Op::Token, None); + let lines: Vec = (0..size / 128).flat_map(|i| format!("{:<127}\n", format!("line {i}")).into_bytes()).collect(); + compare(&format!("search, {kib} KiB"), &lines, Op::Search, Some(b"\n")); + } +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..274fc867b6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2155,6 +2155,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Import and export, later 2026-10-13 merges: SVGs that move objects with a CSS transform (`translate(100px, 0)`, `rotate(45deg)`) or style type with the `font` shorthand import as drawn (#1565); SVG symbols whose shapes use percentage lengths import at the size and place they are drawn, the percentages being of the symbol's `viewBox` (#1596); Inkscape's flowed text (`flowRoot`) opens as area type in its rectangle, a paragraph per `flowPara`, instead of being dropped, and a region that can't be read is left out with a warning (#1569, fixes #1568); the warning for an unsupported SVG filter names the filter, its primitives and the object, and says the object is drawn without it (#1599, fixes #1598); the pages of an Inkscape multi-page SVG become artboards, named by their labels (#1603, fixes #1601); SVG export with CSS classes or style entities stays fast in documents with many distinct styles (#1567); PDF and `.ai` import: evenly letter-spaced or tightened type on a path keeps its length along the path instead of closing up to the font's advances (#1586), and type on a path whose stroke is written glyph by glyph comes in as one text object with its stroke, not one object per glyph (#1585); the ICC profiles embedded in JPEG, TIFF and PSD exports have every tag on a 4-byte boundary (ICC.1 §7.1.2), so strict readers accept them (#1589, fixes #1584); GIF, PNG-8 and other indexed exports find each pixel's palette colour through an index instead of a scan, with identical output (#1576); a zero-length subpath draws its round cap as a dot and its projecting cap as a square, so dots in imported `.ai` and SVG files show (#1619, fixes #1613). - Files and untrusted input, 2026-10-14 merges: EPS import: a stitched shading keeps its hard colour changes (#1654, #1653). WMF/EMF import refuses an oversized embedded PNG or JPEG from its header, before any pixels are decoded (#1776). PDF open no longer takes exponential time on a crafted name tree with shared nodes when it looks for the editing data (#1781). The size limits on a native file's embedded data also apply to files read from memory, not only streamed ones (#1783). Saving over a private file on Unix no longer leaves a readable temporary copy beside it while the file is written (#1778). An Export for Screens suffix can no longer place files outside the export folder (#1777). Package refuses a folder where it would overwrite the open document or one of its linked files (#1786). ruzstd 0.9.1 fixes a decompression bomb (RUSTSEC-2026-0344) reachable from EPS/`.ai` and Affinity import (#1807). File Info dates are stamped only after a save succeeds, so a failed save no longer changes them (#1774). Linked files that change during a drag are updated after the drag instead of being missed (#1773). - EPS import: `readhexstring` and `readline` read the data left in a file in one pass instead of one byte per call, with the same bytes, result and next unread byte as before (about nine times less reader time on 6 MB of hex image data and on 8 MB of lines). + - EPS import: `token` on a string, `search` and `anchorsearch` read their strings in place instead of copying the rest of the string on each call, with the same results, errors and operation count as before. Walking a 512 KiB string by what each call leaves takes 16 ms instead of 518 ms with `token` and 1.0 ms instead of 27 ms with `search`, and a 64 KiB string 2.2 ms instead of 10 ms with `token`; on a 4 KiB string the difference is under 0.1 ms (release build on Linux under load from other builds, median of 7 alternating runs, `cargo test --release -p vectorcraft-eps --lib tests_strings::string_walks_timed -- --ignored --nocapture`). - **Fields, search and window, 2026-10-14 merges:** Fields commit what was typed when you click away or move to another field, as Enter does; Escape still discards it (#1787). Up and Down move through the command search results and Enter runs the highlighted one (#1798, #1757). Slider rails show on Medium Dark (#1808, #1662). On Windows the custom title bar's window stays truly borderless, so the pointer lines up with what is drawn on systems where the hidden caption offset it (#1791, #1758; awaiting the reporter's confirmation). - **Tools, panels and type, later 2026-10-14 merges:** the Transform panel's, Properties panel's and Control bar's X, Y, W and H show and edit the bounds of the anchor points selected with Direct Selection, and a whole-object selection is unchanged (#1839, fixes #1824). With Snap to Grid on, anchors and objects snap to the grid even when Snap to Pixel is also ticked: the grid wins (#1840; #1816 stays open until the reporter confirms). A marquee with the Selection or Direct Selection tool also selects the unlocked ruler guides it crosses (#1836). The toolbar shows no group labels by default (a preference brings them back) and runs on in one or two columns; the All Tools drawer lists the tools by flyout group with their shortcuts, has a menu (Reset, Basic, Advanced) and a Show section for the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls (`toolbar.show`, #1751). An action clicked in the Actions panel stays selected, so Play Current Selection and Delete Selection act on it (#1853, part of #1629; editing actions and action shortcuts remain). Redo pressed during a drag keeps the drag as a step instead of losing the redone edit (#1856, #1719). Preferences are written as soon as OK is pressed, so they survive a session that doesn't end with a normal quit (#1857; #1747 stays open until the reporter confirms). New and Redefine Character Style take the format of the selected text range, also while typing (#1634). Type inside symbols, pattern tiles, graph designs and opacity masks gets its layout bounds back when a native file opens, so warped type in a symbol looks the same after save and reopen (#1833, #1738). Editing, renaming, deleting or merging a global swatch reaches the art of opacity masks, and a swatch used only in a mask is no longer listed as unused (#1830, #1735). On macOS, Save As, Save a Copy and the first Save show their sheet again; the Format menu on the sheet (#866) is withdrawn until the format can be set before the sheet opens, and #866 is open again (#1855; #1800, #1831 and #1518 stay open until confirmed on a Mac). - **Files and untrusted input, later 2026-10-14 merges:** SVG import applies style sheet rules with `:not()` selectors, with their nesting bounded (#1799, #1557), no longer stalls on a style sheet with many stacked descendant selectors over deep nesting (#1834, #1703), and reads an SVG's linked files within the automation roots in force again (#1870). DXF export writes the VPORT record's view direction once (group code 36 was written twice, which strict readers reject, #1789). A deeply nested file no longer overflows the stack: nesting is capped at 32 objects (deeper groups are merged with a warning; SVG past 256 elements and PDF past 256 nested arrays are refused), symbols and patterns that use themselves open without the offending instance or paint, and a document nested more than about 40 deep can no longer be saved to a file that won't open again (#1852). PDF and `.ai` files nested deeply inside compressed streams, page trees holding themselves and functions or colour spaces built on themselves no longer crash the app (hayro 0.8; the import runs on a 16 MB thread, #1871); a decompression bomb or impossible predictor parameters are refused (#1873, #1700, #1701); a brush whose art draws the brush again through a symbol or pattern no longer crashes the app, and graph designs, Affinity, DXF, metafiles and plug-ins were probed with hostile input (#1872). Hostile EPS, Affinity and native files can no longer run memory or CPU away through ASCII85 data, PostScript objects holding themselves, flat-colour pixel layers or far and overlapping data offsets (#1863: #1715, #1714, #1704, #1699), and the save fallback for folders that refuse a rename keeps the old file's content until the new one is in (#1695). A file whose ids sit at their largest value no longer breaks new objects (#1718); a failed `command.batch` puts each document back whole, its file, history and a drag in progress included (#1697); a control request that timed out before the app took it never runs later, and the reply says which case it was (#1725, [control-protocol.md](control-protocol.md)); the Eyedropper and recolouring refuse an image too large as RGBA before decoding it (#1717) (all #1862). A save or export that fails is reported in a dialog that names the file and stays until closed, with the document left modified and the old file untouched (#1685); a browser download that can't start fails the save instead of marking it saved (#1693); a file that finishes opening waits while a dialog is open, so Save As options can't save the wrong document (#1694) (all #1865). krilla is built without its text shaping, so the unmaintained rustybuzz and ttf-parser don't ship (#1874, #1730); the CI gate compiles the web app for wasm, and the web's SVG nesting cap (34) follows from its 1 MiB stack (#1875). From 98a0eaab431d9faea8ac3a168cc63c94655f944e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:29:40 -0800 Subject: [PATCH 21/33] Find Font: the document's font list is worked out once per document version While Type > Find Font... is open, the dialog ran text.fonts on every frame, and the missing-font walk on every frame where a folder picker is available. Each walks all of the document's type and resolves its fonts. The dialog now keeps both answers for the active document's uid, the version of its content and the font database's generation, and works them out again only when one of those changes. A new selection keeps them. The list, its counts and statuses, and Find in Folder... are the same as before. With 2,000 point-type objects of 50 characters each, this took a median 1.53 ms of thread CPU time per frame in a release build on Linux; later frames of one version now take about 10 ns. With 20 such objects it took 58 us per frame. --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/caches.rs | 30 ++++ crates/ui-egui/src/find_font.rs | 265 +++++++++++++++++++++++++++++++- docs/target-app-parity.md | 1 + 4 files changed, 291 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index e3d2a13d64..6e42636c5e 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -82,6 +82,7 @@ impl VectorcraftApp { slices: None, print_tiling: None, live_paint_gaps: None, + find_font: None, hidden_chars: Default::default(), spelling: Default::default(), selection_marks: Default::default(), diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 6dc036fcf2..8b73b60634 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -42,6 +42,10 @@ pub struct CanvasCache { pub print_tiling: Option, /// The gap lines View → Show Live Paint Gaps draws for (document uid, revision). pub live_paint_gaps: Option, + /// Type → Find Font's list of the document's fonts and whether the document misses one, for a + /// version of the document's content and of the available fonts: the dialog reads them every + /// frame. + pub find_font: Option, /// The marks Type → Show Hidden Characters drew on each text object in the last frame. A frame /// that does not draw them drops them ([`canvas::show`]). pub hidden_chars: canvas::HiddenChars, @@ -111,6 +115,32 @@ pub type SliceCache = ((u64, u64), std::sync::Arc>); +/// [`CanvasCache::find_font`]: the document's fonts as `text.fonts` lists them, and whether +/// [`vectorcraft_engine::cmd::fontfiles::missing_fonts`] finds any (`None` until it is asked). +#[derive(Clone, Debug)] +pub struct FindFontCache { + /// The document and the content and fonts the answers were worked out from. + pub key: FontsKey, + pub fonts: std::sync::Arc>, + pub missing: Option, +} + +/// A document's uid, a version of its content (compared by identity) and the font database's +/// generation ([`vectorcraft_text::FontDb::generation`]). The weak reference keeps the version's +/// allocation, so a later version is never placed at the same address while the key is kept. +#[derive(Clone, Debug)] +pub struct FontsKey { + pub uid: u64, + pub doc: std::sync::Weak, + pub generation: u64, +} + +impl PartialEq for FontsKey { + fn eq(&self, other: &Self) -> bool { + self.uid == other.uid && self.generation == other.generation && std::sync::Weak::ptr_eq(&self.doc, &other.doc) + } +} + /// [`CanvasCache::pixel_aligned`]: the selected objects' Align to Pixel Grid, on or off when they /// agree and `None` when they differ, with whether every one can be aligned. pub type PixelAligned = (Option, bool); diff --git a/crates/ui-egui/src/find_font.rs b/crates/ui-egui/src/find_font.rs index 6cffc344d1..0ee21574fb 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -4,10 +4,13 @@ //! missing fonts' files, in the Missing Fonts dialog: `ui.findFontsInFolder`). Find In limits Find //! to the active artboard or the selected layers. +use std::sync::Arc; + use egui::Ui; use serde_json::{Value, json}; use crate::VectorcraftApp; +use crate::caches::{FindFontCache, FontsKey}; use crate::state::Dialog; use crate::theme::Tokens; use crate::widgets; @@ -20,7 +23,7 @@ pub fn open(app: &mut VectorcraftApp) { /// Open the dialog on the first font the document misses, to replace it (Missing Fonts' Find /// Fonts). pub fn open_on_missing(app: &mut VectorcraftApp) { - let first = fonts(app).iter().position(|f| matches!(f["status"].as_str(), Some("missing" | "substitute"))); + let first = document_fonts(app, false).0.iter().position(|f| matches!(f["status"].as_str(), Some("missing" | "substitute"))); open_at(app, first.unwrap_or(0)); } @@ -28,7 +31,7 @@ pub fn open_on_missing(app: &mut VectorcraftApp) { /// System's font ([`system_family`]) to change to, and the last Find In choice (Document at first). fn open_at(app: &mut VectorcraftApp, selected: usize) { let find_in = FIND_IN.iter().find(|f| **f == app.ui.find_font_in).copied().unwrap_or("document"); - let used = fonts(app); + let (used, _) = document_fonts(app, false); let source = "system"; let rows = replacement_rows(app, source, &used); let family = system_family(); @@ -252,6 +255,30 @@ fn fonts(app: &mut VectorcraftApp) -> Vec { app.session.execute("text.fonts", &json!({})).ok().and_then(|v| v.as_array().cloned()).unwrap_or_default() } +/// The active document's fonts ([`fonts`]) and, when `missing` is asked for, whether it misses a +/// font ([`vectorcraft_engine::cmd::fontfiles::missing_fonts`]; `false` when it is not asked +/// for). Both are kept in [`crate::CanvasCache::find_font`] and worked out again only for another +/// document, another version of its content or another font generation. No document: no fonts. +fn document_fonts(app: &mut VectorcraftApp, missing: bool) -> (Arc>, bool) { + let Some(st) = app.session.active() else { return (Arc::default(), false) }; + // The generation is read first: fonts loaded while the answers are worked out leave the entry + // under the older generation, so the next frame works them out again. + let key = FontsKey { uid: st.uid, doc: Arc::downgrade(&st.doc), generation: vectorcraft_text::FontDb::global().generation() }; + if app.canvas.find_font.as_ref().is_none_or(|c| c.key != key) { + let fonts = Arc::new(fonts(app)); + app.canvas.find_font = Some(FindFontCache { key, fonts, missing: None }); + } + if missing + && let Some(c) = app.canvas.find_font.as_mut() + && c.missing.is_none() + && let Some(st) = app.session.active() + { + c.missing = Some(!vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty()); + } + let c = app.canvas.find_font.as_ref(); + (c.map(|c| c.fonts.clone()).unwrap_or_default(), missing && c.and_then(|c| c.missing).unwrap_or(false)) +} + pub fn confirm(app: &mut VectorcraftApp) -> Result { if let Some(ctx) = app.ui_ctx.clone() { clear_search(&ctx); @@ -279,10 +306,9 @@ fn change(app: &mut VectorcraftApp, d: &Dialog, from: &Value, all: bool) -> Resu pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(mut d) = app.ui.dialog.clone() else { return }; let t = Tokens::get(ctx); - let list = fonts(app); // Find in Folder… shows when the document misses fonts, fonts used only in its symbols included. - let offer_folder = crate::picks::can(app, &crate::picks::PickRequest::Folder) - && app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty()); + let can_pick = crate::picks::can(app, &crate::picks::PickRequest::Folder); + let (list, offer_folder) = document_fonts(app, can_pick); let mut close = false; let mut find_in_folder = false; let mut act: Option<&str> = None; @@ -416,7 +442,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { match run_button(app, &d, a, from) { // The rows are a snapshot: the document's fonts and the recent fonts have moved on. Ok(_) if a != "find" => { - let used = fonts(app); + let (used, _) = document_fonts(app, false); d.fields.insert("rows".into(), rows_json(&replacement_rows(app, &d.str("replaceFrom"), &used))); } Ok(_) => {} @@ -1421,4 +1447,231 @@ mod tests { let (note, color) = font_note(&row("exact", 2)); assert!(note.contains("2 characters") && color.is_some()); } + + /// The font list the dialog keeps for the active document. + fn kept_list(app: &VectorcraftApp) -> Arc> { + app.canvas.find_font.as_ref().expect("the dialog kept the document's fonts").fonts.clone() + } + + /// The kept list and Find in Folder… are what `text.fonts` and `missing_fonts` give now. + fn assert_current(app: &mut VectorcraftApp, shown: &str, why: &str) { + let listed = fonts(app); + assert_eq!(*kept_list(app), listed, "{why}: the list"); + let missing = app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty()); + let picks = crate::picks::can(app, &crate::picks::PickRequest::Folder); + assert_eq!(shown.contains("Find in Folder…"), picks && missing, "{why}: Find in Folder… {shown}"); + } + + /// A document set in a missing family and in Inter, with a folder picker. + fn missing_font_document() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for (y, font) in [(20, "Missing Family"), (40, "Inter")] { + app.session.execute("text.create", &json!({"x": 10, "y": y, "text": "Hi", "font": font})).unwrap(); + } + app.services.pick_folder = Some(Box::new(|| None)); + app + } + + /// Frames that change nothing in the document, a new selection included, keep the font list + /// and the missing-font answer worked out on the first; the answer is worked out only once a + /// folder picker is there. + #[test] + fn the_font_list_is_worked_out_once_per_document_version() { + let mut app = missing_font_document(); + let picker = app.services.pick_folder.take(); + open(&mut app); + assert!(kept_over_frames(&mut app, "no folder picker"), "frames of one document version keep its list"); + assert_eq!(app.canvas.find_font.as_ref().and_then(|c| c.missing), None, "no picker: the document is not searched for missing fonts"); + app.services.pick_folder = picker; + assert!(kept_over_frames(&mut app, "a folder picker"), "a picker alone keeps the list"); + assert_eq!(app.canvas.find_font.as_ref().and_then(|c| c.missing), Some(true)); + app.run("select.all", json!({})).unwrap(); + assert!(kept_over_frames(&mut app, "a new selection"), "a new selection keeps the list"); + } + + /// Draws frames of the dialog and tells whether they kept the list kept before them. Another + /// test thread that changes the available fonts meanwhile makes the dialog work the list out + /// again, so the frames are drawn again until the fonts stay as they are. + fn kept_over_frames(app: &mut VectorcraftApp, why: &str) -> bool { + for _ in 0..20 { + // The generation the kept list was worked out under: the database's generation only + // counts up, so the same one after the frames means no fonts changed in between. + let before = kept_list(app); + let generation = app.canvas.find_font.as_ref().map(|c| c.key.generation); + let shown = crate::tests_labels::painted_text(app, |app, ui| show(app, ui.ctx())); + assert_current(app, &shown, why); + if Some(vectorcraft_text::FontDb::global().generation()) == generation { + return Arc::ptr_eq(&before, &kept_list(app)); + } + } + panic!("{why}: the available fonts kept changing") + } + + /// An edit, its undo and a Change All each give the list of the document as it is then. + #[test] + fn an_edit_works_the_font_list_out_again() { + let mut app = missing_font_document(); + open(&mut app); + crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + let first = kept_list(&app); + app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Inter"}})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "after the replacement"); + assert!(!shown.contains("Find in Folder…"), "nothing is missing: {shown}"); + assert_eq!(kept_list(&app).len(), 1, "{:?}", kept_list(&app)); + app.run("edit.undo", json!({})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "after the undo"); + assert_eq!(*kept_list(&app), *first, "the undo brings back the first list"); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("family".into(), json!("Source Serif 4")); + d.fields.insert("style".into(), json!("")); + let from = first.iter().find(|f| f["family"] == "Inter").unwrap().clone(); + change(&mut app, &d, &from, true).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "after Change All"); + assert!(kept_list(&app).iter().any(|f| f["family"] == "Source Serif 4"), "{:?}", kept_list(&app)); + } + + /// Fonts that become available, a composite font defined among them, give the list and the + /// missing-font answer as they are with those fonts. + #[test] + fn other_available_fonts_work_the_font_list_out_again() { + const FAMILY: &str = "Find Font Kept List CF"; + let mut app = missing_font_document(); + app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Ab12", "font": FAMILY})).unwrap(); + open(&mut app); + crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + // The same document under another generation of the font database: what is kept for it no + // longer counts. + let entry = app.canvas.find_font.as_mut().unwrap(); + entry.key.generation = u64::MAX; + entry.fonts = Arc::default(); + entry.missing = Some(false); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "another font generation"); + let row = |app: &VectorcraftApp| kept_list(app).iter().find(|f| f["family"] == FAMILY).cloned().unwrap(); + assert_eq!(row(&app)["status"], "missing"); + let generation = vectorcraft_text::FontDb::global().generation(); + let parts = json!({"name": FAMILY, "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "JetBrains Mono"}, "numerals": {"font": "Inter"}}}); + app.run("type.compositeFonts.set", json!({"fonts": [parts]})).unwrap(); + assert_ne!(vectorcraft_text::FontDb::global().generation(), generation, "defining a composite font is a new generation"); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "the composite font defined"); + assert_eq!(row(&app)["status"], "exact"); + app.run("type.compositeFonts.set", json!({"fonts": []})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "the composite font taken out"); + assert_eq!(row(&app)["status"], "missing"); + } + + /// Another document in front, and pattern editing entered and canceled, each give the list of + /// the document in front as it is then. + #[test] + fn the_font_list_follows_the_document_in_front() { + let mut app = missing_font_document(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let id = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Source Serif 4"})).unwrap()["id"].clone(); + app.services.pick_folder = Some(Box::new(|| None)); + open(&mut app); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "the second document"); + app.session.set_active(0); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "the first document"); + assert!(shown.contains("Find in Folder…"), "{shown}"); + app.session.set_active(1); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("object.pattern.make", json!({"name": "Kept List"})).unwrap(); + assert!(app.session.active().unwrap().doc.pattern_edit.is_some(), "pattern editing"); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "pattern editing"); + app.run("object.pattern.cancel", json!({})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "pattern editing canceled"); + } + + /// CPU time of this thread in nanoseconds where the system reports it (Linux), else `None`. + fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() + } + + /// Time the font list and the missing-font answer a Find Font frame reads, for a document of + /// 2,000 point-type objects of 50 characters each and one of 20, set in five installed faces + /// and a missing family, with a folder picker: worked out on every frame as `text.fonts` and + /// `missing_fonts` (each frame before they were kept), on the first frame of a document version + /// ([`document_fonts`] with nothing kept) and on later frames. Per run, the large document + /// draws 120 frames and the small one 12,000 (so the thread's CPU clock, which advances in + /// steps of a few milliseconds, sees them), and later frames number 1,000,000; the sides + /// alternate, and the median time per frame of 7 runs is printed. + /// Run with `cargo test --release -p vectorcraft-ui-egui --lib find_font_list_timing -- --ignored --nocapture`. + #[test] + #[ignore = "manual timing probe; performance depends on machine load"] + fn find_font_list_timing() { + const KEPT: u32 = 1_000_000; + const FACES: [(&str, &str); 6] = [ + ("Inter", "Regular"), + ("Inter", "Medium"), + ("Source Sans 3", "Bold"), + ("Source Serif 4", "Regular"), + ("JetBrains Mono", "Regular"), + ("Missing Family", "Regular"), + ]; + for (objects, frames) in [(2_000, 120), (20, 12_000)] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 2000, "height": 2000})).unwrap(); + for i in 0..objects { + let (family, style) = FACES[i % FACES.len()]; + let text: String = (0..50).map(|c| char::from(b'a' + ((i + c) % 26) as u8)).collect(); + let (x, y) = ((i % 20 * 90) as f64, (i / 20 * 18) as f64 + 20.0); + app.session.execute("text.create", &json!({"x": x, "y": y, "text": text, "font": family, "style": style})).unwrap(); + } + app.services.pick_folder = Some(Box::new(|| None)); + let every_frame = |app: &mut VectorcraftApp| { + let list = fonts(app); + let offer = crate::picks::can(app, &crate::picks::PickRequest::Folder) + && app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty()); + (list, offer) + }; + let expected = every_frame(&mut app); + assert!(expected.1 && expected.0.len() == FACES.len(), "{expected:?}"); + let kept = document_fonts(&mut app, true); + assert_eq!((kept.0.to_vec(), kept.1), expected, "the kept answers are the ones worked out every frame"); + // Each side's answers for one frame: the number of fonts listed and Find in Folder…. + let time = |app: &mut VectorcraftApp, frames: u32, f: &mut dyn FnMut(&mut VectorcraftApp) -> (usize, bool)| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + for _ in 0..frames { + assert_eq!(f(app), (FACES.len(), true)); + } + let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a); + ns as f64 / f64::from(frames) / 1000.0 + }; + let (mut full, mut first, mut later) = (vec![], vec![], vec![]); + for _ in 0..7 { + full.push(time(&mut app, frames, &mut |app| { + let (list, offer) = every_frame(app); + (list.len(), offer) + })); + first.push(time(&mut app, frames, &mut |app| { + app.canvas.find_font = None; + let (list, offer) = document_fonts(app, true); + (list.len(), offer) + })); + later.push(time(&mut app, KEPT, &mut |app| { + let (list, offer) = document_fonts(app, true); + (list.len(), offer) + })); + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" }; + eprintln!("{objects} text objects of 50 characters; {clock} per frame, median of 7 runs"); + eprintln!("worked out every frame ({frames} frames a run): {:>12.3} us {full:.3?}", median(&mut full)); + eprintln!("first frame of a version ({frames} a run): {:>12.3} us {first:.3?}", median(&mut first)); + eprintln!("later frames of the version ({KEPT} a run): {:>12.4} us {later:.4?}", median(&mut later)); + } + } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..c8ea5665e2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1520,6 +1520,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Find Font: Escape and the replacement search:** Escape with the Replace With Font From or Find In list open closes only the list. The dialog stays open with its choices and its search, also while Escape is held down, and the next press of Escape closes it. Done, Enter, Escape, and Find in Folder… once the Missing Fonts dialog opens, each forget the replacement search, so the next Find Font starts with an empty one; with no folder picked, Find Font stays open with its search. This is VectorCraft's own rule: a dropdown or popover open in a dialog closes before the dialog. Tests: `crates/ui-egui/src/find_font.rs`. - **Select Text by Font: scope (a VectorCraft addition, #5529):** `select.font` takes `scope`: `"document"` (the default, as before), `{artboards: [index, …]}` or `{layers: [id, …]}` (sublayers included). On an artboard means what All on Active Artboard takes (the bounds overlap it or the center is on it; one shared test, `select::on_artboard`); hidden and locked text stays out as before; a symbol instance counts where the instance is. Type › Find Font…'s Find In dropdown passes the active artboard or the selected layers (else the current layer). Tests: `crates/engine/src/cmd/fonts.rs`, `crates/ui-egui/src/find_font.rs`, `crates/engine/tests/command_sweep.rs`. - **Find Font: type in opacity masks and pattern swatches:** Type › Find Font…'s Document list (`text.fonts`), Find (`select.font`), Change and Change All (`text.replaceFont`), Replace Missing Fonts (`addon.cleanup.replaceFonts`), the Missing Fonts dialog (`text.missingFonts`), Document Info's Fonts and Font Details for the whole document (`document.info`), File › Package and the export warning about fonts that aren't available include the type in opacity masks (on objects and layers, disabled masks and masks inside mask, symbol or pattern art included) and in the art of pattern swatches, also a swatch that nothing paints with. A pattern's type is listed and changed once, however many objects the pattern paints. Find selects the objects whose mask holds the font, the text whose inline graphics draw a symbol whose art uses it, and the objects painted with a pattern whose art uses it by a visible fill or stroke above 0% opacity (VectorCraft's own rule; a layer's mask and a swatch that nothing paints with select nothing); Change and Change All leave the type in the mask of a hidden or locked object in its font and count it in `skipped`, and Change does the same with the type of a pattern that only hidden or locked selected objects paint with. The help page (https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) says the Document list holds all the fonts the document uses. Tests: `crates/engine/src/cmd/fonts.rs`, `crates/engine/src/cmd/addons/cleanup/text/tests.rs`, `crates/engine/src/cmd/docinfo.rs`. +- **Find Font works out the document's fonts once per version:** while Type › Find Font… is open, its Document list (`text.fonts`) and whether it shows Find in Folder… (the document misses a font) are worked out once for each version of the document's content and of the available fonts, and later frames reuse them. The list and the button are the same as before; an edit, an undo, another document in front, entering or leaving pattern editing, a composite font defined or taken out, and fonts added or scanned again give them anew. With 2,000 point-type objects of 50 characters each, set in five installed faces and a missing family, working them out took a median 1.53 ms of thread CPU time per frame in a release build on Linux; the first frame after a change still takes about as long, and later frames take about 10 ns. With 20 such objects it took 58 µs per frame. Tests: `find_font::tests::the_font_list_is_worked_out_once_per_document_version`, `an_edit_works_the_font_list_out_again`, `other_available_fonts_work_the_font_list_out_again`, `the_font_list_follows_the_document_in_front`; the timing probe is `find_font::tests::find_font_list_timing`. - **Mouse wheel over the font family field (#5253):** In the Character and Properties panels and the Control bar, turning the mouse wheel over the closed font family field applies the next family to the selected type (the previous one when turned up), keeping the style when the family has it, else its closest. Each notch is one undo step; leaving the field or Escape keeps the family, and Undo takes it back. The steps use the font menu's order at the first turn and keep it until the pointer leaves the field or the text selection changes, so recent-font updates do not reshuffle later turns. That order follows the font filters every font menu shares (one chosen in the Glyphs panel's menu or a dialog's applies too) but ignores its search text, puts recent families first, and stops at the first and last family. A turn with a modifier key is left to the panel and the canvas. Behavior reference: the [Illustrator CS6 reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf#page=10) describes editing hovered dropdown controls with the mouse wheel; [Find and apply fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-apply-fonts.html) names the family field's places. Applying it to the font field, the order, the ends and the undo steps are VectorCraft's own rules. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/tests/font_wheel.rs`. - **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 `` 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 back to the tool that was active before type editing began (kept while clicks move editing to other text), or to the Selection tool when there was none (#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). New type, made with the Type tools, `text.create`, `text.createInPath` or by pasting plain text, starts in [Normal Character Style] as every character does by default ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html)), so it is filled black, or with the fill a redefined [Normal Character Style] has (editing that style is how new type's defaults change: [FAQs on fonts in Illustrator](https://helpx.adobe.com/illustrator/using/fonts-faq.html), "How to change the default font"), not with the current fill left from the last shape; a `color` given to the command still wins (#7975). Tests: `new_type_takes_the_normal_character_style_fill_not_the_current_fill`, `pasted_plain_text_takes_the_normal_character_style_fill`. 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}`). Each reference shows an icon of the height it measures before its name, in the open list and in the closed field (#6304): a frame around a letter for Em Box, a bar from the baseline to the top of a capital for Cap Height and of a lowercase x for x-Height, and a frame inset in the em square for ICF Box. 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). From 0602c437dae4456e52eb49ead90311b7c66b4418 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 19:02:15 -0800 Subject: [PATCH 22/33] Color: the Fill and Stroke proxies find the selected objects through the id cache DocState::proxy_mixed, which decides whether the Fill and Stroke proxies show "?", walked every node of the document to find the selected objects, even with one object selected. The Tools panel proxies, the paint chips and the task bar ask for it on every frame whose revision changed, which includes each frame of a drag preview, and new art asks for it after a selection change. Document::nodes_in_order finds every node with one of the given ids in tree order. When the id cache holds each id once at a path that still checks out, it reads the nodes along those paths; otherwise, and for a selection of an eighth of the document or more, it walks the tree once, as before. Unlike Document::index_paths it returns every node with a repeated id, so a damaged file that repeats an id keeps the question marks it had. proxy_mixed now gathers the selected objects through it. Tests compare the result with a copy of the old walk for one object, different fills and strokes, a group, a group with one of its objects, two layers, a hidden object, Appearance items, picked gradient mesh points beside another object, ids not in the document and a repeated id with different paints, with the cache built and dropped, and for 200 random selections. A cost test shows that with one object selected only that object is read and the tree is not walked. Document tests compare nodes_in_order with a walk. The gain shows on large documents. On 50,000 rectangles in 500 groups on 5 layers (release build on Linux, thread CPU time, median of seven alternating runs of both versions in one process; an ignored test, proxy_mixed_timing, times them): Selection old new 1 object 995 us under 5 us 2 objects, different fills 810 us under 5 us a group of 100 875 us 5 us all 500 groups 3,615 us 2,575 us all 50,000 objects 4,075 us 3,470 us --- crates/doc/src/document.rs | 38 +++ crates/doc/src/tests/lookups.rs | 52 +++++ crates/engine/src/cmd/paint.rs | 26 ++- crates/engine/src/cmd/paint/tests.rs | 335 +++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 5 files changed, 442 insertions(+), 10 deletions(-) create mode 100644 crates/engine/src/cmd/paint/tests.rs diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index f4a307cd5c..879216f951 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -423,6 +423,44 @@ impl Document { out } + /// Every node whose id is in `ids`, in tree order (the order of [`Document::walk`]): unlike + /// [`Document::index_paths`], an id that appears more than once (a damaged file) gives every + /// node that has it. When the cache ([`id_index`]) holds each id once, at a path that still + /// checks out, the nodes are found along those paths; otherwise one walk of the tree finds + /// them. As for every cached lookup, a second node given an existing id after the cache was + /// built is not found while the first one's cached path checks out (see [`id_index`]). + pub fn nodes_in_order(&self, ids: impl IntoIterator) -> Vec<&Node> { + let want: std::collections::HashSet> = ids.into_iter().collect(); + // As in `index_paths`, one walk is quicker than checking the cached paths of a good share + // of the document. + if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) { + let mut paths = Vec::with_capacity(want.len()); + let cached = want.iter().all(|id| match cache.get(id) { + Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => { + paths.push(p); + true + } + _ => false, + }); + if cached { + // A node's path sorts after the paths of the nodes before it in tree order, its + // ancestors included. + paths.sort_unstable(); + return paths.iter().filter_map(|p| self.node_at(p)).collect(); + } + } + let mut out = Vec::new(); + if !want.is_empty() { + crate::id_index::note_tree_walk(); + self.walk(|n| { + if want.contains(&n.id) { + out.push(n); + } + }); + } + out + } + /// The node at index path `path` (as [`Document::index_path`] gives it). pub fn node_at(&self, path: &[usize]) -> Option<&Node> { let (first, rest) = path.split_first()?; diff --git a/crates/doc/src/tests/lookups.rs b/crates/doc/src/tests/lookups.rs index 2f83b65c5e..5657dcfc96 100644 --- a/crates/doc/src/tests/lookups.rs +++ b/crates/doc/src/tests/lookups.rs @@ -157,6 +157,58 @@ fn cached_lookups_follow_any_edit_of_the_tree() { } } +/// Every node whose id is in `ids`, by walking the tree. +fn every_node(d: &Document, ids: &[NodeId]) -> Vec<*const Node> { + let mut out = vec![]; + d.walk(|n| { + if ids.contains(&n.id) { + out.push(n as *const Node); + } + }); + out +} + +/// [`Document::nodes_in_order`] gives every node with each id in tree order, repeated ids +/// included, with the cache built and without it, for a few ids (cached paths) and for many (a +/// walk). +#[test] +fn nodes_in_order_match_a_walk() { + for seed in 1..40 { + let (d, ids) = tree(seed); + let few: Vec = ids.iter().copied().step_by(17).collect(); + for cold in [true, false] { + if cold { + d.drop_lookup_cache(); + } else { + d.node(ids[0]); + } + for list in [&ids[..], &few[..], &ids[ids.len() / 2..ids.len() / 2 + 1], &[]] { + let found: Vec<*const Node> = d.nodes_in_order(list.iter().copied()).into_iter().map(|n| n as *const Node).collect(); + assert_eq!(found, every_node(&d, list), "seed {seed}, cold {cold}, {list:?}"); + } + } + // An id that the tree repeats: every node with it. + let Some(dup) = ids.iter().enumerate().find(|(i, id)| ids[..*i].contains(id)).map(|(_, id)| *id) else { continue }; + assert!(d.nodes_in_order([dup]).len() >= 2, "seed {seed}: {dup:?} is in the tree more than once"); + // A second node given an id once held once, after the cache was built: the lookup finds the + // cached node, which has that id; with the cache built afresh, both. + let mut d = d; + let once = ids.iter().copied().find(|id| every_node(&d, &[*id]).len() == 1 && d.node(*id).is_some_and(|n| !n.is_layer())); + let Some(once) = once else { continue }; + d.node(once); + let copy = Arc::new(Node::path(once, shapes::rectangle(Rect::new(0.0, 0.0, 2.0, 2.0)), Appearance::default_art())); + if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() { + ch.insert(0, copy); + } + let found = d.nodes_in_order([once]); + assert!(!found.is_empty() && found.iter().all(|n| n.id == once), "seed {seed}: {once:?}"); + d.drop_lookup_cache(); + d.node(once); + let found: Vec<*const Node> = d.nodes_in_order([once]).into_iter().map(|n| n as *const Node).collect(); + assert_eq!(found, every_node(&d, &[once]), "seed {seed}: {once:?} cached afresh"); + } +} + /// Nodes of `d` picked and ordered by `seed`. None lies inside another, and each of them, and each /// node it is in, appears in the tree once. fn picks(d: &Document, seed: u64) -> Vec { diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 2421b71d77..52db373e9c 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -274,8 +274,9 @@ impl DocState { /// Whether the selected objects' fills and strokes differ as the proxies show them (a "?" /// proxy; a group whose contents differ counts). `item` (the Appearance panel's active item) /// stands for the proxy of its kind, as in [`Session::proxy_paints`]: that fill or stroke of - /// each selected object's own stack is compared. One walk of the document, so callers that ask - /// every frame cache it by revision. + /// each selected object's own stack is compared. The selected objects are found through the id + /// cache ([`vectorcraft_doc::Document::nodes_in_order`]); a large selection takes one walk + /// of the document, so callers that ask every frame cache it by revision. pub fn proxy_mixed(&self, item: Option) -> (bool, bool) { self.proxy_mixed_with(item, &[]) } @@ -290,15 +291,17 @@ impl DocState { if self.selection.symbol_part.is_some() { return (false, false); } - let ids: std::collections::HashSet = self.selection.objects.iter().copied().collect(); - let (mut selected, mut nodes) = (vec![], vec![]); - self.doc.walk(|n| { - if ids.contains(&n.id) { - selected.push(n); - painted(n, true, &mut nodes); - } - }); + // Looking the first object up builds the id cache when there is none. let first = self.selection.objects.first().and_then(|id| self.doc.node(*id)); + let (mut selected, mut nodes) = (vec![], vec![]); + // Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each + // place it appears. + for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) { + #[cfg(test)] + tests::note_gathered(); + selected.push(n); + painted(n, true, &mut nodes); + } let differ = |stroke: bool| { let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke)); let set = if item.is_some() { &selected } else { &nodes }; @@ -1316,3 +1319,6 @@ fn transparency(s: &mut Session, p: &Value) -> Result { } s.execute("object.setProps", &Value::Object(q)) } + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/paint/tests.rs b/crates/engine/src/cmd/paint/tests.rs new file mode 100644 index 0000000000..3da5d73d9e --- /dev/null +++ b/crates/engine/src/cmd/paint/tests.rs @@ -0,0 +1,335 @@ +//! The Fill/Stroke proxies' "?" ([`DocState::proxy_mixed`]) finds the selected objects through the +//! id cache: it answers as a walk of the whole document does, and with a few objects selected it +//! reads only those. + +use std::cell::Cell; +use std::collections::HashSet; +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Rect, shapes}; + +use super::{painted, picked_colors, proxy_paint, same_in_proxy}; +use crate::{DocState, Session}; + +thread_local! { + /// [`gathered`] of this thread. + static GATHERED: Cell = const { Cell::new(0) }; +} + +/// Adds one to [`gathered`]: `proxy_mixed_with` read a node while looking for the selected ones. +pub(super) fn note_gathered() { + GATHERED.set(GATHERED.get() + 1); +} + +/// How many nodes `proxy_mixed_with` has read on this thread while looking for the selected ones. +fn gathered() -> u64 { + GATHERED.get() +} + +/// `proxy_mixed_with` as it was when it found the selected objects by walking the whole document. +fn walked(st: &DocState, item: Option, points: &[(NodeId, Vec)]) -> (bool, bool) { + if st.selection.is_empty() { + return (false, false); + } + if st.selection.symbol_part.is_some() { + return (false, false); + } + let ids: HashSet = st.selection.objects.iter().copied().collect(); + let (mut selected, mut nodes) = (vec![], vec![]); + st.doc.walk(|n| { + if ids.contains(&n.id) { + selected.push(n); + painted(n, true, &mut nodes); + } + }); + let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)); + let differ = |stroke: bool| { + let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke)); + let set = if item.is_some() { &selected } else { &nodes }; + let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) { + c if c.is_empty() => vec![proxy_paint(n, stroke, item)], + c => c.into_iter().map(Paint::solid).collect(), + }); + let Some(p0) = paints.next() else { return false }; + paints.any(|p| !same_in_proxy(&p0, &p)) + }; + (differ(false), differ(true)) +} + +/// `proxy_mixed_with` answers as [`walked`] does for `st`'s selection, for every Appearance item +/// and with and without `points`, with the id cache built and without it. +fn agree(st: &DocState, points: &[(NodeId, Vec)], what: &str) { + for cold in [true, false] { + if cold { + st.doc.drop_lookup_cache(); + } + for item in [None, Some(0), Some(1), Some(2), Some(3)] { + for points in [points, &[]] { + assert_eq!( + st.proxy_mixed_with(item, points), + walked(st, item, points), + "{what}: item {item:?}, {} picked points, cold cache {cold}", + points.len() + ); + } + } + } +} + +fn id_of(v: &serde_json::Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64, fill: &str, stroke: &str) -> NodeId { + let id = id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": fill})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": stroke})).unwrap(); + id +} + +/// Every case of [`DocState::proxy_mixed`]'s rule, each answered as a walk answers it: one object, +/// different fills or strokes, a group with different contents, a group with one of its objects, +/// objects on two layers, a hidden object, an object with two fills under an Appearance item, a +/// gradient mesh with points picked beside another object, ids not in the document and an id that +/// appears twice (a damaged file) with different paints. +#[test] +fn the_question_marks_match_a_walk_of_the_document() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let a = rect(&mut s, 10.0, "#ff0000", "#000000"); + let b = rect(&mut s, 40.0, "#0000ff", "#000000"); + let c = rect(&mut s, 70.0, "#ff0000", "#00ff00"); + // Two fills: [Fill, Stroke, Fill]. + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.setItem", &json!({"index": 2, "color": "#0000ff"})).unwrap(); + let e = rect(&mut s, 100.0, "#ff0000", "#000000"); + let f = rect(&mut s, 130.0, "#00ff00", "#000000"); + let g = id_of(&s.execute("object.group", &json!({"ids": [e.0, f.0]})).unwrap()); + let mesh = rect(&mut s, 160.0, "#ff0000", "#000000"); + s.execute("object.mesh.create", &json!({"ids": [mesh.0], "rows": 2, "cols": 2})).unwrap(); + let hidden = rect(&mut s, 190.0, "#0000ff", "#000000"); + s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap(); + s.execute("layer.new", &json!({})).unwrap(); + let h = rect(&mut s, 220.0, "#ff0000", "#000000"); + let missing = NodeId(999_999); + let Some(NodeKind::Mesh(m)) = s.doc().unwrap().doc.node(mesh).map(|n| &n.kind) else { panic!("a gradient mesh") }; + let (p00, p01, p11) = (m.idx(0, 0), m.idx(0, 1), m.idx(1, 1)); + s.execute("object.mesh.setPointColor", &json!({"id": mesh.0, "index": p00, "color": "#00ff00"})).unwrap(); + let points = vec![(mesh, vec![p00, p01])]; + let points_alike = vec![(mesh, vec![p01, p11])]; + + let selections = [ + vec![a], + vec![a, b], + vec![b, a], + vec![a, h], + vec![g], + vec![g, e], + vec![e, g], + vec![f, e], + vec![c], + vec![c, a], + vec![a, c], + vec![mesh], + vec![mesh, a], + vec![a, mesh, h], + vec![hidden], + vec![hidden, b], + vec![missing], + vec![missing, a], + vec![a, missing, b], + vec![a, a], + ]; + let check = |s: &mut Session, what: &str| { + for sel in &selections { + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + let st = s.active().unwrap(); + agree(st, &points, &format!("{what}: {sel:?}")); + agree(st, &points_alike, &format!("{what}: {sel:?}, alike points")); + } + s.execute("select.all", &json!({})).unwrap(); + agree(s.active().unwrap(), &points, &format!("{what}: Select All")); + }; + check(&mut s, "unique ids"); + + // A second node with a's id and another fill, at the end of the tree. + let st = s.active_mut().unwrap(); + let mut copy = st.doc.node(a).unwrap().clone(); + copy.appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + let doc = Arc::make_mut(&mut st.doc); + let last = doc.layers.len() - 1; + Arc::make_mut(&mut doc.layers[last]).children_mut().unwrap().push(Arc::new(copy)); + doc.drop_lookup_cache(); + check(&mut s, "a repeated id"); + let st = s.active_mut().unwrap(); + st.selection.objects = vec![a]; + assert_eq!(st.proxy_mixed_with(None, &[]), (true, false), "the two places of a's id differ in fill"); +} + +/// A document of `layers` layers, each with `groups` groups of `per_group` rectangles; every other +/// rectangle red, the rest blue. Returns it with the rectangles' ids, in tree order. +fn big(layers: usize, groups: usize, per_group: usize) -> (Document, Vec) { + let mut d = Document::new(612.0, 792.0); + d.layers.clear(); + let mut rects = vec![]; + for l in 0..layers { + let mut layer = Node::layer(d.alloc_id(), &format!("L{l}"), LayerColor::Preset(0)); + for _ in 0..groups { + let children = (0..per_group) + .map(|_| { + let id = d.alloc_id(); + let mut ap = Appearance::default_art(); + let red = rects.len() % 2 == 0; + ap.set_fill(Paint::solid(if red { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) })); + rects.push(id); + Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), ap)) + }) + .collect(); + let group = Node::group(d.alloc_id(), children); + layer.children_mut().unwrap().push(Arc::new(group)); + } + d.layers.push(Arc::new(layer)); + } + (d, rects) +} + +fn state(doc: Document) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 612, "height": 792})).unwrap(); + s.active_mut().unwrap().doc = Arc::new(doc); + s +} + +/// With one object selected, the "?" reads only that object, not every node of the document, and +/// does not walk the tree once the id cache is built; with every object selected it walks the tree +/// once. +#[test] +fn the_question_marks_read_only_the_selected_objects() { + let (doc, rects) = big(2, 40, 25); + let mut s = state(doc); + let st = s.active_mut().unwrap(); + st.selection.objects = vec![rects[777]]; + assert_eq!(st.proxy_mixed(None), (false, false)); + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (false, false)); + assert_eq!(gathered() - read, 1, "only the selected object is read"); + assert_eq!(vectorcraft_doc::tree_walks() - walks, 0, "the cached path answers"); + + st.selection.objects = vec![rects[3], rects[1500]]; + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (true, false)); + assert_eq!((gathered() - read, vectorcraft_doc::tree_walks() - walks), (2, 0)); + + st.selection.objects = rects.clone(); + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (true, false)); + assert_eq!(gathered() - read, rects.len() as u64); + assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection"); +} + +/// Random selections of a document with nested groups answer as a walk does. +#[test] +fn random_selections_match_a_walk_of_the_document() { + let (doc, rects) = big(3, 12, 6); + let mut s = state(doc); + let groups: Vec = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect(); + let layers: Vec = s.active().unwrap().doc.layers.iter().map(|l| l.id).collect(); + let all: Vec = rects.iter().chain(&groups).chain(&layers).copied().chain([NodeId(999_999)]).collect(); + let mut r = 0x2545_f491_4f6c_dd1d_u64; + let mut next = |n: usize| { + r ^= r << 13; + r ^= r >> 7; + r ^= r << 17; + (r % n as u64) as usize + }; + for round in 0..200 { + let count = 1 + next(if round % 10 == 0 { all.len() } else { 6 }); + let sel: Vec = (0..count).map(|_| all[next(all.len())]).collect(); + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + agree(s.active().unwrap(), &[], &format!("round {round}: {sel:?}")); + } +} + +/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere. +fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos) +} + +/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock. +fn time(f: impl FnOnce()) -> std::time::Duration { + match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = std::time::Instant::now(); + f(); + start.elapsed() + } + } +} + +/// The time of `proxy_mixed` against a walk of the document, on 50,000 rectangles in 500 groups on +/// 5 layers: `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing; run by hand"] +fn proxy_mixed_timing() { + let (doc, rects) = big(5, 100, 100); + let mut s = state(doc); + let groups: Vec = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect(); + let cases: [(&str, Vec); 5] = [ + ("1 object", vec![rects[25_000]]), + ("2 objects, different fills", vec![rects[10], rects[40_001]]), + ("a group of 100", vec![groups[250]]), + ("all 500 groups", groups.clone()), + ("all 50,000 objects", rects.clone()), + ]; + const CALLS: usize = 200; + let median = |mut v: Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + println!("proxy_mixed_timing: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + println!("| Selection | Id cache | Walk (µs/call) | Id cache (µs/call) | Runs (walk / id cache, µs) |"); + println!("|---|---|---|---|---|"); + for (name, sel) in &cases { + for cold in [false, true] { + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + let st = s.active().unwrap(); + assert_eq!(st.proxy_mixed_with(None, &[]), walked(st, None, &[]), "{name}"); + let (mut old, mut new) = (vec![], vec![]); + let calls = if cold { CALLS / 10 } else { CALLS }; + for _ in 0..7 { + for (times, use_walk) in [(&mut old, true), (&mut new, false)] { + let d = time(|| { + for _ in 0..calls { + if cold { + st.doc.drop_lookup_cache(); + } + std::hint::black_box(if use_walk { walked(st, None, &[]) } else { st.proxy_mixed_with(None, &[]) }); + } + }); + times.push(d.as_secs_f64() * 1e6 / calls as f64); + } + } + let runs = |v: &[f64]| v.iter().map(|x| format!("{x:.1}")).collect::>().join(" "); + println!( + "| {name} | {} | {:.1} | {:.1} | {} / {} |", + if cold { "dropped before each call" } else { "built" }, + median(old.clone()), + median(new.clone()), + runs(&old), + runs(&new) + ); + } + } +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..d52ac64fa7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1755,6 +1755,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A double-click right of an RGB field switches the Color panel's R, G and B between percent and 0 to 255 ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), Color panel). In VectorCraft the color does not change, Web Safe RGB and the hex field stay in 0 to 255, and the panel keeps the choice between sessions (`ui.colorPanel {rgbPercent}`); the color mixer of the Fill and Stroke chips and the gradient stop dialog follow the same setting. Toggle RGB Percent (`ui.colorRgbPercent`) in the command palette and Keyboard Shortcuts switches the units from the keyboard. Tests: `rgb_percent_switches_the_rgb_fields_between_percent_and_0_to_255`, `rgb_percent_does_not_switch_while_the_rows_are_disabled`, `rgb_percent_comes_back_after_a_restart` and `toggle_rgb_percent_switches_the_units_from_the_keyboard` in `crates/ui-egui/src/panels/color/tests.rs`. View › Proof Setup › Color blindness – Tritanopia-type turns Proof Colors on and proofs the canvas with the tritanopia simulation of Brettel, Viénot and Mollon (1997). The Separations Preview panel's Proof Setup list offers the same target (`view.proofSetup {target: "tritanopia"}`). Grays keep their value. The Separations Preview panel's Gamut Check button reports one color outside the CMYK gamut in the singular and more in the plural, in English and in each language's plural forms (`gamut_check_status_takes_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). + The "?" on the Fill and Stroke proxies finds a few selected objects along their cached places in the document instead of walking every object; a large selection takes one walk, as before. The proxies show the same paints and question marks as before, also for an id that a damaged file repeats. On a document of 50,000 rectangles in 500 groups on 5 layers with one object selected, the check takes under 5 µs of CPU time instead of a median of 995 µs in a release build on Linux, so the gain shows on large documents (seven alternating runs, `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`). - **Document Color Mode outside the layers:** File › Document Color Mode (in one undo step) and `document.open {colorMode}` also convert the colors of graph designs, graphic styles, opacity-mask art, the tile that pattern editing's Cancel puts back and the art of brushes (with a Hue Shift brush's key color); a tint of a global swatch there becomes the converted swatch's color at its tint, as in the art. - **Segments dragged onto the grid (#3835):** with View › Snap to Grid (or Snap to Pixel) on, a straight segment dragged with Direct Selection or Group Selection lands its anchors on the grid, the box round them putting an edge on a gridline on each axis as a moved object's does (Shift keeps the move on its line), instead of the point it was pressed at landing on an intersection and leaving both anchors off the grid; a dragged anchor still lands on an intersection itself, and drawn points and resize handles already snapped (`direct::tests::a_dragged_segment_lands_its_anchors_on_the_grid`). - **Spinner arrows in the shadow and glow dialogs (#5367, #5368):** Drop Shadow's Opacity, X Offset, Y Offset, Blur and Darkness and the Outer and Inner Glow's Opacity and Blur have up and down arrows beside the field, as the other number fields with arrows do: a click steps by one (a unit for distances; Shift ×10, Ctrl/Cmd ÷10), holding repeats, Opacity and Darkness stop at 0 and 100 % and Blur at 0 (`dialogs::effect` test `drop_shadow_and_outer_glow_fields_have_spinner_arrows`). From 90a39f6a127ce7002c2e4b5adda5cb8acc8ee135 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 20:16:52 -0800 Subject: [PATCH 23/33] Rerun CI From 5811cab5231e822b53f3851fef3f16e831c5689d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 20:29:16 -0800 Subject: [PATCH 24/33] Part of #5941: dialogs too large for the window scroll instead of running off the screen A dialog taller than the app window was drawn past the window's edges with no scroll bar. In a 1024 by 480 window, SVG, EPS and DXF Options, Save PDF, Export for Screens, Print, Keyboard Shortcuts and Find Font ran past the top, so their heading and first options could not be seen. Save for Web, Preferences and New Document also ran past the bottom, with their buttons out of reach. - The body of a shared dialog scrolls while the dialog would be taller than the window, and its heading and buttons stay in view. - A dialog window without such a body scrolls as a whole on each axis on which it is taller or wider than the window. Its buttons can then sit below or beside the part in view until it is scrolled. - A dialog that sizes its lists from the window's height (Import Shortcut Set, Character and Paragraph Style Options, the Color Picker) is not scrolled vertically again, but it scrolls sideways when it is wider than the window. - A list with its own scroll bar inside a scrolling body (the Save for Web settings, the Print and Save PDF sections) is no taller than the body shows, so the list and its bar can be scrolled into view whole. - A dialog that closes and opens again starts at its top. A dialog that was only hidden while another opened over it (Keyboard Shortcuts under Import Shortcut Set) keeps where it was scrolled to. - A field being edited keeps its text and focus when a resize makes the dialog start or stop scrolling. - Save for Web in a window narrower than its full layout draws its preview panes narrower, down to 240 pt, so the settings column and the buttons stay in view. Reported by erolkarino in #5941. --- crates/ui-egui/src/dialogs.rs | 13 +- .../ui-egui/src/dialogs/char_style_options.rs | 1 + crates/ui-egui/src/dialogs/color_picker.rs | 1 + crates/ui-egui/src/dialogs/modal.rs | 392 +++++++++++++++++- .../ui-egui/src/dialogs/para_style_options.rs | 1 + crates/ui-egui/src/dialogs/print.rs | 3 +- crates/ui-egui/src/dialogs/save_for_web.rs | 32 +- crates/ui-egui/src/dialogs/save_pdf.rs | 3 +- crates/ui-egui/src/dialogs/shortcut_import.rs | 1 + crates/ui-egui/src/dialogs/tests_print.rs | 8 +- crates/ui-egui/src/dialogs/tests_scroll.rs | 367 ++++++++++++++++ 11 files changed, 786 insertions(+), 36 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/tests_scroll.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index b6a5d26cff..e2514957c9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -831,6 +831,10 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } let focus_first = focus_first && !clicked; let spec = spec(&d.kind); + // Opened over another dialog, which Cancel shows again: that one keeps where it was scrolled to. + if d.fields.get(PARENT).is_some_and(|p| !p.is_null()) { + modal::over_parent(ctx); + } if let Some(window) = spec.window { return window(app, ctx); } @@ -873,14 +877,16 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if focus_first { ui.data_mut(|m| m.insert_temp(widgets::dialog_focus_flag(), true)); } + // When the dialog is taller than the window, its body scrolls, and the heading and the + // buttons stay in view. if let Some(body) = spec.body_with_actions { - match body(app, ui, &mut d) { + match modal::body_rows(ui, |ui| body(app, ui, &mut d)) { DialogAction::None => {} DialogAction::Confirm => ok = true, DialogAction::Cancel => cancel = true, } } else { - cancel = (spec.body)(app, ui, &mut d); + cancel = modal::body_rows(ui, |ui| (spec.body)(app, ui, &mut d)); } // Taken (the flag is gone): done. Still there (the window's measuring frame): next frame. if focus_first && ui.data_mut(|m| m.remove_temp::(widgets::dialog_focus_flag())).is_none() { @@ -1059,6 +1065,9 @@ mod tests_perspective; #[cfg(test)] mod tests_modal; +#[cfg(test)] +mod tests_scroll; + #[cfg(test)] mod tests_rectangular_grid; diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index b4abf8c6e2..c07f7af647 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -1036,6 +1036,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id { /// (as drawn last frame). The section list stays put while the content scrolls. Returns whether /// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`). fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + super::modal::fits_itself(ui); let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height()); let content = ui.ctx().data(|m| m.get_temp::(content_id(ui))).unwrap_or(0.0); let rest = (window - content).max(0.0); diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index bb3a5633ed..d6ebd2241a 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -365,6 +365,7 @@ fn header(ui: &mut Ui, title: &str) { /// Draws the responsive picker and updates its color fields and live preview. /// Returns the requested action for the shared frame to confirm or cancel. fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { + super::modal::fits_itself(ui); let channel = Channel::parse(&d.str("channel")).unwrap_or_default(); let web = d.bool("webOnly"); let swatches = d.bool("swatches"); diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index f72383068e..582bd65a0d 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -2,8 +2,9 @@ //! window with no title bar that opens centred and moves by dragging its heading (the band from its //! top edge down to the heading), as a title bar would, showing the arrow until it is dragged. Where //! it was moved to stays, per window, for the session, and the window never leaves the screen. Rows -//! too many for the screen's height scroll inside it ([`scrolled_rows`]), so its heading and buttons -//! stay in view. +//! too many for the screen's height scroll inside it ([`scrolled_rows`], [`body_rows`]), so its +//! heading and buttons stay in view. A window without such rows that is still too tall or too wide +//! for the screen scrolls as a whole on that axis. use egui::{Id, Rect, Vec2}; @@ -33,11 +34,89 @@ pub(crate) fn show_at(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 .title_bar(false) .anchor(egui::Align2::CENTER_CENTER, offset(ctx, id, initial)) .frame(egui::Frame::window(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(margin))) - .show(ctx, add)?; - keep_rest(ctx, id, shown.response.rect.height()); + .show(ctx, |ui| { + // Just opened: what scrolls in the window starts at its top, wherever it was left when + // the window last closed. + if opened(ctx, id) { + ctx.data_mut(|m| { + m.insert_temp(id.with(TOP_ROWS_KEY), true); + m.insert_temp(id.with(TOP_WHOLE_KEY), true); + }); + } + // A window whose contents are wider than the screen has room for, or taller without + // rows that scroll ([`scrolled_rows`], [`body_rows`]), scrolls as a whole on that axis, + // so none of it is out of reach. The contents keep their ids whether the window scrolls + // or not, so a field being edited keeps its text when that changes. + let [wide, tall] = ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default(); + let scope = egui::UiBuilder::new().scope_id(id.with("modal-contents")); + let (r, contents) = if wide || tall { + let room = whole_room(ctx, margin); + let mut area = egui::ScrollArea::new([wide, tall]); + if ctx.data_mut(|m| m.remove_temp::(id.with(TOP_WHOLE_KEY))).is_some() { + area = area.scroll_offset(Vec2::ZERO); + } + let out = area + .id_salt("modal-whole") + .max_width(room.x) + .max_height(room.y) + .min_scrolled_width(room.x) + .min_scrolled_height(room.y) + .show(ui, |ui| ui.scope_builder(scope, add).inner); + (out.inner, out.content_size) + } else { + let r = ui.scope_builder(scope, add).inner; + (r, ui.min_rect().size()) + }; + ctx.data_mut(|m| m.insert_temp(id.with(CONTENTS_KEY), contents)); + r + })?; + keep_rest(ctx, id, shown.response.rect.height(), margin); shown.inner } +/// Mark the modal window drawn next in this pass as opened over the one drawn in the pass before, +/// which it hides until it closes and shows that one again (Import Shortcut Set over Keyboard +/// Shortcuts). The window under it keeps where it was scrolled to. +pub(crate) fn over_parent(ctx: &egui::Context) { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|m| m.insert_temp(Id::unique(OVER_KEY), pass)); +} + +/// Whether modal window `id`, drawn in this pass, opened in it: it was not drawn in the pass before, +/// and the window drawn in the pass before was not one opened over it ([`over_parent`]). +fn opened(ctx: &egui::Context, id: Id) -> bool { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|m| { + // The window drawn in the pass before, if another. + let before = + m.get_temp::<(u64, Id)>(Id::unique(LAST_KEY)).filter(|&(at, other)| other != id && at.saturating_add(1) == pass).map(|(_, other)| other); + m.insert_temp(Id::unique(LAST_KEY), (pass, id)); + let last = std::mem::replace(m.get_temp_mut_or(id.with(SHOWN_KEY), u64::MAX), pass); + if last != u64::MAX && last.saturating_add(1) >= pass { + return false; + } + // Shown again as the window opened over it closed. + if before.is_some_and(|over| m.get_temp::(over.with(HOLDS_KEY)) == Some(id)) { + return false; + } + // Opened over the window drawn in the pass before, it holds that one; otherwise none. + match before.filter(|_| m.get_temp::(Id::unique(OVER_KEY)) == Some(pass)) { + Some(under) => { + m.insert_temp(id.with(HOLDS_KEY), under); + } + None => { + m.remove::(id.with(HOLDS_KEY)); + } + } + true + }) +} + +/// The room for the contents of a modal window with `margin` inside its frame. +fn whole_room(ctx: &egui::Context, margin: i8) -> Vec2 { + (ctx.content_rect().size() - Vec2::splat(2.0 * (super::EDGE_GAP + f32::from(margin)))).max(Vec2::ZERO) +} + /// The layer of the backdrop behind a modal dialog window, which takes the clicks the rest of /// the app would get. pub(crate) fn backdrop() -> egui::LayerId { @@ -73,34 +152,157 @@ pub(super) fn handle(id: Id) -> Id { id.with("modal-drag") } -/// Under a modal window's id: how tall its [`scrolled_rows`] were drawn this frame, and how tall -/// the rest of it was when last drawn. +/// Under a modal window's id: how tall its [`scrolled_rows`] (or [`body_rows`]) were drawn this +/// frame, and how tall the rest of it was when last drawn. const ROWS_KEY: &str = "modal-rows"; const REST_KEY: &str = "modal-rest"; +/// Under a modal window's id: its contents drew [`scrolled_rows`] of their own or fit themselves to +/// the screen ([`fits_itself`]) this frame (`OWN_ROWS_KEY`), or last frame (`OWN_BEFORE_KEY`). +const OWN_ROWS_KEY: &str = "modal-own-rows"; +const OWN_BEFORE_KEY: &str = "modal-own-before"; +/// Under a modal window's id: how tall its [`body_rows`] would be without scrolling, this frame. +const BODY_KEY: &str = "modal-body"; +/// Under a modal window's id: how large its contents would be without scrolling as a whole, this +/// frame. +const CONTENTS_KEY: &str = "modal-contents"; +/// Under a modal window's id, for the next frame: its [`body_rows`] scroll (`TALL_KEY`), and on +/// which axes ([wide, tall]) it scrolls as a whole (`WHOLE_KEY`). +const TALL_KEY: &str = "modal-tall"; +const WHOLE_KEY: &str = "modal-whole"; +/// Under a modal window's id: the pass it was last drawn in (`SHOWN_KEY`), and, since it opened, +/// its rows (`TOP_ROWS_KEY`) or the window as a whole (`TOP_WHOLE_KEY`) have not scrolled yet, so +/// they start at the top when they first do. +const SHOWN_KEY: &str = "modal-shown"; +const TOP_ROWS_KEY: &str = "modal-top-rows"; +const TOP_WHOLE_KEY: &str = "modal-top-whole"; +/// For all modal windows: the pass the last one was drawn in and its id (`LAST_KEY`), and the pass +/// in which the window drawn next was marked as opened over another ([`over_parent`], `OVER_KEY`). +/// Under a modal window's id: the window it was opened over and hides (`HOLDS_KEY`). +const LAST_KEY: &str = "modal-last"; +const OVER_KEY: &str = "modal-over"; +const HOLDS_KEY: &str = "modal-holds"; /// Rows of the modal window `ui` is in (one list of them per window) that scroll if the window /// would be taller than the screen. Their height is the screen's less the rest of the window as /// last drawn (a frame late, as only the drawn window knows its height). /// Rows that fit are as tall as they are. pub(crate) fn scrolled_rows(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, add: impl FnOnce(&mut egui::Ui) -> R) -> R { - let id = ui.layer_id().id; - let rest = ui.ctx().data(|m| m.get_temp::(id.with(REST_KEY))).unwrap_or(0.0); - let room = (ui.ctx().content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0); - // As tall as the room at once: by itself a scroll area grows a frame at a time with the window. - let rows = ui.scope(|ui| egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room).show(ui, add).inner); - ui.ctx().data_mut(|m| m.insert_temp(id.with(ROWS_KEY), rows.response.rect.height())); - rows.inner + fits_itself(ui); + let (r, drawn, _) = rows(ui, salt, true, add); + ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(ROWS_KEY), drawn)); + r } -/// After modal window `id` is drawn `height` tall: keep the height of all of it but its -/// [`scrolled_rows`] for the next frame. If the rows were sized by a different one (the window just -/// opened, or what is around them changed), the next frame is drawn at once, for the rows to fit -/// without waiting for input. -fn keep_rest(ctx: &egui::Context, id: Id, height: f32) { - let Some(rows) = ctx.data_mut(|m| m.remove_temp::(id.with(ROWS_KEY))) else { return }; - let rest = (height - rows).max(0.0); - let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest)); - if (used - rest).abs() > 0.5 { +/// Mark the contents of the modal window `ui` is in as fitting themselves to the screen (sizing +/// what scrolls in them from the screen's height), so neither [`body_rows`] nor the window +/// scroll them again. +pub(crate) fn fits_itself(ui: &egui::Ui) { + ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(OWN_ROWS_KEY), true)); +} + +/// The body of a shared dialog window. While the window would be taller than the screen has room +/// for, the body scrolls as [`scrolled_rows`] do, so the heading and the buttons stay in view; +/// otherwise it is drawn as it is. A body that fits itself ([`fits_itself`]) is drawn as it is. +pub(crate) fn body_rows(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + let id = ui.layer_id().id; + let (r, drawn, body) = rows(ui, "dialog-body", body_scrolls(ui.ctx(), id), add); + if !ui.ctx().data(|m| m.get_temp::(id.with(OWN_ROWS_KEY))).unwrap_or(false) { + ui.ctx().data_mut(|m| { + m.insert_temp(id.with(ROWS_KEY), drawn); + m.insert_temp(id.with(BODY_KEY), body); + }); + } + r +} + +/// Whether the [`body_rows`] of modal window `id` scroll in this frame. +fn body_scrolls(ctx: &egui::Context, id: Id) -> bool { + let own = ctx.data(|m| m.get_temp::(id.with(OWN_BEFORE_KEY))).unwrap_or(false); + !own && ctx.data(|m| m.get_temp::(id.with(TALL_KEY))).unwrap_or(false) +} + +/// While the [`body_rows`] of the modal window `ui` is in scroll: how tall they are drawn. +pub(crate) fn body_view(ui: &egui::Ui) -> Option { + let id = ui.layer_id().id; + body_scrolls(ui.ctx(), id).then(|| rows_room(ui.ctx(), id)) +} + +/// How modal window `id` scrolls: while its [`body_rows`] scroll, how tall they are drawn; and on +/// which axes ([wide, tall]) the window scrolls as a whole. +#[cfg(test)] +pub(crate) fn scrolling(ctx: &egui::Context, id: Id) -> (Option, [bool; 2]) { + let body = body_scrolls(ctx, id).then(|| rows_room(ctx, id)); + (body, ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default()) +} + +/// The height of a list `height` tall at most, with a scroll bar of its own, in the [`body_rows`] +/// of the modal window `ui` is in: while the body scrolls, no taller than the body is drawn, so +/// the list and its bar can be scrolled into view whole. +pub(crate) fn list_height(ui: &egui::Ui, height: f32) -> f32 { + body_view(ui).map_or(height, |view| view.min(height)) +} + +/// The height rows that scroll in modal window `id` are drawn: the screen's less the rest of the +/// window as last drawn. +fn rows_room(ctx: &egui::Context, id: Id) -> f32 { + let rest = ctx.data(|m| m.get_temp::(id.with(REST_KEY))).unwrap_or(0.0); + (ctx.content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0) +} + +/// [`scrolled_rows`] without marking the window's body as having rows of its own or keeping their +/// height. Also returns how tall the rows were drawn and how tall they would be without scrolling. +/// Rows that do not `scroll` are as tall as they are, with no +/// scroll area (which would take the scroll requests of their fields from the window's). The rows +/// keep their ids either way, so a field being edited keeps its text when they start or stop +/// scrolling. +fn rows(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, scroll: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> (R, f32, f32) { + let id = ui.layer_id().id; + let room = rows_room(ui.ctx(), id); + let scope = egui::UiBuilder::new().scope_id(ui.make_persistent_id(&salt).with("modal-rows")); + if !scroll { + let rows = ui.scope_builder(scope, add); + let height = rows.response.rect.height(); + return (rows.inner, height, height); + } + // As tall as the room at once: by itself a scroll area grows a frame at a time with the window. + let mut area = egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room); + if ui.ctx().data_mut(|m| m.remove_temp::(id.with(TOP_ROWS_KEY))).is_some() { + area = area.scroll_offset(Vec2::ZERO); + } + let rows = ui.scope(|ui| area.show(ui, |ui| ui.scope_builder(scope, add).inner)); + (rows.inner.inner, rows.response.rect.height(), rows.inner.content_size.y) +} + +/// After modal window `id` (with `margin` inside its frame) is drawn `height` tall: keep the height +/// of all of it but its [`scrolled_rows`] for the next frame. If the rows were sized by a different +/// one (the window just opened, or what is around them changed), the next frame is drawn at once, +/// for the rows to fit without waiting for input. From the next frame on, [`body_rows`] scroll +/// while the window would be taller than the screen has room for without them scrolling; a window +/// without rows that scroll scrolls as a whole while its contents would be taller than the room, +/// and any window scrolls sideways while its contents would be wider. +fn keep_rest(ctx: &egui::Context, id: Id, height: f32, margin: i8) { + let rows = ctx.data_mut(|m| m.remove_temp::(id.with(ROWS_KEY))); + let body = ctx.data_mut(|m| m.remove_temp::(id.with(BODY_KEY))); + let contents = ctx.data_mut(|m| m.remove_temp::(id.with(CONTENTS_KEY))).unwrap_or_default(); + let own = ctx.data_mut(|m| m.remove_temp::(id.with(OWN_ROWS_KEY))).unwrap_or(false); + ctx.data_mut(|m| m.insert_temp(id.with(OWN_BEFORE_KEY), own)); + let room = whole_room(ctx, margin); + let screen = ctx.content_rect().height() - 2.0 * super::EDGE_GAP; + let tall = match (rows, body) { + (Some(rows), Some(body)) if !own => height - rows + body > screen + 0.5, + _ => false, + }; + // A window that fits itself to the screen's height can still be too wide for it. + let whole = [contents.x > room.x + 0.5, !own && rows.is_none() && contents.y > room.y + 0.5]; + let was_tall = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(TALL_KEY), false), tall)); + let was_whole = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(WHOLE_KEY), [false; 2]), whole)); + let mut repaint = tall != was_tall || whole != was_whole; + if let Some(rows) = rows { + let rest = (height - rows).max(0.0); + let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest)); + repaint |= (used - rest).abs() > 0.5; + } + if repaint { ctx.request_repaint(); } } @@ -146,4 +348,150 @@ mod tests { // Larger than the screen: its top left stays in view. assert_eq!(on_screen(r(-10.0, -10.0, 900.0, 700.0), screen), r(0.0, 0.0, 900.0, 700.0)); } + + /// Draw `frames` frames of a 400×300 screen from `time`, the first with `events`, with the modal + /// window named `open` open, if any: a heading and 60 rows, in [`scrolled_rows`] when + /// `in_rows`. A window named "over …" is opened over the one before it ([`over_parent`]). + /// Returns whether a first row could be seen in the last frame (inside the screen and its clip). + fn first_row_seen(ctx: &egui::Context, open: Option<&str>, in_rows: bool, events: Vec, time: &mut f64, frames: usize) -> bool { + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 300.0)); + let add = |ui: &mut egui::Ui| { + for i in 0..60 { + ui.label(format!("Row {i}")); + } + }; + let mut events = Some(events); + let mut seen = false; + for _ in 0..frames { + *time += 1.0 / 60.0; + let input = + egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(*time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + if let Some(name) = open { + if name.starts_with("over ") { + over_parent(ui.ctx()); + } + show(ui.ctx(), name, Id::unique(("modal-reopen-test", name)), 0.0, 8, |ui| { + heading(ui, "Top"); + if in_rows { + scrolled_rows(ui, "rows", add); + } else { + add(ui); + } + }); + } + }); + out.textures_delta.clear(); + seen = out.shapes.iter().any(|c| match &c.shape { + egui::Shape::Text(t) => { + let r = t.visual_bounding_rect(); + t.galley.text() == "Row 0" && screen.contains_rect(r) && c.clip_rect.contains_rect(r) + } + _ => false, + }); + } + seen + } + + /// A wheel turn far down, at the middle of the 400×300 screen. + fn wheel_down() -> Vec { + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -3000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + vec![egui::Event::PointerMoved(egui::pos2(200.0, 200.0)), wheel] + } + + #[test] + fn a_window_that_scrolled_opens_again_at_its_top() { + for in_rows in [false, true] { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let mut time = 0.0; + assert!(first_row_seen(&ctx, Some("A"), in_rows, vec![], &mut time, 4), "rows {in_rows}: the window opens at its top"); + assert!(!first_row_seen(&ctx, Some("A"), in_rows, wheel_down(), &mut time, 60), "rows {in_rows}: the wheel scrolls the first row away"); + first_row_seen(&ctx, None, in_rows, vec![], &mut time, 2); + assert!(first_row_seen(&ctx, Some("A"), in_rows, vec![], &mut time, 4), "rows {in_rows}: opened again, the window starts at its top"); + } + } + + #[test] + fn a_window_hidden_under_one_opened_over_it_keeps_its_scroll() { + // As Keyboard Shortcuts is while Import Shortcut Set is open over it: it is not drawn, but it + // did not close. A window that another replaced did close. + let mut wrong = vec![]; + for in_rows in [false, true] { + for (other, kept) in [("over B", true), ("C", false)] { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let mut time = 0.0; + first_row_seen(&ctx, Some("A"), in_rows, vec![], &mut time, 4); + if first_row_seen(&ctx, Some("A"), in_rows, wheel_down(), &mut time, 60) { + wrong.push(format!("rows {in_rows}: the wheel does not scroll A")); + } + if !first_row_seen(&ctx, Some(other), in_rows, vec![], &mut time, 4) { + wrong.push(format!("rows {in_rows}: {other} does not open at its top")); + } + if first_row_seen(&ctx, Some("A"), in_rows, vec![], &mut time, 4) == kept { + wrong.push(format!("rows {in_rows}: after {other}, A {} where it was scrolled to", if kept { "is not" } else { "is still" })); + } + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + } + + #[test] + fn a_field_keeps_its_text_and_focus_when_the_window_starts_or_stops_scrolling() { + // A field's edit state and the keyboard focus are kept under its id, so typing goes on into + // the same field when the screen's height changes whether the body or the window scrolls. + let mut wrong = vec![]; + for in_body in [false, true] { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let window = Id::unique("modal-field-id-test"); + let mut text = String::from("12"); + let mut time = 0.0; + let mut field = None; + let mut seen = vec![]; + for (height, typed) in [(900.0, "3"), (300.0, "4"), (900.0, "5")] { + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, height)); + for i in 0..4 { + time += 1.0 / 60.0; + // Typed once the window has settled at this height. + let events = if i == 3 { vec![egui::Event::Text(typed.into())] } else { vec![] }; + let input = egui::RawInput { screen_rect: Some(screen), events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + show(ui.ctx(), "Test", window, 0.0, 8, |ui| { + heading(ui, "Top"); + let mut add = |ui: &mut egui::Ui| { + let r = ui.text_edit_singleline(&mut text); + for i in 0..30 { + ui.label(format!("Row {i}")); + } + r.id + }; + field = Some(if in_body { body_rows(ui, add) } else { add(ui) }); + }); + }); + out.textures_delta.clear(); + if let Some(id) = field.filter(|_| ctx.memory(|m| m.focused()).is_none()) { + ctx.memory_mut(|m| m.request_focus(id)); + } + } + let key = if in_body { window.with(TALL_KEY) } else { window.with(WHOLE_KEY) }; + let scrolls = ctx.data(|m| m.get_temp::(key).unwrap_or(false) || m.get_temp::<[bool; 2]>(key).is_some_and(|a| a[1])); + seen.push((scrolls, text.clone(), ctx.memory(|m| m.focused()) == field && field.is_some())); + } + let want = [(false, "123", true), (true, "1234", true), (false, "12345", true)]; + let want: Vec<_> = want.iter().map(|&(s, t, f)| (s, t.to_string(), f)).collect(); + if seen != want { + wrong.push((in_body, seen)); + } + } + // Only the short screen scrolls, and the field keeps its focus and takes each key. + assert_eq!(wrong, vec![], "(body, [(scrolls, text, focused)]) that went wrong"); + } } diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index 9a9da0c164..b64815b8dd 100644 --- a/crates/ui-egui/src/dialogs/para_style_options.rs +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -982,6 +982,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id { /// (as drawn last frame). The section list stays put while the content scrolls. Returns whether /// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`). fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + super::modal::fits_itself(ui); let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height()); let content = ui.ctx().data(|m| m.get_temp::(content_id(ui))).unwrap_or(0.0); let rest = (window - content).max(0.0); diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index ebaad1749a..dd8db94418 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -251,7 +251,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.vertical(|ui| { ui.set_width(500.0); ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong)); - egui::ScrollArea::vertical().id_salt(("print", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section { + let list_h = super::modal::list_height(ui, 360.0); + egui::ScrollArea::vertical().id_salt(("print", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section { "Marks and Bleed" => super::save_pdf::marks_and_bleeds(app, ui, d), "Output" => output(ui, d, &preview), "Graphics" => graphics(ui, d), diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 589d1dfdce..a214dc108a 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -52,6 +52,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// The preview area (panes and their captions) and the settings column. const PREVIEW_W: f32 = 620.0; +/// The narrowest the panes get in a narrow window. +const MIN_PREVIEW_W: f32 = 240.0; const PREVIEW_H: f32 = 470.0; const SIDE_W: f32 = 296.0; const GAP: f32 = 16.0; @@ -532,10 +534,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } let settings = settings_of(app, d); let mut browser = false; - ui.horizontal_top(|ui| { + // In a window too narrow for both, the panes are narrower, so the settings beside them and the + // buttons below stay in view. The room is the screen's (the window's own width follows what it + // drew last), less a column for the bar of the body while it scrolls; the settings column is as + // wide as it was drawn last. + let bar = if super::modal::body_view(ui).is_some() { ui.spacing().scroll.allocated_width() } else { 0.0 }; + let room = ui.ctx().content_rect().width() - 2.0 * (f32::from(super::MARGIN) + super::EDGE_GAP) - bar; + let rest_id = egui::Id::unique("save-for-web-beside-panes"); + let rest = ui.ctx().data(|m| m.get_temp::(rest_id)).unwrap_or(ui.spacing().item_spacing.x + GAP + SIDE_W); + let preview_w = (room.min(ui.available_width()) - rest).clamp(MIN_PREVIEW_W, PREVIEW_W); + let row = ui.horizontal_top(|ui| { ui.vertical(|ui| { - ui.set_width(PREVIEW_W); - browser = preview_area(app, ui, d, &settings); + ui.set_width(preview_w); + browser = preview_area(app, ui, d, &settings, preview_w); }); ui.add_space(GAP); ui.vertical(|ui| { @@ -543,6 +554,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { side(app, ui, d, settings.as_ref().ok()); }); }); + let drawn = row.response.rect.width() - preview_w; + if (ui.ctx().data_mut(|m| std::mem::replace(m.get_temp_mut_or(rest_id, rest), drawn)) - drawn).abs() > 0.5 { + ui.ctx().request_repaint(); + } optimize_on_enter(ui.ctx(), d); if browser && let Err(e) = app.run("file.saveForWeb.browser", params(d)) { app.status(e); @@ -550,16 +565,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// The view tabs, the panes and the zoom and speed row. Returns whether Preview in Browser was -/// clicked. -fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result) -> bool { +/// The view tabs, the panes (`width` wide) and the zoom and speed row. Returns whether Preview in +/// Browser was clicked. +fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result, width: f32) -> bool { let t = Tokens::get(ui.ctx()); let view = VIEWS.iter().position(|v| *v == d.str("__view")).unwrap_or(2); if let Some(i) = widgets::tab_bar(ui, &VIEW_LABELS, view) { d.fields.insert("__view".into(), json!(VIEWS[i])); } ui.add_space(4.0); - let (area, resp) = ui.allocate_exact_size(egui::vec2(PREVIEW_W, PREVIEW_H), egui::Sense::click_and_drag()); + let (area, resp) = ui.allocate_exact_size(egui::vec2(width, PREVIEW_H), egui::Sense::click_and_drag()); let pan_id = egui::Id::unique("save-for-web-pan"); let mut pan: egui::Vec2 = ui.ctx().data(|m| m.get_temp(pan_id)).unwrap_or_default(); if resp.dragged() { @@ -729,7 +744,8 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<& presets_row(app, ui, d, s); optimize_rows(ui, d, s, &art_key(app)); widgets::divider(ui); - egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(PREVIEW_H - 40.0).auto_shrink([false, true]).show(ui, |ui| { + let list_h = super::modal::list_height(ui, PREVIEW_H - 40.0); + egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(list_h).auto_shrink([false, true]).show(ui, |ui| { let choice = |ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, options: &[(&str, &str)]| { form::choice(ui, d, key, label, (LABEL_W, FIELD_W), options); }; diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index f76dcc164b..fce6b9b453 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -408,7 +408,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.vertical(|ui| { ui.set_width(500.0); ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong)); - egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section { + let list_h = super::modal::list_height(ui, 360.0); + egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section { "Compression" => compression(ui, d), "Marks and Bleeds" => marks_and_bleeds(app, ui, d), "Output" => output(ui, d), diff --git a/crates/ui-egui/src/dialogs/shortcut_import.rs b/crates/ui-egui/src/dialogs/shortcut_import.rs index 0516695233..e6c9a6ee0a 100644 --- a/crates/ui-egui/src/dialogs/shortcut_import.rs +++ b/crates/ui-egui/src/dialogs/shortcut_import.rs @@ -670,6 +670,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let (keys_h, rows_h) = list_heights(ctx.content_rect().height() - rest, keys_open); let (mut apply, mut cancel, mut copy, mut lists) = (false, false, false, 0.0); crate::dialogs::modal::show(ctx, tl!("Import Shortcut Set"), id, -20.0, 20, |ui| { + crate::dialogs::modal::fits_itself(ui); ui.set_width(NAME_W + TARGET_W + CHORD_W + 220.0); crate::dialogs::modal::heading(ui, tl!("Import Shortcut Set")); ui.add_space(10.0); diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index cad38bb984..00b45e0db7 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -428,13 +428,17 @@ fn request(action: egui::accesskit::Action, target_node: egui::accesskit::NodeId egui::Event::AccessKitActionRequest(ActionRequest { action, target_node, target_tree: TreeId::ROOT, data: None }) } -/// Type `typed` into Scale W, which shows `shown` (the first field that does, before H), and Tab out. +/// Type `typed` into Scale W, which shows `shown` (the leftmost field that does, before H), and Tab out. fn type_w(screen: &mut Screen, app: &mut VectorcraftApp, shown: &str, typed: &str) { let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; screen.run(app, vec![]); let out = screen.run(app, vec![]); let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; - let w = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown))); + // W is left of H on their row (the tree lists its nodes in no particular order). + let w = nodes + .iter() + .filter(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown))) + .min_by(|(_, a), (_, b)| a.bounds().map_or(f64::MAX, |r| r.x0).total_cmp(&b.bounds().map_or(f64::MAX, |r| r.x0))); screen.run(app, vec![request(egui::accesskit::Action::Focus, w.expect("the Scale W field").0)]); screen.run(app, vec![key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text(typed.into())]); screen.run(app, vec![key(egui::Key::Tab, egui::Modifiers::NONE)]); diff --git a/crates/ui-egui/src/dialogs/tests_scroll.rs b/crates/ui-egui/src/dialogs/tests_scroll.rs new file mode 100644 index 0000000000..d5db06b17d --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_scroll.rs @@ -0,0 +1,367 @@ +//! Dialogs in a short or narrow window: a dialog too large for the window scrolls instead of +//! running off the screen. Every scroll bar here is drawn at rest (a solid bar style), so the tests +//! can find it. +use egui::{Pos2, Rect, Shape, vec2}; +use serde_json::json; +use vectorcraft_engine::Session; + +use super::*; + +type Open = fn(&mut VectorcraftApp); + +/// What a dialog drew: the shapes, the dialog window's rectangle, and how it scrolls +/// ([`modal::scrolling`]). +struct Shown { + shapes: Vec, + window: Rect, + body: Option, + whole: [bool; 2], +} + +/// Open a dialog with `open` in a `size` window, with the pointer in the window's corner (away +/// from the dialog), and draw it until it settles. With `scroll`, then scroll far down and right +/// near the dialog's right edge (on the bar of a window that scrolls as a whole, beside the lists +/// inside it) and draw it until it settles again. +fn show_in(open: Open, size: egui::Vec2, scroll: bool) -> Shown { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 60})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + ctx.global_style_mut(|s| s.spacing.scroll = egui::style::ScrollStyle::solid()); + open(&mut app); + let screen = Rect::from_min_size(Pos2::ZERO, size); + let window = |ctx: &egui::Context| { + ctx.memory(|m| { + m.areas() + .visible_layer_ids() + .into_iter() + .filter(|l| l.order == egui::Order::Foreground) + .filter_map(|l| Some((l.id, m.area_rect(l.id)?))) + .max_by(|a, b| a.1.area().total_cmp(&b.1.area())) + }) + .unwrap_or((egui::Id::NULL, Rect::NOTHING)) + }; + let mut time = 0.0; + let mut frames = |app: &mut VectorcraftApp, first: Vec| { + let mut first = Some(first); + let mut shapes = vec![]; + for _ in 0..12 { + time += 1.0; + let input = + egui::RawInput { screen_rect: Some(screen), events: first.take().unwrap_or_default(), time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + shapes = std::mem::take(&mut out.shapes); + } + shapes + }; + let mut shapes = frames(&mut app, vec![egui::Event::PointerMoved(screen.max - vec2(2.0, 2.0))]); + if scroll { + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(-5000.0, -5000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + let (_, w) = window(&ctx); + let before = Shown { shapes: std::mem::take(&mut shapes), window: w, body: None, whole: [false; 2] }; + let at = whole_bar(&before).map_or(egui::pos2(w.right() - 23.0, w.center().y), |r| r.center()); + shapes = frames(&mut app, vec![egui::Event::PointerMoved(at), wheel]); + } + let (id, window) = window(&ctx); + let (body, whole) = modal::scrolling(&ctx, id); + Shown { shapes, window, body, whole } +} + +/// Filled bars 4 to 10 pt across and longer than 12 pt (scroll bars and their handles), upright or +/// (`sideways`) flat, inside the dialog window; with `seen`, only those inside their clip. +fn bars(shown: &Shown, sideways: bool, seen: bool) -> Vec { + fn walk(s: &Shape, clip: Rect, sideways: bool, seen: bool, out: &mut Vec) { + match s { + Shape::Rect(r) if r.fill != egui::Color32::TRANSPARENT => { + let (across, along) = if sideways { (r.rect.height(), r.rect.width()) } else { (r.rect.width(), r.rect.height()) }; + if (4.0..=10.0).contains(&across) && along > 12.0 && (!seen || clip.contains_rect(r.rect)) { + out.push(r.rect); + } + } + Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, sideways, seen, out)), + _ => {} + } + } + let mut out = vec![]; + shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, sideways, seen, &mut out)); + out.retain(|r| shown.window.expand(0.5).contains_rect(*r)); + out +} + +/// The bar of a shared dialog's scrolling body: the rightmost upright bar as tall as the body is +/// drawn (a list inside the body draws its bar further left). +fn body_bar(shown: &Shown) -> Option { + let view = shown.body?; + bars(shown, false, true).into_iter().filter(|r| (r.height() - view).abs() <= 1.0).max_by(|a, b| a.right().total_cmp(&b.right())) +} + +/// The bar of a window that scrolls as a whole: an upright bar at the window's right edge that +/// runs most of the window's height (lists inside it are shorter). +fn whole_bar(shown: &Shown) -> Option { + let w = shown.window; + bars(shown, false, true) + .into_iter() + .filter(|r| r.right() >= w.right() - 24.0 && r.height() >= 0.8 * w.height()) + .max_by(|a, b| a.height().total_cmp(&b.height())) +} + +/// The texts `labels` the dialog drew, each with whether it can be seen (inside the screen and +/// its clip). +fn buttons(shown: &Shown, screen: Rect, labels: &[&str]) -> Vec<(String, bool)> { + fn walk(s: &Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) { + match s { + Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect(), clip)), + Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, out)), + _ => {} + } + } + let mut texts = vec![]; + shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts)); + texts + .into_iter() + .filter(|(s, ..)| labels.contains(&s.as_str())) + .map(|(s, r, clip)| (s, screen.contains_rect(r) && clip.contains_rect(r))) + .collect() +} + +#[test] +fn a_dialog_taller_than_the_window_scrolls_its_body_and_keeps_its_buttons_in_view() { + let opens: [(&str, Open, &[&str]); 7] = [ + ("SVG Options", |app| svg_options::open(app, svg_options::Mode::Export, Some("/tmp/x.svg")), &["OK", "Cancel"]), + ("EPS Options", |app| eps_options::open(app, &json!({"format": "eps", "path": "/tmp/x.eps"})), &["Export", "Cancel"]), + ("DXF Options", |app| dxf_options::open(app, &json!({"format": "dxf", "path": "/tmp/x.dxf"})), &["Export", "Cancel"]), + ( + "Save PDF", + |app| { + save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap(); + }, + &["Cancel"], + ), + ( + "Save for Web", + |app| { + save_for_web::open(app).unwrap(); + }, + &["Cancel", "Done"], + ), + ("Export for Screens", export_for_screens::open, &["Cancel"]), + ( + "Print", + |app| { + print::open(app).unwrap(); + }, + &["Cancel", "Done"], + ), + ]; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 480.0)); + for (name, open, labels) in opens { + let tall = show_in(open, vec2(1280.0, 900.0), false); + assert!(tall.window.height() > screen.height(), "{name}: the dialog is taller than the short window ({:?})", tall.window); + assert_eq!((tall.body, tall.whole), (None, [false; 2]), "{name}: in a tall window nothing scrolls"); + let shown = show_in(open, screen.size(), false); + assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window); + let found = buttons(&shown, screen, labels); + assert_eq!(found.len(), labels.len(), "{name}: {found:?}"); + assert!(found.iter().all(|(_, seen)| *seen), "{name}: the buttons stay in view: {found:?}"); + assert_eq!(shown.whole, [false; 2], "{name}: the window does not scroll as a whole"); + let bar = body_bar(&shown); + assert!(bar.is_some(), "{name}: the body scrolls ({:?}) and its bar is drawn: {:?}", shown.body, bars(&shown, false, true)); + } +} + +#[test] +fn a_list_in_a_scrolling_body_is_no_taller_than_the_body() { + // The settings of Save for Web and the sections of Print and Save PDF scroll in lists of their + // own; in a short window those lists are no taller than the body shows, so each list and its + // bar can be scrolled into view whole. + let opens: [(&str, Open); 3] = [ + ("Save for Web", |app| { + save_for_web::open(app).unwrap(); + }), + ("Print", |app| { + print::open(app).unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("__section".into(), json!("Marks and Bleed")); + } + }), + ("Save PDF", |app| { + save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("__section".into(), json!("Marks and Bleeds")); + } + }), + ]; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 400.0)); + let mut wrong = vec![]; + for (name, open) in opens { + let shown = show_in(open, screen.size(), false); + let Some(body) = body_bar(&shown) else { + wrong.push(format!("{name}: the body does not scroll ({:?}): {:?}", shown.body, bars(&shown, false, false))); + continue; + }; + // The tracks of the lists' bars, seen or not: left of the body's bar and inside the window + // (a list taller than the body runs past the window's bottom). + let lists: Vec = bars(&shown, false, false).into_iter().filter(|r| r.right() < body.left()).collect(); + let tallest = lists.iter().map(|r| r.height()).fold(0.0, f32::max); + if tallest == 0.0 || tallest > body.height() + 0.5 { + wrong.push(format!("{name}: no list bar no taller than the body ({}): {:?}", body.height(), bars(&shown, false, false))); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +#[test] +fn save_for_web_in_the_smallest_window_keeps_its_settings_and_buttons_in_view() { + let open: Open = |app| { + save_for_web::open(app).unwrap(); + }; + // The app window's smallest size, 800 by 500 pixels, at a UI scale of 100%, 110% and 125%. + let mut wrong = vec![]; + for size in [vec2(800.0, 500.0), vec2(727.0, 454.0), vec2(640.0, 400.0)] { + let screen = Rect::from_min_size(Pos2::ZERO, size); + let shown = show_in(open, size, false); + let labels = ["Format:", "Optimize to File Size…", "Cancel", "Done"]; + let found = buttons(&shown, screen, &labels); + if !screen.contains_rect(shown.window) || found.len() != labels.len() || !found.iter().all(|(_, seen)| *seen) { + wrong.push(format!("{size:?}: the dialog ({:?}) leaves its settings and buttons in view: {found:?}", shown.window)); + } + if body_bar(&shown).is_none() || shown.whole != [false; 2] { + wrong.push(format!("{size:?}: only the body scrolls ({:?}, {:?})", shown.body, shown.whole)); + } + // The controls under the narrower panes stay in their column, left of the settings. + let controls = text_rects(&shown, "Preview in Browser").first().map(|r| r.right()); + let settings = text_rects(&shown, "Format:").first().map(|r| r.left()); + if !matches!((controls, settings), (Some(c), Some(s)) if c < s) { + wrong.push(format!("{size:?}: Preview in Browser ({controls:?}) is left of the settings ({settings:?})")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// The rectangles of the texts `label` the dialog drew. +fn text_rects(shown: &Shown, label: &str) -> Vec { + fn walk(s: &Shape, label: &str, out: &mut Vec) { + match s { + Shape::Text(t) if t.galley.text() == label => out.push(t.visual_bounding_rect()), + Shape::Vec(v) => v.iter().for_each(|s| walk(s, label, out)), + _ => {} + } + } + let mut out = vec![]; + shown.shapes.iter().for_each(|c| walk(&c.shape, label, &mut out)); + out +} + +#[test] +fn a_window_too_large_for_the_screen_scrolls_as_a_whole() { + let opens: [(&str, Open, &[&str]); 4] = [ + ("Preferences", |app| crate::prefs_dialog::open(app, None), &["OK", "Cancel"]), + ("Keyboard Shortcuts", crate::shortcut_editor::open, &["OK", "Cancel"]), + ("New Document", new_document::open, &["Create", "Close"]), + ("Find Font", crate::find_font::open, &["Done"]), + ]; + // The app window's smallest size. + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + for (name, open, labels) in opens { + let tall = show_in(open, vec2(1280.0, 900.0), false); + assert!( + tall.window.height() > screen.height() || tall.window.width() > screen.width(), + "{name}: the dialog is larger than the small window ({:?})", + tall.window + ); + assert_eq!(tall.whole, [false; 2], "{name}: in a large window the dialog does not scroll as a whole"); + let shown = show_in(open, screen.size(), false); + assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window); + assert!(shown.whole[1], "{name}: the dialog scrolls as a whole"); + assert!(whole_bar(&shown).is_some(), "{name}: the window's bar is drawn: {:?}", bars(&shown, false, true)); + // The buttons can sit outside the part in view; each is in view at the top or scrolled to + // the end. + let scrolled = show_in(open, screen.size(), true); + let (top, end) = (buttons(&shown, screen, labels), buttons(&scrolled, screen, labels)); + for label in labels { + let seen = |found: &[(String, bool)]| found.iter().any(|(s, seen)| s == label && *seen); + assert!(seen(&top) || seen(&end), "{name}: {label} can be scrolled into view: {top:?} {end:?}"); + } + } +} + +#[test] +fn keyboard_shortcuts_keeps_its_scroll_under_import_shortcut_set() { + // Scrolled down in the smallest window, Keyboard Shortcuts is where it was left when Import + // Shortcut Set, opened over it, is canceled; closed and opened again, it starts at its top. + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + let mut time = 0.0; + // Draws 12 frames, the first with `events`; returns whether the heading can be seen. + let mut heading_seen = |app: &mut VectorcraftApp, events: Vec| { + let mut events = Some(events); + let mut seen = false; + for _ in 0..12 { + time += 1.0; + let input = + egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + let shown = Shown { shapes: out.shapes, window: screen, body: None, whole: [false; 2] }; + seen = buttons(&shown, screen, &["Keyboard Shortcuts"]).iter().any(|(_, seen)| *seen); + } + seen + }; + let wheel = |at: Pos2| { + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -5000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + vec![egui::Event::PointerMoved(at), wheel] + }; + crate::shortcut_editor::open(&mut app); + assert!(heading_seen(&mut app, vec![]), "Keyboard Shortcuts opens at its top"); + // On the window's bar, inside its 20 pt margin. + let window = ctx.memory(|m| m.area_rect(egui::Id::unique("dialog-shortcuts"))).unwrap_or(screen); + assert!(!heading_seen(&mut app, wheel(egui::pos2(window.right() - 23.0, window.center().y))), "the wheel scrolls the heading away"); + let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n}\n"; + crate::io::open_bytes(&mut app, "Keys.kys", kys.as_bytes(), None).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(shortcut_import::KIND)); + heading_seen(&mut app, vec![]); + cancel(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("shortcuts"), "Cancel shows Keyboard Shortcuts again"); + assert!(!heading_seen(&mut app, vec![]), "shown again, Keyboard Shortcuts is where it was scrolled to"); + cancel(&mut app); + heading_seen(&mut app, vec![]); + crate::shortcut_editor::open(&mut app); + assert!(heading_seen(&mut app, vec![]), "opened again, Keyboard Shortcuts starts at its top"); +} + +#[test] +fn a_window_that_fits_itself_but_is_too_wide_scrolls_sideways() { + // Import Shortcut Set sizes its lists from the window's height and is about 780 pt wide. An + // 800 by 600 pixel window at a UI scale of 125% is 640 by 480 pt. + let open: Open = |app| { + let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n /Acme\\ Paste { /Modifiers 11 /Key 903 }\n}\n"; + crate::io::open_bytes(app, "Keys.kys", kys.as_bytes(), None).unwrap(); + }; + let wide = show_in(open, vec2(1280.0, 900.0), false); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(640.0, 480.0)); + assert!(wide.window.width() > screen.width(), "Import Shortcut Set is wider than the window: {:?}", wide.window); + assert_eq!(wide.whole, [false; 2], "in a large window it does not scroll"); + let shown = show_in(open, screen.size(), false); + assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window); + assert_eq!(shown.whole, [true, false], "it scrolls sideways only"); + let sideways: Vec = bars(&shown, true, true).into_iter().filter(|r| r.width() >= 0.5 * shown.window.width()).collect(); + assert!(!sideways.is_empty(), "its sideways bar is drawn: {:?}", bars(&shown, true, false)); +} From 58e510f06c9533e8a8d718b360010cbc75a84992 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 21:18:56 -0800 Subject: [PATCH 25/33] Fix #5451: Windows Save As follows selected file type --- apps/vectorcraft/src/host_services.rs | 44 +++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 53e0484534..1ce124c1dd 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -96,7 +96,24 @@ fn dialog_for(d: D, request: &PickRequest) -> D { Some(folder) => d.folder(folder), None => d, }; - if pick.name.is_empty() { d } else { d.file_name(&pick.name) } + if pick.name.is_empty() { + return d; + } + // Windows' save dialog changes the extension when a different file type is chosen only when + // the suggested name has no explicit extension. rfd supplies the first filter's extension to + // that dialog, so leave the suffix to Windows for saves that offer several formats (#5451). + // A remaining dot in the stem would look like another explicit extension to Windows. + #[cfg(windows)] + if matches!(request, PickRequest::Save(_)) + && pick.filters.len() > 1 + && let Some(ext) = std::path::Path::new(&pick.name).extension().and_then(|e| e.to_str()) + && pick.filters.iter().any(|(_, exts)| exts.iter().any(|e| e.eq_ignore_ascii_case(ext))) + && let Some(stem) = std::path::Path::new(&pick.name).file_stem().and_then(|s| s.to_str()) + && !stem.contains('.') + { + return d.file_name(stem); + } + d.file_name(&pick.name) } #[cfg(test)] @@ -796,7 +813,7 @@ mod dialog_tests { /// The file types a dialog was given, by label. #[derive(Default)] - struct Filters(Vec<(String, Vec)>); + struct Filters(Vec<(String, Vec)>, Option); impl DialogSettings for Filters { fn parent(self, _window: &winit::window::Window) -> Self { @@ -812,7 +829,8 @@ mod dialog_tests { fn folder(self, _folder: &str) -> Self { self } - fn file_name(self, _name: &str) -> Self { + fn file_name(mut self, name: &str) -> Self { + self.1 = Some(name.to_string()); self } } @@ -869,4 +887,24 @@ mod dialog_tests { let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS)); assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first); } + + /// A format selected after the Windows Save As dialog opens can replace the suffix of the + /// suggested name. Single-format saves and open dialogs keep the supplied name verbatim. + #[cfg(windows)] + #[test] + fn save_dialog_with_several_formats_leaves_the_extension_to_windows() { + let filters = vec![FilePick::filter("VectorCraft", &["vectorcraft"]), FilePick::filter("PDF-compatible .ai", &["ai"])]; + let pick = FilePick { name: "Poster.vectorcraft".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick.clone())).1.as_deref(), Some("Poster")); + assert_eq!(dialog_for(Filters::default(), &PickRequest::Open(pick)).1.as_deref(), Some("Poster.vectorcraft")); + + let pick = FilePick { name: "Poster.AI".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster")); + let pick = FilePick { name: "Poster.design".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.design")); + let pick = FilePick { name: "draft.v1.vectorcraft".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("draft.v1.vectorcraft")); + let pick = FilePick { name: "Poster.vectorcraft".into(), filters: vec![filters[0].clone()], ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.vectorcraft")); + } } From 0c2d7d148882dac04b88edf8e456b018f810df8d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 21:23:32 -0800 Subject: [PATCH 26/33] Dimension: Arrow Style shows each style's arrowhead drawn before its name The Arrow Style dropdown in Dimension Tool Options and in the Properties panel's Dimension section showed only the names Filled, Open, Tick and None. Each style now shows its arrowhead at the end of a short line before its name, in the open list and in the closed field, drawn with the Stroke panel's arrowhead previews. The four styles and their saved values are unchanged. ArrowStyle::arrowhead holds the style-to-arrowhead mapping, so the dimension line and the preview use the same head. dropdown_icon_names_sized takes an icon size that is not square. Part of #8049. --- crates/doc/src/dimension.rs | 12 +++ crates/engine/src/cmd/dimension.rs | 13 +-- crates/ui-egui/src/dialogs/dimension.rs | 104 +++++++++++++++++++++++- crates/ui-egui/src/panels/stroke.rs | 2 +- crates/ui-egui/src/widgets.rs | 4 +- crates/ui-egui/src/widgets/dropdowns.rs | 18 +++- docs/target-app-parity.md | 1 + 7 files changed, 135 insertions(+), 19 deletions(-) diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index e803d867fc..9e78d17d4d 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -112,6 +112,18 @@ pub enum ArrowStyle { None, } +impl ArrowStyle { + /// The stroke arrowhead drawn at each end of the dimension line, or None for no head. + pub fn arrowhead(self) -> Option { + match self { + Self::Filled => Some(crate::Arrowhead::Triangle), + Self::Open => Some(crate::Arrowhead::TriangleOpen), + Self::Tick => Some(crate::Arrowhead::Slash), + Self::None => None, + } + } +} + /// Where the label sits across the dimension line. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index 183cbd3746..955401b923 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -3,10 +3,8 @@ use super::{CommandSpec, EngineError, Result, Session, cmd, has_doc}; use serde_json::{Value, json}; use std::sync::Arc; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::dimension::{ - ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition, -}; -use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_doc::dimension::{Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition}; +use vectorcraft_doc::{Appearance, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject}; use vectorcraft_geom::{Affine, BezPath, PathData, Point, Vec2}; pub fn specs() -> Vec { @@ -567,12 +565,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) -> LineType::Solid => None, }; if arrows { - let head = match o.arrow_style { - ArrowStyle::Filled => Some(Arrowhead::Triangle), - ArrowStyle::Open => Some(Arrowhead::TriangleOpen), - ArrowStyle::Tick => Some(Arrowhead::Slash), - ArrowStyle::None => None, - }; + let head = o.arrow_style.arrowhead(); st.start_arrow = head.clone(); st.end_arrow = head; st.arrow_scale = (o.arrow_scale, o.arrow_scale); diff --git a/crates/ui-egui/src/dialogs/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index 1a08c4d377..bcb56eb4e6 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -4,7 +4,7 @@ use super::DialogSpec; use crate::{VectorcraftApp, state::Dialog, theme::Tokens, widgets}; use egui::{RichText, Ui}; use serde_json::{Value, json}; -use vectorcraft_doc::dimension::DimensionOptions; +use vectorcraft_doc::dimension::{ArrowStyle, DimensionOptions}; pub const KIND: &str = "dimensionOptions"; pub(super) const SPEC: DialogSpec = DialogSpec { @@ -32,6 +32,8 @@ const UNITS: Choices = &[ ]; const LINE_TYPES: Choices = &[("solid", "Solid"), ("dashed", "Dashed"), ("dotted", "Dotted")]; const ARROWS: Choices = &[("filled", "Filled"), ("open", "Open"), ("tick", "Tick"), ("none", "None")]; +/// The size of an Arrow Style preview: a line with the head at its right end. +const ARROW_PREVIEW: egui::Vec2 = egui::vec2(40.0, 16.0); const POSITIONS: Choices = &[("away", "Away from the Line"), ("between", "Between Line and Object")]; const ALIGNMENTS: Choices = &[("left", "Left"), ("center", "Center"), ("right", "Right")]; @@ -69,6 +71,31 @@ fn choose(ui: &mut Ui, fields: &mut serde_json::Map, key: &str, l }); changed } +/// The Arrow Style dropdown: each style shows a drawn preview of its arrowhead before its name, in +/// the open list and in the closed field. +fn arrow_style(ui: &mut Ui, fields: &mut serde_json::Map, id: &str) -> bool { + const KEY: &str = "arrowStyle"; + let mut changed = false; + widgets::label_row(ui, tl!("Arrow Style:"), 96.0, |ui| { + let current = fields.get(KEY).and_then(Value::as_str).unwrap_or_default(); + let shown = ARROWS.iter().position(|(v, _)| *v == current); + let names: Vec<&str> = ARROWS.iter().map(|(_, s)| tl!(*s)).collect(); + let icon = |ui: &Ui, rect: egui::Rect, i: usize, ink: egui::Color32, _: bool| { + if let Some((value, _)) = ARROWS.get(i) + && let Ok(style) = serde_json::from_value::(json!(value)) + { + crate::panels::stroke::paint_arrow(ui, rect, style.arrowhead().as_ref(), false, ink); + } + }; + if let Some((value, _)) = + widgets::dropdown_icon_names_sized(ui, ("dimension", id), shown, &names, 150.0, ARROW_PREVIEW, icon).and_then(|i| ARROWS.get(i)) + { + fields.insert(KEY.into(), json!(value)); + changed = true; + } + }); + changed +} fn number(ui: &mut Ui, fields: &mut serde_json::Map, key: &str, label: &str, range: (f64, f64), suffix: &str) -> bool { let mut changed = false; widgets::label_row(ui, tl!(label), 96.0, |ui| { @@ -160,7 +187,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { color(ui, f, "lineColor"); }); ui.horizontal(|ui| { - choose(ui, f, "arrowStyle", "Arrow Style:", ARROWS); + arrow_style(ui, f, "arrowStyle"); number(ui, f, "arrowScale", "Arrow Scale:", (1.0, 1000.0), "%"); }); }); @@ -310,7 +337,7 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) { changed |= number(ui, &mut f, "lineWeight", "Line Weight:", (0.1, 100.0), "pt"); changed |= color(ui, &mut f, "lineColor"); }); - ui.horizontal(|ui| changed |= choose(ui, &mut f, "arrowStyle", "Arrow Style:", ARROWS)); + ui.horizontal(|ui| changed |= arrow_style(ui, &mut f, "props-arrowStyle")); ui.horizontal(|ui| { changed |= number(ui, &mut f, "fontSize", "Font Size:", (1.0, 1000.0), "pt"); changed |= color(ui, &mut f, "textColor"); @@ -377,4 +404,75 @@ mod tests { assert!(text.contains(label), "{label}: {text}"); } } + + /// Whether a frame drew a picture (a textured mesh) just before the text `name` on its line. + fn picture_before(out: &egui::FullOutput, name: &str) -> bool { + fn collect(s: &egui::Shape, texts: &mut Vec<(String, egui::Rect)>, pictures: &mut Vec) { + match s { + egui::Shape::Text(t) => texts.push((t.galley.text().to_owned(), t.visual_bounding_rect())), + egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => pictures.push(m.calc_bounds()), + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, texts, pictures)), + _ => {} + } + } + let (mut texts, mut pictures) = (vec![], vec![]); + for c in &out.shapes { + collect(&c.shape, &mut texts, &mut pictures); + } + texts + .iter() + .filter(|(t, _)| t == name) + .any(|(_, r)| pictures.iter().any(|p| p.max.x <= r.min.x + 1.0 && r.min.x - p.max.x < 16.0 && p.min.y < r.max.y && p.max.y > r.min.y)) + } + + /// The frame `f` draws, once its previews are loaded. + fn frame(app: &mut VectorcraftApp, mut f: impl FnMut(&mut VectorcraftApp, &mut Ui)) -> egui::FullOutput { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui)).textures_delta.clear(); + ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui)) + } + + /// The Arrow Style field of the Tool Options and of Properties shows the style's arrowhead, + /// drawn, before its name (#8049). + #[test] + fn arrow_style_shows_a_drawn_arrowhead() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("tool.options", json!({"tool":"dimension"})).unwrap(); + let out = frame(&mut app, |app, ui| super::super::show(app, ui.ctx())); + assert!(picture_before(&out, "Filled"), "Tool Options"); + app.ui.dialog = None; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("dimension.create", json!({"a":[10,10],"b":[110,10],"options":{"arrowStyle":"tick"}})).unwrap(); + let out = frame(&mut app, properties_section); + assert!(picture_before(&out, "Tick"), "Properties"); + } + + /// Each preview shows the stroke head that the dimension line draws at its ends. + #[test] + fn arrow_previews_match_the_dimension_line() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + for style in [ArrowStyle::Filled, ArrowStyle::Open, ArrowStyle::Tick, ArrowStyle::None] { + let options = json!({"arrowStyle": style}); + let id = app.run("dimension.create", json!({"a":[10,10],"b":[110,10],"options":options})).unwrap()["id"].as_u64().unwrap(); + let st = app.session.active().unwrap(); + let heads: Vec<_> = st + .doc + .node(vectorcraft_doc::NodeId(id)) + .unwrap() + .children() + .unwrap() + .iter() + .filter_map(|n| n.appearance.stroke().map(|s| (s.start_arrow.clone(), s.end_arrow.clone()))) + .filter(|(a, b)| a.is_some() || b.is_some()) + .collect(); + match style.arrowhead() { + Some(head) => { + assert!(!heads.is_empty() && heads.iter().all(|h| *h == (Some(head.clone()), Some(head.clone()))), "{style:?}: {heads:?}") + } + None => assert!(heads.is_empty(), "{style:?}: {heads:?}"), + } + } + } } diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index 3b48f45e91..ccdda25eb8 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -416,7 +416,7 @@ pub(super) fn arrow_doc(mut a: Option, start: bool, w: f64, h: f64) - /// Draw an arrowhead preview (the head as the canvas draws it) in `r`: a line with the head at the /// left (`start`) or right end. -fn paint_arrow(ui: &Ui, r: Rect, a: Option<&Arrowhead>, start: bool, color: Color32) { +pub(crate) fn paint_arrow(ui: &Ui, r: Rect, a: Option<&Arrowhead>, start: bool, color: Color32) { if let Some(tex) = widgets::doc_preview(ui, &format!("arrow:{}:{start}", arrow_key(a)), r.size(), |w, h| arrow_doc(a.cloned(), start, w, h)) { ui.painter().image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), color); } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index d3278f667d..0c628e3d28 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -50,8 +50,8 @@ pub use drag::{ use dropdowns::combo_button_id; pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field_named, combo_named, field_focused_in, menu_min_width, popover_is_open}; pub use dropdowns::{ - dropdown, dropdown_icon_names, 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, + dropdown, dropdown_icon_names, dropdown_icon_names_sized, 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, }; #[cfg(test)] pub(crate) use dropdowns::{menu_floor, menu_room_either}; diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index 7f088f25ef..1b2d4b421f 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -50,11 +50,23 @@ pub fn dropdown_icon_names( width: f32, icon_size: f32, icon: impl Fn(&Ui, Rect, usize, egui::Color32, bool), +) -> Option { + dropdown_icon_names_sized(ui, id, current, options, width, Vec2::splat(icon_size), icon) +} + +/// [`dropdown_icon_names`] with icons of any size, for a picture wider than it is tall, such as a +/// line with an arrowhead. +pub fn dropdown_icon_names_sized( + ui: &mut Ui, + id: impl std::hash::Hash, + current: Option, + options: &[&str], + width: f32, + icon_size: Vec2, + icon: impl Fn(&Ui, Rect, usize, egui::Color32, bool), ) -> Option { let icon = &icon; - let atom = move |i: usize, highlighted: bool| { - egui::Atom::paint(Vec2::splat(icon_size), move |ui, a| icon(ui, a.rect, i, a.fallback_text_color, highlighted)) - }; + let atom = move |i: usize, highlighted: bool| egui::Atom::paint(icon_size, move |ui, a| icon(ui, a.rect, i, a.fallback_text_color, highlighted)); let shown = match current.and_then(|i| options.get(i).map(|name| (i, *name))) { Some((i, name)) => (atom(i, false), egui::RichText::new(name).size(12.0)).into_atoms(), None => egui::RichText::new("").size(12.0).into_atoms(), diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1a4de32fa2..daf4f1f70d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -631,6 +631,7 @@ since 2026-10-01. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. **Drawing tools, Dimension tool points land on dimensions already drawn (#8063):** By VectorCraft's own rule, with Smart Guides or Snap to Point on, a Linear point that no anchor of the art within 8 pixels takes lands on the end of a visible, unlocked dimension's dimension line, or on the far end of its extension line, within 8 pixels, and a point that nothing else places lands on the closest point of such a line within 8 pixels, so at any zoom a dimension can start where another one ends. The end of an extension line next to the point it measures does not pull points away from that anchor. With Smart Guides and Anchor/Path Labels on, a point on an anchor or line end shows the "anchor" label and a point on a segment or line shows the "path" label. `linear_picks_land_on_anchors_paths_and_drawn_dimensions` and `an_anchor_beside_a_drawn_dimension_takes_the_point` cover it. **Drawing tools, Dimension tool dimensions selected with their art keep their lines and label:** Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave a dimension selected with art it measures, directly or in selected groups without fills, strokes or effects of their own, as it is and change only the other art; when the new art no longer fits its link, the dimension stays where it was, no longer linked, and undo links it again. `expand_leaves_a_dimension_selected_with_its_art_as_it_is`, `expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is`, `outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is`, `a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing`, `a_group_effect_expanded_reaches_the_dimension_it_holds`, `expand_keeps_a_dimension_in_its_asset_and_its_variable_binding`, `a_dimension_keeps_no_link_to_the_art_expand_replaced`, `a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced`, `a_dimension_outlasts_the_stroke_expand_outlined` and `expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art` cover it. +**Drawing tools, Dimension tool Arrow Style shows each arrowhead (#8049):** The Arrow Style dropdown in Dimension Tool Options and in the Properties panel's Dimension section draws each style's arrowhead at the end of a short line before its name, in the open list and in the closed field, using the Stroke panel's arrowhead previews. Filled, Open, Tick and None are the same four styles, saved as before. `arrow_style_shows_a_drawn_arrowhead` and `arrow_previews_match_the_dimension_line` cover it. **Drawing tools, Line Segment from one curve onto a common tangent of another:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a Line Segment drag pressed anywhere on a convex closed path with curves and dragged to within the snapping tolerance of another such path lands on a common tangent of the two ([tangent lines to circles](https://en.wikipedia.org/wiki/Tangent_lines_to_circles)): both ends move to where the line touches the paths, the start sliding along the first path, and each end shows the "tangent" label when Anchor/Path Labels is on, with the line drawn as a guide when Alignment Guides is on. The line is the tangent whose touch point on the second path is nearest the pointer, so moving the pointer around the second path switches between the outer tangent and the one crossing between the paths. The start stays where it was pressed when Shift, Alt or Space is held, when an anchor, center or crossing lies nearer the pointer than the second path does, when the press snapped to an anchor, center or crossing off the first path, when Snap to Tangent is off, when Snap to Grid or pixel snapping places drawn points, or when either path bends inward somewhere or has more than 512 segments. `a_line_from_one_circle_to_another_lands_on_their_common_tangent`, `a_line_from_a_turned_ellipse_lands_on_its_tangent_with_a_circle`, `a_line_near_the_second_path_takes_the_tangent_touching_it_nearest`, `a_line_keeps_its_start_without_a_tangent_snap`, `a_line_to_a_crescent_or_from_an_anchor_beside_the_curve_keeps_its_start` and `a_line_segment_drag_draws_the_common_tangent_as_one_undo_step` cover it. **Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views:** `live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle` checks every TraceView, geometric and visual bounds and rotated result bounds. `live_trace_selection_highlight_excludes_the_retained_source_rectangle` checks result highlights and the existing ordinary-group policy. Shared editing-child traversal also preserves Shaper handling. **Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards:** Shared existing preset definitions are reused; no external preset assets are added. Presets preserve each selected artboard's orientation, and orientation choices apply even when the active board already matches. Fit operations draft bounds until OK, affect only the active artboard and leave artwork in place. Regression coverage checks draft/Cancel, selected-set application, active-only fitting and Undo. From deea93f36cd0dd90c7869adf7d39e87d0f4938e5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 22:01:26 -0800 Subject: [PATCH 27/33] Part of #5941: a hidden dialog keeps its scroll when an alert was also open - A dialog hidden under one opened over it now finds that window among every modal window drawn in the pass before, not only the last one, so an alert drawn beside the window over it no longer makes the dialog under it start at its top again. - The field test gives the field the focus once and checks that it keeps it and takes each key through the resizes. - New tests: Check Spelling, which draws its buttons in its body, keeps its heading in view while its buttons scroll with the body; Import Shortcut Set, Keyboard Shortcuts and Preferences in a window narrower than themselves scroll sideways to their right edge. - The Color Picker marks itself as fitting the window a few lines lower in its body. --- crates/ui-egui/src/dialogs/color_picker.rs | 2 +- crates/ui-egui/src/dialogs/modal.rs | 74 ++++++++----- crates/ui-egui/src/dialogs/tests_scroll.rs | 114 +++++++++++++++++---- 3 files changed, 142 insertions(+), 48 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index d6ebd2241a..1172a957b3 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -365,13 +365,13 @@ fn header(ui: &mut Ui, title: &str) { /// Draws the responsive picker and updates its color fields and live preview. /// Returns the requested action for the shared frame to confirm or cancel. fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { - super::modal::fits_itself(ui); let channel = Channel::parse(&d.str("channel")).unwrap_or_default(); let web = d.bool("webOnly"); let swatches = d.bool("swatches"); let p = picked(d); let original = d.fields.get("original").and_then(color_value).unwrap_or(p.color); let gamut = gamut_fix(app, ui.ctx(), "picker-gamut", &p.color); + super::modal::fits_itself(ui); let (side, values_w, button_w, stacked) = layout_size(ui); let field_w = side + SLIDER_GAP + SLIDER_W; let content_w = if stacked { field_w.max(values_w) } else { field_w + COLUMN_GAP + values_w }; diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index 582bd65a0d..26f9dda1a4 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -83,24 +83,32 @@ pub(crate) fn over_parent(ctx: &egui::Context) { } /// Whether modal window `id`, drawn in this pass, opened in it: it was not drawn in the pass before, -/// and the window drawn in the pass before was not one opened over it ([`over_parent`]). +/// and none of the windows drawn in the pass before was one opened over it ([`over_parent`]). fn opened(ctx: &egui::Context, id: Id) -> bool { let pass = ctx.cumulative_pass_nr(); ctx.data_mut(|m| { - // The window drawn in the pass before, if another. - let before = - m.get_temp::<(u64, Id)>(Id::unique(LAST_KEY)).filter(|&(at, other)| other != id && at.saturating_add(1) == pass).map(|(_, other)| other); - m.insert_temp(Id::unique(LAST_KEY), (pass, id)); + // The windows drawn in this pass so far and in the pass before. + let (at, now, prev) = m.get_temp::<(u64, Vec, Vec)>(Id::unique(LAST_KEY)).unwrap_or_default(); + let (mut now, prev) = if at == pass { + (now, prev) + } else if at.saturating_add(1) == pass { + (vec![], now) + } else { + (vec![], vec![]) + }; + let before: Vec = prev.iter().copied().filter(|&other| other != id).collect(); + now.push(id); + m.insert_temp(Id::unique(LAST_KEY), (pass, now, prev)); let last = std::mem::replace(m.get_temp_mut_or(id.with(SHOWN_KEY), u64::MAX), pass); if last != u64::MAX && last.saturating_add(1) >= pass { return false; } // Shown again as the window opened over it closed. - if before.is_some_and(|over| m.get_temp::(over.with(HOLDS_KEY)) == Some(id)) { + if before.iter().any(|over| m.get_temp::(over.with(HOLDS_KEY)) == Some(id)) { return false; } - // Opened over the window drawn in the pass before, it holds that one; otherwise none. - match before.filter(|_| m.get_temp::(Id::unique(OVER_KEY)) == Some(pass)) { + // Opened over the window drawn last in the pass before, it holds that one; otherwise none. + match before.last().copied().filter(|_| m.get_temp::(Id::unique(OVER_KEY)) == Some(pass)) { Some(under) => { m.insert_temp(id.with(HOLDS_KEY), under); } @@ -175,7 +183,8 @@ const WHOLE_KEY: &str = "modal-whole"; const SHOWN_KEY: &str = "modal-shown"; const TOP_ROWS_KEY: &str = "modal-top-rows"; const TOP_WHOLE_KEY: &str = "modal-top-whole"; -/// For all modal windows: the pass the last one was drawn in and its id (`LAST_KEY`), and the pass +/// For all modal windows: the pass the last one was drawn in, the ids of those drawn in that pass +/// and of those drawn in the pass before it (`LAST_KEY`), and the pass /// in which the window drawn next was marked as opened over another ([`over_parent`], `OVER_KEY`). /// Under a modal window's id: the window it was opened over and hides (`HOLDS_KEY`). const LAST_KEY: &str = "modal-last"; @@ -350,10 +359,11 @@ mod tests { } /// Draw `frames` frames of a 400×300 screen from `time`, the first with `events`, with the modal - /// window named `open` open, if any: a heading and 60 rows, in [`scrolled_rows`] when - /// `in_rows`. A window named "over …" is opened over the one before it ([`over_parent`]). - /// Returns whether a first row could be seen in the last frame (inside the screen and its clip). - fn first_row_seen(ctx: &egui::Context, open: Option<&str>, in_rows: bool, events: Vec, time: &mut f64, frames: usize) -> bool { + /// windows named in `open` open, in that order: the first a heading and 60 rows, in + /// [`scrolled_rows`] when `in_rows`, and any other a short alert. A window named "over …" is + /// opened over the one before it ([`over_parent`]). Returns whether a first row could be seen in + /// the last frame (inside the screen and its clip). + fn first_row_seen(ctx: &egui::Context, open: &[&str], in_rows: bool, events: Vec, time: &mut f64, frames: usize) -> bool { let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 300.0)); let add = |ui: &mut egui::Ui| { for i in 0..60 { @@ -367,13 +377,15 @@ mod tests { let input = egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(*time), ..Default::default() }; let mut out = ctx.run_ui(input, |ui| { - if let Some(name) = open { + for (i, &name) in open.iter().enumerate() { if name.starts_with("over ") { over_parent(ui.ctx()); } show(ui.ctx(), name, Id::unique(("modal-reopen-test", name)), 0.0, 8, |ui| { heading(ui, "Top"); - if in_rows { + if i > 0 { + ui.label("Alert"); + } else if in_rows { scrolled_rows(ui, "rows", add); } else { add(ui); @@ -411,32 +423,34 @@ mod tests { let ctx = egui::Context::default(); crate::theme::apply(&ctx, Default::default()); let mut time = 0.0; - assert!(first_row_seen(&ctx, Some("A"), in_rows, vec![], &mut time, 4), "rows {in_rows}: the window opens at its top"); - assert!(!first_row_seen(&ctx, Some("A"), in_rows, wheel_down(), &mut time, 60), "rows {in_rows}: the wheel scrolls the first row away"); - first_row_seen(&ctx, None, in_rows, vec![], &mut time, 2); - assert!(first_row_seen(&ctx, Some("A"), in_rows, vec![], &mut time, 4), "rows {in_rows}: opened again, the window starts at its top"); + assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: the window opens at its top"); + assert!(!first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60), "rows {in_rows}: the wheel scrolls the first row away"); + first_row_seen(&ctx, &[], in_rows, vec![], &mut time, 2); + assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: opened again, the window starts at its top"); } } #[test] fn a_window_hidden_under_one_opened_over_it_keeps_its_scroll() { // As Keyboard Shortcuts is while Import Shortcut Set is open over it: it is not drawn, but it - // did not close. A window that another replaced did close. + // did not close. A window that another replaced did close. Either may have shown an alert + // of its own, drawn after it in the same passes. + let others: [(&[&str], bool); 4] = [(&["over B"], true), (&["over B", "Alert"], true), (&["C"], false), (&["C", "Alert"], false)]; let mut wrong = vec![]; for in_rows in [false, true] { - for (other, kept) in [("over B", true), ("C", false)] { + for (other, kept) in others { let ctx = egui::Context::default(); crate::theme::apply(&ctx, Default::default()); let mut time = 0.0; - first_row_seen(&ctx, Some("A"), in_rows, vec![], &mut time, 4); - if first_row_seen(&ctx, Some("A"), in_rows, wheel_down(), &mut time, 60) { + first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4); + if first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60) { wrong.push(format!("rows {in_rows}: the wheel does not scroll A")); } - if !first_row_seen(&ctx, Some(other), in_rows, vec![], &mut time, 4) { - wrong.push(format!("rows {in_rows}: {other} does not open at its top")); + if !first_row_seen(&ctx, other, in_rows, vec![], &mut time, 4) { + wrong.push(format!("rows {in_rows}: {other:?} does not open at its top")); } - if first_row_seen(&ctx, Some("A"), in_rows, vec![], &mut time, 4) == kept { - wrong.push(format!("rows {in_rows}: after {other}, A {} where it was scrolled to", if kept { "is not" } else { "is still" })); + if first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4) == kept { + wrong.push(format!("rows {in_rows}: after {other:?}, A {} where it was scrolled to", if kept { "is not" } else { "is still" })); } } } @@ -455,6 +469,7 @@ mod tests { let mut text = String::from("12"); let mut time = 0.0; let mut field = None; + let mut focus_given = false; let mut seen = vec![]; for (height, typed) in [(900.0, "3"), (300.0, "4"), (900.0, "5")] { let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, height)); @@ -477,8 +492,11 @@ mod tests { }); }); out.textures_delta.clear(); - if let Some(id) = field.filter(|_| ctx.memory(|m| m.focused()).is_none()) { + // The field is given the focus once, after the first frame; a resize that took it + // away would leave the keys typed after it untaken. + if let Some(id) = field.filter(|_| !focus_given) { ctx.memory_mut(|m| m.request_focus(id)); + focus_given = true; } } let key = if in_body { window.with(TALL_KEY) } else { window.with(WHOLE_KEY) }; diff --git a/crates/ui-egui/src/dialogs/tests_scroll.rs b/crates/ui-egui/src/dialogs/tests_scroll.rs index d5db06b17d..01c9456fa2 100644 --- a/crates/ui-egui/src/dialogs/tests_scroll.rs +++ b/crates/ui-egui/src/dialogs/tests_scroll.rs @@ -1,6 +1,7 @@ //! Dialogs in a short or narrow window: a dialog too large for the window scrolls instead of //! running off the screen. Every scroll bar here is drawn at rest (a solid bar style), so the tests //! can find it. + use egui::{Pos2, Rect, Shape, vec2}; use serde_json::json; use vectorcraft_engine::Session; @@ -66,9 +67,13 @@ fn show_in(open: Open, size: egui::Vec2, scroll: bool) -> Shown { source: egui::MouseWheelSource::Unknown, modifiers: egui::Modifiers::NONE, }; - let (_, w) = window(&ctx); - let before = Shown { shapes: std::mem::take(&mut shapes), window: w, body: None, whole: [false; 2] }; - let at = whole_bar(&before).map_or(egui::pos2(w.right() - 23.0, w.center().y), |r| r.center()); + let (id, w) = window(&ctx); + let (body, whole) = modal::scrolling(&ctx, id); + let before = Shown { shapes: std::mem::take(&mut shapes), window: w, body, whole }; + // On the window's upright bar, else on its body's bar, else on its sideways bar, else at + // its right edge. + let sideways = bars(&before, true, true).into_iter().find(|r| r.width() >= 0.5 * w.width()); + let at = whole_bar(&before).or(body_bar(&before)).or(sideways).map_or(egui::pos2(w.right() - 23.0, w.center().y), |r| r.center()); shapes = frames(&mut app, vec![egui::Event::PointerMoved(at), wheel]); } let (id, window) = window(&ctx); @@ -117,16 +122,7 @@ fn whole_bar(shown: &Shown) -> Option { /// The texts `labels` the dialog drew, each with whether it can be seen (inside the screen and /// its clip). fn buttons(shown: &Shown, screen: Rect, labels: &[&str]) -> Vec<(String, bool)> { - fn walk(s: &Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) { - match s { - Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect(), clip)), - Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, out)), - _ => {} - } - } - let mut texts = vec![]; - shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts)); - texts + texts(shown) .into_iter() .filter(|(s, ..)| labels.contains(&s.as_str())) .map(|(s, r, clip)| (s, screen.contains_rect(r) && clip.contains_rect(r))) @@ -347,21 +343,101 @@ fn keyboard_shortcuts_keeps_its_scroll_under_import_shortcut_set() { assert!(heading_seen(&mut app, vec![]), "opened again, Keyboard Shortcuts starts at its top"); } +/// Open Import Shortcut Set on a set of two shortcuts. +fn open_shortcut_import(app: &mut VectorcraftApp) { + let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n /Acme\\ Paste { /Modifiers 11 /Key 903 }\n}\n"; + crate::io::open_bytes(app, "Keys.kys", kys.as_bytes(), None).unwrap(); +} + #[test] fn a_window_that_fits_itself_but_is_too_wide_scrolls_sideways() { // Import Shortcut Set sizes its lists from the window's height and is about 780 pt wide. An // 800 by 600 pixel window at a UI scale of 125% is 640 by 480 pt. - let open: Open = |app| { - let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n /Acme\\ Paste { /Modifiers 11 /Key 903 }\n}\n"; - crate::io::open_bytes(app, "Keys.kys", kys.as_bytes(), None).unwrap(); - }; - let wide = show_in(open, vec2(1280.0, 900.0), false); + let wide = show_in(open_shortcut_import, vec2(1280.0, 900.0), false); let screen = Rect::from_min_size(Pos2::ZERO, vec2(640.0, 480.0)); assert!(wide.window.width() > screen.width(), "Import Shortcut Set is wider than the window: {:?}", wide.window); assert_eq!(wide.whole, [false; 2], "in a large window it does not scroll"); - let shown = show_in(open, screen.size(), false); + let shown = show_in(open_shortcut_import, screen.size(), false); assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window); assert_eq!(shown.whole, [true, false], "it scrolls sideways only"); let sideways: Vec = bars(&shown, true, true).into_iter().filter(|r| r.width() >= 0.5 * shown.window.width()).collect(); assert!(!sideways.is_empty(), "its sideways bar is drawn: {:?}", bars(&shown, true, false)); } + +#[test] +fn a_window_wider_than_the_screen_scrolls_sideways_to_its_right_edge() { + // In a window 70% as wide as the dialog, the dialog scrolls sideways, and scrolled to its right + // edge, the text drawn furthest right in a large window can be seen. + let opens: [(&str, Open); 3] = [ + ("Import Shortcut Set", open_shortcut_import), + ("Keyboard Shortcuts", crate::shortcut_editor::open), + ("Preferences", |app| crate::prefs_dialog::open(app, None)), + ]; + let mut wrong = vec![]; + for (name, open) in opens { + let wide = show_in(open, vec2(1600.0, 1000.0), false); + let Some((right, _)) = texts(&wide) + .into_iter() + .filter(|(_, r, _)| wide.window.contains_rect(*r)) + .map(|(s, r, _)| (s, r.right())) + .max_by(|a, b| a.1.total_cmp(&b.1)) + else { + wrong.push(format!("{name}: no text in the large window")); + continue; + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2((0.7 * wide.window.width()).round(), 1000.0)); + let shown = show_in(open, screen.size(), false); + let scrolled = show_in(open, screen.size(), true); + // Within 1 pt: a text's drawn box can reach a fraction of a point past the content's edge. + let seen = + |shown: &Shown| texts(shown).iter().any(|(s, r, clip)| *s == right && screen.contains_rect(*r) && clip.expand(1.0).contains_rect(*r)); + let sideways = bars(&shown, true, true).into_iter().any(|r| r.width() >= 0.5 * shown.window.width()); + if !screen.contains_rect(shown.window) || !shown.whole[0] || !sideways || seen(&shown) || !seen(&scrolled) { + let at = |shown: &Shown| texts(shown).into_iter().filter(|(s, ..)| *s == right).collect::>(); + wrong.push(format!( + "{name} in {:?}: window {:?}, scrolls {:?}, sideways bar {sideways}, {right:?} seen at first {} {:?}, scrolled {} {:?}, bars {:?}", + screen.size(), + shown.window, + shown.whole, + seen(&shown), + at(&shown), + seen(&scrolled), + at(&scrolled), + bars(&shown, true, true) + )); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// Every text the dialog drew, with its rectangle and its clip. +fn texts(shown: &Shown) -> Vec<(String, Rect, Rect)> { + fn walk(s: &Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) { + match s { + Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect(), clip)), + Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, out)), + _ => {} + } + } + let mut out = vec![]; + shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut out)); + out +} + +#[test] +fn a_dialog_with_buttons_in_its_body_scrolls_them_with_the_body() { + // Check Spelling draws its buttons inside its body: in a window too short for it, the heading + // stays in view and the buttons scroll with the body. + let open: Open = |app| { + check_spelling::open(app).unwrap(); + }; + let tall = show_in(open, vec2(1280.0, 900.0), false); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, (0.6 * tall.window.height()).round())); + let shown = show_in(open, screen.size(), false); + let scrolled = show_in(open, screen.size(), true); + let seen = |shown: &Shown, label: &str| buttons(shown, screen, &[label]).iter().any(|(_, seen)| *seen); + assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window); + assert!(body_bar(&shown).is_some() && shown.whole == [false; 2], "only the body scrolls ({:?}, {:?})", shown.body, shown.whole); + assert!(seen(&shown, "Check Spelling") && seen(&scrolled, "Check Spelling"), "the heading stays in view"); + assert!(!seen(&shown, "Cancel") && seen(&scrolled, "Cancel"), "Cancel is out of view until the body is scrolled down"); +} From f1dbcb9e69733e155079cc9c64b8e1d02ae41d29 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 22:17:29 -0800 Subject: [PATCH 28/33] Part of #5941: Save for Web's Preview in Browser no longer covers the lists With the preview panes at their narrowest (a 640 by 400 window), Preview in Browser was drawn over the Download list. It now goes on a row of its own below the Zoom and Download lists when the panes are too narrow for it beside them. The Save for Web test checks that it clears the list. --- crates/ui-egui/src/dialogs/save_for_web.rs | 23 ++++++++++++++++++---- crates/ui-egui/src/dialogs/tests_scroll.rs | 6 ++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index a214dc108a..86c53e9db9 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -619,6 +619,17 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, set } ui.add_space(6.0); let mut browser = false; + // Preview in Browser goes on a row of its own when the panes are too narrow for it beside the + // two lists (its width as `widgets::secondary_button` draws it). + let label = tl!("Preview in Browser"); + let button_w = (ui.painter().layout_no_wrap(label.to_string(), crate::theme::semibold(12.5), t.text).size().x + 32.0).max(72.0); + let mut beside = false; + let mut button = |ui: &mut egui::Ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, label)); + browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked(); + }); + }; ui.horizontal(|ui| { let z = ZOOMS.iter().position(|z| *z == d.str("__zoom")).unwrap_or(2); let zoom = ui.name_inputs(tl!("Zoom"), |ui| widgets::dropdown(ui, "sfw-zoom", ZOOM_LABELS[z], &ZOOM_LABELS, 110.0)); @@ -635,11 +646,15 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, set { d.fields.insert("__kbps".into(), json!(s)); } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, tl!("Preview in Browser"))); - browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked(); - }); + beside = ui.available_width() >= button_w; + if beside { + button(ui); + } }); + if !beside { + ui.add_space(4.0); + ui.horizontal(button); + } browser } diff --git a/crates/ui-egui/src/dialogs/tests_scroll.rs b/crates/ui-egui/src/dialogs/tests_scroll.rs index 01c9456fa2..bb013802ed 100644 --- a/crates/ui-egui/src/dialogs/tests_scroll.rs +++ b/crates/ui-egui/src/dialogs/tests_scroll.rs @@ -239,6 +239,12 @@ fn save_for_web_in_the_smallest_window_keeps_its_settings_and_buttons_in_view() if !matches!((controls, settings), (Some(c), Some(s)) if c < s) { wrong.push(format!("{size:?}: Preview in Browser ({controls:?}) is left of the settings ({settings:?})")); } + // Preview in Browser is right of the download speed list or on a row below it, not over it. + let button = text_rects(&shown, "Preview in Browser").first().copied(); + let speed = text_rects(&shown, "56.6 Kbps").first().copied(); + if !matches!((button, speed), (Some(b), Some(s)) if b.left() > s.right() + 16.0 || b.top() > s.bottom() + 8.0) { + wrong.push(format!("{size:?}: Preview in Browser ({button:?}) clears the download speed list ({speed:?})")); + } } assert!(wrong.is_empty(), "{wrong:#?}"); } From 285fc75c95e3bf9d02da25452bd3c2ec3f48365d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 22:17:50 -0800 Subject: [PATCH 29/33] Dimension: test each Arrow Style's arrowhead against the expected head The engine test now names the head each style draws (Filled a filled triangle, Open an open triangle, Tick a slash, None no head) instead of comparing the dimension line with ArrowStyle::arrowhead, which the engine itself calls. It moves to crates/engine/tests/it/dimensions.rs. The Arrow Style previews take each style from a constant list in the order of the dropdown entries instead of parsing the entry's value every frame, and a test checks that each entry's value matches its style. Part of #8049. --- crates/engine/tests/it/dimensions.rs | 23 ++++++++++++++++ crates/ui-egui/src/dialogs/dimension.rs | 35 ++++++------------------- 2 files changed, 31 insertions(+), 27 deletions(-) diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 23bbdb0bee..516e87854f 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -95,6 +95,29 @@ fn apply_to_all_restyles_every_dimension_in_one_undo_step() { assert!(s.execute("dimension.applyToAll", &json!({"id":line})).is_err(), "not a dimension"); } +#[test] +fn each_arrow_style_draws_its_stroke_arrowhead_at_both_ends() { + use vectorcraft_doc::Arrowhead; + let mut s = session(); + for (style, head) in + [("filled", Some(Arrowhead::Triangle)), ("open", Some(Arrowhead::TriangleOpen)), ("tick", Some(Arrowhead::Slash)), ("none", None)] + { + let id = run(&mut s, "dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"arrowStyle":style}}))["id"].as_u64().unwrap(); + let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap(); + let heads: Vec<_> = n + .children() + .unwrap() + .iter() + .filter_map(|n| n.appearance.stroke().map(|s| (s.start_arrow.clone(), s.end_arrow.clone()))) + .filter(|(a, b)| a.is_some() || b.is_some()) + .collect(); + match head { + Some(head) => assert!(!heads.is_empty() && heads.iter().all(|h| *h == (Some(head.clone()), Some(head.clone()))), "{style}: {heads:?}"), + None => assert!(heads.is_empty(), "{style}: {heads:?}"), + } + } +} + #[test] fn dimension_angles_circles_arcs_and_curves() { let mut s = session(); diff --git a/crates/ui-egui/src/dialogs/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index bcb56eb4e6..3a977e76c6 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -32,6 +32,8 @@ const UNITS: Choices = &[ ]; const LINE_TYPES: Choices = &[("solid", "Solid"), ("dashed", "Dashed"), ("dotted", "Dotted")]; const ARROWS: Choices = &[("filled", "Filled"), ("open", "Open"), ("tick", "Tick"), ("none", "None")]; +/// The style of each `ARROWS` entry, in the same order. +const ARROW_STYLES: [ArrowStyle; 4] = [ArrowStyle::Filled, ArrowStyle::Open, ArrowStyle::Tick, ArrowStyle::None]; /// The size of an Arrow Style preview: a line with the head at its right end. const ARROW_PREVIEW: egui::Vec2 = egui::vec2(40.0, 16.0); const POSITIONS: Choices = &[("away", "Away from the Line"), ("between", "Between Line and Object")]; @@ -81,9 +83,7 @@ fn arrow_style(ui: &mut Ui, fields: &mut serde_json::Map, id: &st let shown = ARROWS.iter().position(|(v, _)| *v == current); let names: Vec<&str> = ARROWS.iter().map(|(_, s)| tl!(*s)).collect(); let icon = |ui: &Ui, rect: egui::Rect, i: usize, ink: egui::Color32, _: bool| { - if let Some((value, _)) = ARROWS.get(i) - && let Ok(style) = serde_json::from_value::(json!(value)) - { + if let Some(style) = ARROW_STYLES.get(i) { crate::panels::stroke::paint_arrow(ui, rect, style.arrowhead().as_ref(), false, ink); } }; @@ -448,31 +448,12 @@ mod tests { assert!(picture_before(&out, "Tick"), "Properties"); } - /// Each preview shows the stroke head that the dimension line draws at its ends. + /// Each Arrow Style entry previews the style its value names. #[test] - fn arrow_previews_match_the_dimension_line() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - for style in [ArrowStyle::Filled, ArrowStyle::Open, ArrowStyle::Tick, ArrowStyle::None] { - let options = json!({"arrowStyle": style}); - let id = app.run("dimension.create", json!({"a":[10,10],"b":[110,10],"options":options})).unwrap()["id"].as_u64().unwrap(); - let st = app.session.active().unwrap(); - let heads: Vec<_> = st - .doc - .node(vectorcraft_doc::NodeId(id)) - .unwrap() - .children() - .unwrap() - .iter() - .filter_map(|n| n.appearance.stroke().map(|s| (s.start_arrow.clone(), s.end_arrow.clone()))) - .filter(|(a, b)| a.is_some() || b.is_some()) - .collect(); - match style.arrowhead() { - Some(head) => { - assert!(!heads.is_empty() && heads.iter().all(|h| *h == (Some(head.clone()), Some(head.clone()))), "{style:?}: {heads:?}") - } - None => assert!(heads.is_empty(), "{style:?}: {heads:?}"), - } + fn arrow_previews_follow_the_listed_styles() { + assert_eq!(ARROWS.len(), ARROW_STYLES.len()); + for ((value, _), style) in ARROWS.iter().zip(ARROW_STYLES) { + assert_eq!(serde_json::to_value(style).unwrap(), json!(value)); } } } From 84c9d93956e220a09d31c333035c1cf01e49333c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 22:16:05 -0800 Subject: [PATCH 30/33] Symbols: a marquee touches what an instance's fill and stroke effects paint A marquee across the shapes that the geometry effects of a symbol instance's active fill or stroke paint outside its box now selects the instance, as a click there does. An image is likewise touched where its own fills and strokes paint outside its frame. Outline mode keeps the box alone. --- crates/doc/src/hit.rs | 31 +++++++++--- crates/engine/src/tests/expand.rs | 79 ++++++++++++++++++++++++++----- docs/target-app-parity.md | 2 +- 3 files changed, 94 insertions(+), 18 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 6a32a21bbc..93baa85ed8 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -2096,7 +2096,9 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option { /// Objects (children of layers, or of `scope` in isolation mode) touched by a marquee rect, leaving /// out those on a locked artboard ([`crate::LockedArtboards::holds_id`]). Symbol instances are measured /// by their art ([`Node::geometric_bounds_with`]), and outside that box, except in outline, they are -/// touched where the live geometry effects of a clipping path in their art show it. The art of a clip group or of a layer with a +/// touched where the live geometry effects of a clipping path in their art show it, or where the +/// geometry effects of their active fill or stroke reshape the art. Images are also touched, except +/// in outline, where their own fills and strokes paint outside their box. The art of a clip group or of a layer with a /// clipping mask counts only when the marquee meets the region its clipping path clips to, and then /// only within that region's bounds. In isolation mode the clipping mask of the isolated container, /// or of the parent of the single object isolated, does not limit the marquee, as it does not limit @@ -2265,8 +2267,10 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip /// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched /// by the copies it draws, as clicks hit them. Objects of every other kind except paths, - /// compound paths, layers and groups are touched by their box. A clipping path is touched by - /// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]). + /// compound paths, layers and groups are touched by their box, and an image or a symbol + /// instance also where its fills and strokes paint outside it ([`painted_touches`]). A clipping + /// path is touched by its own geometry ([`mask_marquee`]) and on the edge of its region + /// ([`clip_edge_touches`]). fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool) -> bool { // A path or compound path whose geometry effects reshape it, or a group or layer whose own // geometry effects reshape its members, is touched where that art is drawn ([`drawn_art`]). @@ -2296,12 +2300,27 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)), NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)), // A symbol instance is touched by its box, and outside it where the live geometry - // effects of a clipping path in its art show the art. In the art of another instance - // walked outside that instance's box, it is touched only by its own art ([`ArtOnly`]). - NodeKind::SymbolInstance { .. } => !ArtOnly::on() && box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds), + // effects of a clipping path in its art show the art, or where the geometry effects of + // its active fill or stroke reshape the art ([`painted_touches`]). In the art of another + // instance walked outside that instance's box, it is touched only by its own art + // ([`ArtOnly`]) and those shapes. + NodeKind::SymbolInstance { .. } => { + !ArtOnly::on() && box_touches(n, s, r) || !outline && (instance_art_touches(n, s, r, whole_compounds) || painted_touches(n, s, r)) + } + // An image is touched by its box, and outside it where its own fills and strokes paint. + NodeKind::Image(_) => box_touches(n, s, r) || !outline && painted_touches(n, s, r), _ => box_touches(n, s, r), } } + /// Does the marquee `r` touch the shapes that the fills and strokes of image or symbol + /// instance `n` paint ([`image_paint`]), where clicks hit them ([`hit_painted`])? Each shape is + /// touched by its path, as a path is ([`vectorcraft_geom::hit::intersects_rect`]). Only when + /// `r` meets the reach of `n` ([`Node::reach_bounds_with`]). + fn painted_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool { + let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1; + n.reach_bounds_with(s).is_some_and(meets) + && image_paint(Some(s.document()), n).iter().any(|(bp, _, _)| vectorcraft_geom::hit::intersects_rect(&PathData::from_bezpath(bp), r)) + } /// Does the marquee `r` touch the box of `n`? A box with no width or no height (an instance of /// a symbol that draws a straight line) is touched where the marquee crosses it. fn box_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool { diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index 4e8d8697d4..e728754655 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -387,22 +387,79 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() { assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); } +/// An image whose fill Convert to Shape gives a shape, selected. The frame runs from 85 to 115; +/// the fill's shape is 9 pt larger on each side. +fn image_with_shaped_fill(s: &mut Session) -> NodeId { + let mut png = vec![]; + image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let r = run(s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]})); + let im = NodeId(r["ids"][0].as_u64().unwrap()); + run(s, "select.set", json!({"ids": [im.0]})); + run(s, "appearance.addFill", json!({})); + run(s, "paint.setFill", json!({"color": "#0000ff", "item": 0})); + run(s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0})); + im +} + +/// The objects a marquee from `x0` to `x1` across y = 100 touches, as the canvas shows them, in +/// outline with `outline`. +fn marquee_at(s: &Session, x0: f64, x1: f64, outline: bool) -> Vec { + let r = vectorcraft_geom::Rect::new(x0, 90.0, x1, 110.0); + vectorcraft_doc::hit::marquee_in_view(&s.doc().unwrap().doc, r, None, true, outline) +} + +/// A marquee touches a symbol instance where the geometry effects of its fill or stroke paint its +/// art outside its box, as a click there selects it, except in outline. +#[test] +fn a_marquee_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it() { + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + assert_eq!(marquee_at(&s, 38.0, 45.0, false), []); + offset_row(&mut s, id, row, 10.0); + assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill"); + assert_eq!(marquee_at(&s, 30.0, 37.0, false), [], "a marquee past the grown fill"); + assert_eq!(marquee_at(&s, 38.0, 45.0, true), [], "outline mode draws the art as it is"); + + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", false); + offset_row(&mut s, id, row, 10.0); + assert_eq!(marquee_at(&s, 38.0, 42.0, false), [id], "a marquee across the moved stroke"); + assert_eq!(marquee_at(&s, 43.0, 45.0, false), [], "a marquee between the moved stroke and the fill"); + + let mut s = session(); + let (id, row) = nested_instance_with_row(&mut s); + offset_row(&mut s, id, row, 10.0); + assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill of the nested art"); +} + +/// A marquee touches an image where the shape of its own fill lies outside its frame, and an +/// instance of a symbol made of that image where the instance's fill effect grows that shape, as +/// clicks there select them, except in outline. +#[test] +fn a_marquee_on_the_shape_of_an_image_fill_selects_it() { + let mut s = session(); + let im = image_with_shaped_fill(&mut s); + assert_eq!(marquee_at(&s, 74.0, 79.0, false), [im], "a marquee across the fill's shape outside the frame"); + assert_eq!(marquee_at(&s, 70.0, 75.0, false), [], "a marquee past the fill's shape"); + assert_eq!(marquee_at(&s, 74.0, 79.0, true), [], "outline mode draws the frame"); + + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + offset_row(&mut s, id, row, 10.0); + assert_eq!(marquee_at(&s, 64.0, 68.0, false), [id], "a marquee across the instance's grown fill"); + assert_eq!(marquee_at(&s, 58.0, 63.0, false), [], "a marquee past the grown fill"); +} + /// An image in the symbol's art whose fill Convert to Shape gives a shape: the instance's fill /// effect grows what that fill paints, and a click there selects the instance. #[test] fn a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance() { let mut s = session(); - let mut png = vec![]; - image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); - // The frame runs from 85 to 115; the fill's shape is 9 pt larger on each side. - let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]})); - let im = NodeId(r["ids"][0].as_u64().unwrap()); - run(&mut s, "select.set", json!({"ids": [im.0]})); - run(&mut s, "appearance.addFill", json!({})); - run(&mut s, "paint.setFill", json!({"color": "#0000ff", "item": 0})); - run(&mut s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0})); + image_with_shaped_fill(&mut s); let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap()); run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); let row = node(&s, id).appearance.items.len() - 1; diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c767c1e6cc..722f28da77 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1915,7 +1915,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Outline Object on an image's own fill or stroke follows the outline of the image's opaque area, and the image's frame when the image has no transparency. Path effects apply to a fill or stroke added to a bitmap object ([archived reference manual, page 561](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=561)), and with Outline Object such a stroke follows the boundary of the art when the image has transparent areas and the image's frame when it has none ([CreativePro article on strokes for placed images](https://web.archive.org/web/20250815214529/https://creativepro.com/add-strokes-placed-images-illustrator/)). VectorCraft's own rules: the opaque area is the pixels at least 50% opaque, and its outline is traced as Image Trace's Black and White mode traces at threshold 128 and fitted with curves. Evidence: `tests::imageoutline` (vectorcraft-effects), `opaque::tests` (vectorcraft-trace), `tests::containers::an_images_stroke_with_outline_object_follows_its_opaque_area` and `tests::containers::an_images_outline_object_stroke_exports_selects_and_measures_along_its_opaque_area` (vectorcraft-engine), `tests::objectfx::an_images_outline_object_stroke_follows_new_pixels_under_the_same_key` (vectorcraft-render). A geometry effect on one of type's own fills or strokes reshapes the whole outline that the fill or stroke paints, on the canvas and in exports; PDF, SVG, EPS and the other vector exports write such type as paths. On type that holds inline graphics, those effects are drawn and exported only when the type has a geometry effect or perspective of its own. A geometry effect on a symbol instance's fill reshapes the filled shapes of the symbol's art and leaves their strokes as they are; one on the instance's stroke reshapes the stroked shapes and leaves their fills as they are. The shapes keep their colors. Only the instance's topmost fill and topmost stroke count, and only while they are visible with an opacity above 0. The canvas and Object › Expand Appearance use the same art, SVG and PDF export bake the same shapes, and Expand Appearance turns the instance into an editable group in one undo step. A group's own fills and strokes in the art take the effects too. An instance inside the art passes the effects on to its own art, and a dynamic symbol's instance reshapes the fills and strokes it paints on the art. How the effects map onto the symbol's art is VectorCraft's own rule. The help page describes effects on one fill or stroke, and the help page describes Expand Appearance (engine `expand::a_symbol_instance_fill_effect_reshapes_its_filled_art_and_expands`, `a_symbol_instance_stroke_effect_reshapes_its_stroked_art_and_expands`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `only_the_topmost_visible_instance_fill_reshapes_the_art`, `a_nested_symbol_instance_takes_the_outer_fill_effect`, `export_bakes_a_symbol_instance_fill_effect`, `a_fill_effect_on_an_instance_of_a_symbol_that_holds_itself_ends`). Existing documents with a geometry effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. - Effect › Pathfinder takes a symbol instance as the art it draws with the geometry effects of its fill and stroke, as they take a path with such effects: the result painted by the instance's art carries those effects, also when the instance has geometry effects of its own and when the instance sits inside another symbol's art. A click where those effects paint the art outside the instance's bounds selects the instance, a fill only when Selection by Path Only is off, and outline mode still takes the instance's bounds alone. A compound shape's area leaves out its members' fill and stroke effects for symbol instances as for paths, since the compound shape paints the area with its own appearance. These are VectorCraft's own rules (engine `expand::pathfinder_takes_a_symbol_instance_fill_and_stroke_effects`, `a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance`). Before, Pathfinder dropped those effects and clicks took only the instance's bounds. + Effect › Pathfinder takes a symbol instance as the art it draws with the geometry effects of its fill and stroke, as they take a path with such effects: the result painted by the instance's art carries those effects, also when the instance has geometry effects of its own and when the instance sits inside another symbol's art. A click where those effects paint the art outside the instance's bounds selects the instance, a fill only when Selection by Path Only is off, and outline mode still takes the instance's bounds alone. A marquee across those shapes selects the instance too, and a marquee across the shape an image's own fill or stroke paints outside its frame selects the image, except in outline mode. A compound shape's area leaves out its members' fill and stroke effects for symbol instances as for paths, since the compound shape paints the area with its own appearance. These are VectorCraft's own rules (engine `expand::pathfinder_takes_a_symbol_instance_fill_and_stroke_effects`, `a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance`, `a_marquee_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_marquee_on_the_shape_of_an_image_fill_selects_it`). Before, Pathfinder dropped those effects, and clicks and marquees took only the instance's bounds. Live effects inside a symbol's art (geometry effects, color adjustments and the rest that export bakes) are written where each instance places the art in PDF, print, EPS and DXF, as the canvas draws them: the art is placed first and its effects are applied after, so an instance that scales its art does not scale the distance a Transform effect moves it. Symbols nested in the art, a dynamic symbol instance's own paint changes and the stain an instance's fill gives its art are kept, and the art is stained before its effects apply. A linked instance's PDF link covers its art where the effects draw it. A symbol whose art holds itself stops at the nesting limit, and the symbols' own art keeps its effects. An instance stays an instance in these exports when the objects its art makes once baked (the copies a Transform effect makes included) would take the export's placed symbol art past 16,000,000 objects, or when its baked art would draw deeper than the 128 levels a document may draw; these are VectorCraft's own limits. Art baked for an instance that then stays an instance still counts toward that limit, and while an instance's art bakes, the art's own objects are held in the limit for the instances nested in it. Instances the export leaves out (hidden ones, those in hidden groups, on template layers, and on hidden layers or layers that do not print when the export leaves those out) are not placed and do not count toward that limit. Before, these exports wrote the art without its effects (effects `bake::placing_symbols_bakes_their_art_where_each_instance_places_it`, `placing_symbols_reaches_the_art_of_nested_instances`, `placing_a_symbol_that_holds_itself_stops`, `placing_symbols_keeps_dynamic_instances_changes`, `placing_symbols_keeps_the_instances_stain`, `placing_symbols_counts_the_baked_art`, `placing_symbols_counts_nested_art_once`, `placing_symbols_holds_the_outer_art_while_it_bakes`, `placing_symbols_counts_the_art_it_drops`, `placing_symbols_counts_art_dropped_for_depth_against_later_baked_art`, `placing_symbols_keeps_the_baked_art_within_the_drawn_depth`, `placing_symbols_skips_instances_the_export_leaves_out`; doc `depth::tests::drawn_heights_measure_objects_outside_the_layers`; PDF, print, EPS and DXF `symbol_art_effects_are_written_where_they_draw`, `symbol_art_effects_print_where_they_draw`; PDF `a_stained_instance_keeps_its_stain_when_its_art_has_effects`, `a_linked_instance_keeps_its_link_when_its_art_has_effects`). EMF, WMF and SVG export write the same symbol art the same way: an instance of a symbol whose art, or the art of a symbol nested in it, has such effects is written as that art placed by the instance and then baked, so a square that a Transform effect moves 100 pt right draws 100 pt right of where the instance places it at any scale or rotation, and art the effect moves onto the artboard is written. EMF and SVG clip 9-slice cells and WMF does not, as each places other instances. In SVG those instances use no ``, and instances of symbols without such effects still share one; named objects in a symbol's art take no ids there, as in an instance with its own copy of the art, so two instances do not write the same id; with Hidden Layers on, hidden instances are placed too and written hidden. An SVG instance nested in another instance's art is shared through `` only when the transform it is drawn with, the outer instances' included, keeps the shared art as the canvas draws it, so a nested stroke keeps its weight in a scaled instance. Preserve Editing still embeds the document with its live effects. Before, these exports wrote the art without its effects (metafile `tests::import::symbol_art_effects_are_written_where_they_draw`; SVG `symbols_layers::symbol_art_effects_are_written_where_the_canvas_draws_them`, `a_kept_hidden_instance_is_written_with_its_symbols_effects`, `instances_written_as_their_art_give_its_names_no_id`, `a_nested_instance_is_shared_only_under_the_transform_it_is_drawn_with`; effects `bake::placing_symbols_skips_instances_the_export_leaves_out`). EMF and WMF export with Use Artboards applies the document's live effects once for all the chosen artboards instead of once for each, and writes the same files byte for byte (metafile `tests::export_regions_writes_what_each_region_writes_alone`; `export_regions_perf` times it). From 0865242d2fcf4fd6b8586b9aa777767285dfdedc Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Wed, 18 Nov 2026 11:46:27 +0500 Subject: [PATCH 31/33] PDF export: write the document language as the catalog's /Lang (#3644) The writer passed no language to craft-pdf, so exported and printed PDFs had no /Lang and accessibility checkers failed primary-language. Writer::new now passes the BCP 47 tag of the Document Setup language (new vectorcraft_doc::setup::language_tag, en-US by default) through write::Writer::new_with_language, which writes the catalog's /Lang and the XMP dc:language. A language with no tag writes none. /MarkInfo is left for tagged PDF (#3643). --- crates/doc/src/setup.rs | 17 ++++++++++++++++ crates/pdf/src/export/writer.rs | 10 +++++++--- crates/pdf/src/tests.rs | 35 +++++++++++++++++++++++++++++++++ docs/file-format-parity.md | 5 +++-- docs/gaps.md | 5 +++-- docs/roadmap.md | 5 +++-- docs/target-app-parity.md | 5 +++-- 7 files changed, 71 insertions(+), 11 deletions(-) diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index 4dd8394ce2..e91542fe1a 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -220,6 +220,13 @@ pub fn language_quotes(language: &str) -> Option { LANGUAGES.iter().find(|(l, _, _)| l.eq_ignore_ascii_case(language)).map(|(_, _, q)| *q) } +/// The BCP 47 tag of the [`LANGUAGES`] entry named or tagged `language` (case-insensitive), the +/// default's included (`en-US`): what a document's language ([`DocSetup::language`]) is written +/// as in an exported file. `None` for a language not in the list. +pub fn language_tag(language: &str) -> Option<&'static str> { + LANGUAGES.iter().find(|(n, t, _)| n.eq_ignore_ascii_case(language) || t.eq_ignore_ascii_case(language)).map(|(_, t, _)| *t) +} + /// 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. @@ -404,6 +411,16 @@ impl DocSetup { mod tests { use super::*; + /// A document's language is written by its tag, the default's included (#3644). + #[test] + fn document_languages_have_their_tags() { + assert_eq!(language_tag(&DocSetup::default().language), Some("en-US")); + assert_eq!(language_tag("French"), Some("fr")); + assert_eq!(language_tag("german: swiss"), Some("de-CH")); + assert_eq!(language_tag("sr-latn"), Some("sr-Latn")); + assert_eq!((language_tag("Klingon"), language_tag("")), (None, None)); + } + /// Characters store a language of the list by its tag, the default as none. #[test] fn char_languages_are_stored_by_tag() { diff --git a/crates/pdf/src/export/writer.rs b/crates/pdf/src/export/writer.rs index b7c967989e..bd241421c7 100644 --- a/crates/pdf/src/export/writer.rs +++ b/crates/pdf/src/export/writer.rs @@ -64,8 +64,8 @@ pub(crate) struct Sheet<'a> { impl Writer { /// A PDF with `set`'s version, standard, compression and colour output, and `doc`'s metadata - /// under `title`, created at `created` (Unix seconds). With `cmyk`, transparency blends in - /// CMYK (unless the colours are converted to RGB). + /// and language under `title`, created at `created` (Unix seconds). With `cmyk`, transparency + /// blends in CMYK (unless the colours are converted to RGB). pub(crate) fn new(doc: &Document, set: &crate::PdfSettings, title: &str, created: Option, cmyk: bool) -> Result { let out = ColorOut::new(doc, set)?; let mut warnings = out.profile_notes.clone(); @@ -111,7 +111,11 @@ impl Writer { created: created.map(date_time), modified: None, }; - let pdf = write::Writer::new(settings, metadata); + // The document language (Document Setup) as the catalog's `Lang` and the XMP packet's + // `dc:language` (ISO 32000-1, 14.9.2): its BCP 47 tag. A language without a tag writes + // none rather than a guess. + let language = vectorcraft_doc::setup::language_tag(&doc.setup.language).map(str::to_string); + let pdf = write::Writer::new_with_language(settings, metadata, language); Ok(Self { pdf, cmyk: out.blends_cmyk(cmyk), diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 91c037ad84..e2abe87637 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -1449,6 +1449,41 @@ fn empty_and_populated_file_info_preserve_key_presence() { assert!(s.contains("/ViewerPreferences<>"), "viewers should show the document title (#3646)"); } +/// The text of the `/Lang` entry of the catalog of `pdf` (a literal string), if any. +fn catalog_lang(pdf: &[u8]) -> Option { + let xref = crate::patch::Xref::read(pdf).expect("a cross-reference table"); + let root = xref.trailer_ref(pdf, b"/Root").expect("a catalog"); + let (start, end) = xref.dict(pdf, root).expect("the catalog's dictionary"); + let catalog = String::from_utf8_lossy(&pdf[start..end]).into_owned(); + let at = catalog.find("/Lang")? + "/Lang".len(); + let rest = catalog[at..].trim_start().strip_prefix('(').expect("a literal string"); + Some(rest[..rest.find(')').expect("a closed string")].to_string()) +} + +/// The catalog gives the document language chosen in Document Setup as its BCP 47 tag, in +/// exported and printed PDFs, and the XMP packet says it too (#3644). +#[test] +fn the_catalog_gives_the_document_language() { + let mut d = doc(100.0, 100.0); + for (language, tag) in [(None, "en-US"), (Some("French"), "fr"), (Some("German: Swiss"), "de-CH")] { + if let Some(language) = language { + d.setup.language = language.into(); + } + for opts in [PdfOptions::uncompressed(), PdfOptions::default()] { + let bytes = export(&d, &opts).unwrap(); + assert_eq!(catalog_lang(&bytes).as_deref(), Some(tag), "{language:?}"); + } + // Print to PDF writes its file with the same writer. + let printed = print(&d, &PrintOptions { created: Some(1_700_000_000), ..Default::default() }).unwrap(); + assert_eq!(catalog_lang(&printed.bytes).as_deref(), Some(tag), "{language:?}: printed"); + let s = uncompressed(&d); + assert!(s.contains(&format!("{tag}")), "{language:?}: {s}"); + } + // A language without a tag (from a file) writes none rather than a guess. + d.setup.language = "Klingon".into(); + assert_eq!(catalog_lang(&export(&d, &PdfOptions::uncompressed()).unwrap()), None); +} + /// A function or colour space built on itself is refused before the interpreter builds it (by /// recursion, with no cap: a stack overflow), and those of real files are read. #[test] diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 91af8cd7b3..36e73837d8 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-17 · **Change:** minor (PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (PDF export writes the document language as the catalog's `/Lang`, #3644; PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). @@ -315,7 +315,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | 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 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 (authored ActualText in editable import, #6165; 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; Import PDF pages as links opens each page as a placed document linked to it, on its own artboard, `tests/placed_document.rs`, and is checked when All is picked and cleared when Range is picked) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X) | 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); an image mask (`/ImageMask true`) painted in a solid color opens as a grayscale image colorized by that color, a spot color keeping its swatch and tint, so Fill and Recolor Artwork reach it, and the same mask painted again in another color keeps that color (#6313); an image in a Separation space opens as a grayscale image of its tints colorized by its ink at 100 % (a spot swatch, a process plate or Registration), its soft mask as its opacity mask (#6314); a DeviceN image of one colorant opens the same way, and one of process plates only (the ink `None` may be among them) opens in CMYK with each colorant's tint in its plate (#6348) PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | +| PDF | open, place, save | yes (authored ActualText in editable import, #6165; 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; Import PDF pages as links opens each page as a placed document linked to it, on its own artboard, `tests/placed_document.rs`, and is checked when All is picked and cleared when Range is picked) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X; the document language as the catalog's `/Lang` and XMP `dc:language`, #3644) | 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); an image mask (`/ImageMask true`) painted in a solid color opens as a grayscale image colorized by that color, a spot color keeping its swatch and tint, so Fill and Recolor Artwork reach it, and the same mask painted again in another color keeps that color (#6313); an image in a Separation space opens as a grayscale image of its tints colorized by its ink at 100 % (a spot swatch, a process plate or Registration), its soft mask as its opacity mask (#6314); a DeviceN image of one colorant opens the same way, and one of process plates only (the ink `None` may be among them) opens in CMYK with each colorant's tint in its plate (#6348) PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CIDFonts the file doesn't carry not drawn, but for those over a predefined CMap (`UniJIS-UCS2-H`, `90ms-RKSJ-H`, `GBK-EUC-H`, `KSCms-UHC-H`, `ETen-B5-H`), set as type in the font of the CIDFont's name, vertical over a `-V` CMap; a name that ends in the row-and-cell CMap `H` or `V` splits off the CMap only when the file defines the CIDFont of that name, the CIDFont is `Ryumin-Light` or `GothicBBB-Medium` (the Japanese CIDFonts a printer carries), or the name has a hyphen and an installed face that covers Japanese has it; name-keyed fonts in a FontSet set as type by name; #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); an embedded Type 1 font's encrypted part is read for its glyphs, which space its type, outline it and draw glyphs without a character, in plain and composite fonts; a Type 42 font that carries its TrueType font gives each code its character by its glyph name or, for names that say nothing (`/g12`), by the glyph's entry in the font's own character map, spaces its type by its own widths and draws glyphs that stand for no character from its outlines; the show operators' spacing along the baseline (`ashow`, `widthshow`, `xshow`, `yshow`, `xyshow`, and the moves of `kshow`'s procedure, run between each two characters) is kept on live type as tracking, so type in a font that isn't installed keeps the file's line lengths (spacing that moves characters off the baseline, as `yshow`, `xyshow` or a `kshow` procedure can, places each character as its own text object); composite (Type 0) fonts with the 8/8 mapping, as PDF-to-PostScript converters write two-byte fonts, draw a Type 42 descendant's glyphs from the TrueType outlines it carries and an embedded Type 1 descendant's from its charstrings, and set other descendants' characters as type at the composite font's size (other mappings are still set as type in the font of their name); CID-keyed fonts (`composefont`, `FMapType` 9 over a CMap built with the CIDInit operators or `Identity-H`/`Identity-V`; `bfchar` and `bfrange` mappings give a base-font descendant its codes or glyph names) draw the glyphs of the Type 0 CIDFonts (Type 1 charstrings in their `StartData` binary data or `GlyphDirectory`) and Type 2 CIDFonts (TrueType glyphs through `CIDMap`) they carry, and the CID-keyed fonts of a FontSet's Compact Font Format data (Type 2 charstrings); 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); sampled functions (type 0) interpolate between their samples, multilinearly or by cubics with `Order 3`, and a sampled axial or radial gradient has a stop at each sample; a gradient the page paints as a row of abutting one-colour strips (as Level 2 writers draw smooth shades) imports as one linear gradient, without the seams the strips leave when each is drawn alone; 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` | | DCS 1.0 / 2.0 | place linked | place linked only (one image of the plates; spot plates as spot swatches; the composite's clipping path; each plate on its own ink in Separations Preview and print separations) | no | `crates/eps/src/dcs/tests.rs`, `crates/engine/src/tests/dcs.rs` | @@ -383,6 +383,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | PDF export (#3644): the document language chosen in Document Setup is written as the catalog's `/Lang` (BCP 47, `en-US` by default) and as XMP `dc:language`; a language without a tag writes none. Scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | | 2026-11-16 | minor | PDF import: fill and stroke rendering (text rendering modes 2 and 6) draws all the glyphs of a text-showing operator (`Tj`, `TJ`, `'`, `"`) filled, then the same glyphs stroked, so a word shown at once came in as two type objects: a stroke-only copy over a fill-only one. Each stroke is now matched, in order, to the glyph filled with the same placement (where, how large, how wide, slanted and turned) in the same font with the same text on the line, and only that glyph takes the stroke, so the word comes in as one type object, filled and stroked; glyphs stroked with another join part way through still split into runs of their own, and stroked type over no filled glyph (modes 1 and 5) stays stroke only (#8015; `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`, `a_vertical_column_filled_then_stroked_is_one_filled_and_stroked_type` in `crates/pdf/src/tests/text_placement.rs`). Scores and estimates unchanged. | diff --git a/docs/gaps.md b/docs/gaps.md index 5dee50afa1..304535dacb 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged. @@ -36,6 +36,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | G19: PDF export writes the document language chosen in Document Setup as the catalog's `/Lang` (its BCP 47 tag, `en-US` by default) and the XMP packet's `dc:language`, in exported and printed PDFs (#3644); `/MarkInfo` stays with tagged PDF (#3643). Scores and estimates unchanged. | | 2026-11-16 | minor | G1: Recolor Artwork - native Lab entry in Color Picker, swatch libraries access in Color Picker, and row right-click context menu ("Pick from Swatches", "Limit to Library") (#4028); scores and estimates unchanged. | | 2026-11-15 | minor | G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `ui.checkSpelling`, #4936) with Not in Dictionary sentence context, suggestions, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done/Cancel, keyboard navigation, and one-step Undo/Redo; spell check complete; scores and estimates unchanged. | | 2026-11-15 | minor | G5: Neon & Glow joins Shadows and Glows, Outlines and Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD and Status Effects as an eleventh built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor; original procedural styles generated in code); estimate unchanged (3–13 h). | @@ -869,7 +870,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** AccessKit is on by default, so egui widgets reach screen readers, but custom panels, the canvas and its objects aren't described and nothing has been tested with VoiceOver, Narrator or Orca; keyboard-only canvas operation; high contrast. Illustrator's own accessibility is limited, so this is mostly beyond parity. -- **Done:** PDF export writes `/ViewerPreferences << /DisplayDocTitle true >>` when File Info has a Document Title (or an explicit export title is supplied), so viewers and accessibility checkers use that title instead of the file name (#3646). +- **Done:** PDF export writes `/ViewerPreferences << /DisplayDocTitle true >>` when File Info has a Document Title (or an explicit export title is supplied), so viewers and accessibility checkers use that title instead of the file name (#3646). It writes the document language chosen in Document Setup as the catalog's `/Lang` (its BCP 47 tag, `en-US` by default) and the XMP packet's `dc:language`, so screen readers and checkers know the language (#3644). Tagged PDF (structure tree, `/MarkInfo`) is still missing (#3643). - **Estimate:** 15–25 h. ## Highlighted-text Eyedropper (2026-10-21) diff --git a/docs/roadmap.md b/docs/roadmap.md index 3c09bde829..2e9fe39fe9 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -59,6 +59,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | M14: PDF export writes the document language (Document Setup) as the catalog's `/Lang` (#3644). Scores and estimates unchanged. | | 2026-11-13 | minor | Graphic Styles: in a panel made taller the list fills the space above the footer instead of stopping at 220 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/graphic_styles.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke instead of being left out, adding no text (#6971; `empty_actual_text_keeps_the_glyphs_art` in `crates/pdf/src/tests/actual_text.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | Library panels (swatch, Color Book, brush, symbol and graphic style libraries): in a panel made taller the list fills the space above the footer instead of scrolling inside 220 or 280 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/library_panel/tests.rs`). Scores and estimates unchanged. | @@ -173,7 +174,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with 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; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | -| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12) | 18–28 | +| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | | M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c767c1e6cc..6eafff331e 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-17 · **Change:** minor (Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -63,6 +63,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | Hardening: PDF export writes the document language (Document Setup) as the catalog's `/Lang` and XMP `dc:language` (#3644). Scores and estimates unchanged. | | 2026-11-17 | minor | Distort & Transform › Twist: handles follow the rotation's derivative, so a strongly twisted path is a smooth spiral instead of pieces meeting at kinks (#7069; `twist_joins_its_pieces_smoothly` in `crates/effects/src/tests.rs`). Scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | @@ -549,7 +550,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Libraries, Links, Package | 2 | 82% | the Libraries panel is local only (no cloud by design: libraries are files on this machine) and has no shared libraries, linked graphics or gradients and patterns as items yet; its graphics, colours and text styles (#745), its search, groups and library export/import as `.vclibrary` files (#926), a list that scrolls, with items and groups reordered by dragging and items dragged into and out of groups, art and swatches dragged in added where they are dropped, and items shown as icons or in a list with their names, are done; Links and Package are done; placed VectorCraft documents are done (linked by default, vectors in every output, previews, Break Link, Expand, Edit Original, refresh on save) | 2–3 | | **Feature parity** | **103** | **~75%** | | **~210–330** | | Interaction-fidelity pass (side by side with Illustrator: every tool modifier, cursor, dialog, Properties context) | | | | 60–90 | -| Hardening (big-file corpus, fuzzing, cross-platform and browser QA, accessibility, packaging) | | | Bounded control socket waits (#1726); PngSuite pinned-file integrity and download budgets verified (#1729); RPM runtime capabilities and glibc floor checked (#1275); titled PDF exports ask viewers to display the document title (#3646); real-distro installation/start-up QA pending | 50–80 | +| Hardening (big-file corpus, fuzzing, cross-platform and browser QA, accessibility, packaging) | | | Bounded control socket waits (#1726); PngSuite pinned-file integrity and download budgets verified (#1729); RPM runtime capabilities and glibc floor checked (#1275); titled PDF exports ask viewers to display the document title (#3646); PDF exports give the document language as the catalog's `/Lang` (#3644); real-distro installation/start-up QA pending | 50–80 | | **Full parity** | | **~56%** | | **~320–500** | _Inventories (2026-10-07):_ 13 menu items still stubbed (`todo(…)` in `crates/ui-egui/src/menus.rs`); every tool From c24f1fc5a550d9fdf5da059c3ce3676c4c242d53 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 22:49:09 -0800 Subject: [PATCH 32/33] Fields: range and mixed fields refuse text that reads as no number A range, mixed or spinner field that committed text it could not read (`abc`, `(10+5)*2`) returned nothing and did not mark the commit as refused. Enter in such a field then confirmed an open dialog with the old value, and in Save for Web's Optimize to File Size rows it ran the search with the old size. The field now refuses that text as unit fields do: it flashes, shows its value again, and the Enter does not confirm the dialog. --- crates/ui-egui/src/widgets/look_tests.rs | 25 ++++++++++++++++++++++++ crates/ui-egui/src/widgets/numeric.rs | 14 ++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/widgets/look_tests.rs b/crates/ui-egui/src/widgets/look_tests.rs index c6c241e504..0b89811929 100644 --- a/crates/ui-egui/src/widgets/look_tests.rs +++ b/crates/ui-egui/src/widgets/look_tests.rs @@ -524,3 +524,28 @@ fn kerning_reads_parentheses_around_its_text_with_a_manual_value_too() { assert_eq!(typed(automatic, "(1,5)"), Some(SpinPick::Value(1.5)), "a decimal comma, automatic: {automatic}"); } } + +/// Enter on text that reads as no number in a range field refuses it as a unit field does: the +/// field flashes and an open dialog is not confirmed with the old value. +#[test] +fn a_range_field_refuses_text_that_reads_as_no_number() { + let typed = |text: &str| { + let ctx = themed(Default::default()); + let picked = std::cell::Cell::new(None); + let mut add = |ui: &mut Ui| { + if let Some(v) = range_field(ui, "count", 12.0, 0.0..=100.0, "", 0, 80.0) { + picked.set(Some(v)); + } + }; + arm_field_focus(&ctx, "count"); + frame(&ctx, 0.0, vec![], &mut add); + frame(&ctx, 0.1, vec![], &mut add); + let enter = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + frame(&ctx, 0.2, vec![egui::Event::Text(text.into()), enter(true), enter(false)], &mut add); + let refused = ctx.data_mut(|d| d.remove_temp::(dialog_reject_commit_flag())).unwrap_or(false); + (picked.get(), refused) + }; + assert_eq!(typed("40"), (Some(40.0), false), "a number commits"); + assert_eq!(typed("abc"), (None, true), "text that reads as no number is refused"); + assert_eq!(typed("(10+5)*2"), (None, true), "parentheses the field doesn't read are refused"); +} diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index 01ce18757f..a9d4020ab3 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -917,7 +917,19 @@ fn bounded_field_reading( let stepped = step_value(ui, &resp, &mut buf, bounds, (read, show), step, &[]).map(|v| round_to(v, decimals)); let scrubbed = scrub::field(ui, id, rect, &buf, value, decimals, bounds); if commit && buf != shown { - read(&buf) + let typed = read(&buf); + if typed.is_none() { + // Text that reads as no number is refused as [`unit_field_from`] refuses it: the field + // flashes, shows its value again, and an open dialog is not confirmed by this Enter. + let end = ui.input(|i| i.time + 0.25); + ui.data_mut(|d| { + d.remove::(id); + d.insert_temp(id.with("invalid-flash"), end); + }); + crate::widgets::reject_dialog_commit(ui.ctx()); + ui.ctx().request_repaint(); + } + typed } else if let Some(v) = stepped.or(scrubbed).filter(|&v| Some(v) != value) { Some(v) } else if live && resp.changed() { From 8905b4361a3ae6824c9845e5debfdef1b4249415 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 22:53:59 -0800 Subject: [PATCH 33/33] Docs: name the engine test that covers the Arrow Style arrowheads --- 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 daf4f1f70d..0bee0adc16 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -631,7 +631,7 @@ since 2026-10-01. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. **Drawing tools, Dimension tool points land on dimensions already drawn (#8063):** By VectorCraft's own rule, with Smart Guides or Snap to Point on, a Linear point that no anchor of the art within 8 pixels takes lands on the end of a visible, unlocked dimension's dimension line, or on the far end of its extension line, within 8 pixels, and a point that nothing else places lands on the closest point of such a line within 8 pixels, so at any zoom a dimension can start where another one ends. The end of an extension line next to the point it measures does not pull points away from that anchor. With Smart Guides and Anchor/Path Labels on, a point on an anchor or line end shows the "anchor" label and a point on a segment or line shows the "path" label. `linear_picks_land_on_anchors_paths_and_drawn_dimensions` and `an_anchor_beside_a_drawn_dimension_takes_the_point` cover it. **Drawing tools, Dimension tool dimensions selected with their art keep their lines and label:** Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave a dimension selected with art it measures, directly or in selected groups without fills, strokes or effects of their own, as it is and change only the other art; when the new art no longer fits its link, the dimension stays where it was, no longer linked, and undo links it again. `expand_leaves_a_dimension_selected_with_its_art_as_it_is`, `expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is`, `outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is`, `a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing`, `a_group_effect_expanded_reaches_the_dimension_it_holds`, `expand_keeps_a_dimension_in_its_asset_and_its_variable_binding`, `a_dimension_keeps_no_link_to_the_art_expand_replaced`, `a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced`, `a_dimension_outlasts_the_stroke_expand_outlined` and `expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art` cover it. -**Drawing tools, Dimension tool Arrow Style shows each arrowhead (#8049):** The Arrow Style dropdown in Dimension Tool Options and in the Properties panel's Dimension section draws each style's arrowhead at the end of a short line before its name, in the open list and in the closed field, using the Stroke panel's arrowhead previews. Filled, Open, Tick and None are the same four styles, saved as before. `arrow_style_shows_a_drawn_arrowhead` and `arrow_previews_match_the_dimension_line` cover it. +**Drawing tools, Dimension tool Arrow Style shows each arrowhead (#8049):** The Arrow Style dropdown in Dimension Tool Options and in the Properties panel's Dimension section draws each style's arrowhead at the end of a short line before its name, in the open list and in the closed field, using the Stroke panel's arrowhead previews. Filled, Open, Tick and None are the same four styles, saved as before. `arrow_style_shows_a_drawn_arrowhead` and `each_arrow_style_draws_its_stroke_arrowhead_at_both_ends` cover it. **Drawing tools, Line Segment from one curve onto a common tangent of another:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a Line Segment drag pressed anywhere on a convex closed path with curves and dragged to within the snapping tolerance of another such path lands on a common tangent of the two ([tangent lines to circles](https://en.wikipedia.org/wiki/Tangent_lines_to_circles)): both ends move to where the line touches the paths, the start sliding along the first path, and each end shows the "tangent" label when Anchor/Path Labels is on, with the line drawn as a guide when Alignment Guides is on. The line is the tangent whose touch point on the second path is nearest the pointer, so moving the pointer around the second path switches between the outer tangent and the one crossing between the paths. The start stays where it was pressed when Shift, Alt or Space is held, when an anchor, center or crossing lies nearer the pointer than the second path does, when the press snapped to an anchor, center or crossing off the first path, when Snap to Tangent is off, when Snap to Grid or pixel snapping places drawn points, or when either path bends inward somewhere or has more than 512 segments. `a_line_from_one_circle_to_another_lands_on_their_common_tangent`, `a_line_from_a_turned_ellipse_lands_on_its_tangent_with_a_circle`, `a_line_near_the_second_path_takes_the_tangent_touching_it_nearest`, `a_line_keeps_its_start_without_a_tangent_snap`, `a_line_to_a_crescent_or_from_an_anchor_beside_the_curve_keeps_its_start` and `a_line_segment_drag_draws_the_common_tangent_as_one_undo_step` cover it. **Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views:** `live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle` checks every TraceView, geometric and visual bounds and rotated result bounds. `live_trace_selection_highlight_excludes_the_retained_source_rectangle` checks result highlights and the existing ordinary-group policy. Shared editing-child traversal also preserves Shaper handling. **Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards:** Shared existing preset definitions are reused; no external preset assets are added. Presets preserve each selected artboard's orientation, and orientation choices apply even when the active board already matches. Fit operations draft bounds until OK, affect only the active artboard and leave artwork in place. Regression coverage checks draft/Cancel, selected-set application, active-only fitting and Undo.