From dbf10b856e8f3340009096737ab1f34916c7bc17 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:35:34 +0530 Subject: [PATCH 01/14] Fix locked item and group import from Illustrator files (#9176) --- crates/eps/src/import/ai/read/ops.rs | 5 +- crates/eps/src/import/native.rs | 2 +- crates/eps/src/import/native/layers.rs | 94 +++++++++++++++++- crates/eps/src/import/native/slots.rs | 3 + crates/eps/src/import/tests_native.rs | 130 +++++++++++++++++++++++++ crates/pdf/src/import_scan.rs | 65 +++++++++++-- crates/pdf/src/pages.rs | 67 +++++++++++-- crates/pdf/src/tests/import_layers.rs | 105 ++++++++++++++++++++ crates/pdf/tests/import_layers.rs | 53 ++++++++++ 9 files changed, 505 insertions(+), 19 deletions(-) create mode 100644 crates/pdf/tests/import_layers.rs diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 65875c5a52..f267de09fb 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -352,7 +352,7 @@ impl<'a> Reader<'a> { } } "Xw" => self.gs.hidden = Self::nums(&vals).last() == Some(&1.0), - "A" => self.gs.locked = Self::nums(&vals).last() == Some(&1.0), + "A" => self.gs.locked = Self::nums(&vals).last().is_some_and(|&v| v != 0.0), "XW" => self.state_marker(&vals, hidden), // Gradients. "Bd" => self.gradient_def = GradientDef::begin(&vals, &mut self.names), @@ -951,9 +951,12 @@ impl<'a> Reader<'a> { let Some(mut look) = f.children.pop() else { return }; let state = (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape); (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape) = (1.0, BlendMode::Normal, false, Knockout::Neutral, false); + let (visible, locked) = (object.visible, object.locked); (object.opacity, object.blend, object.isolate, object.knockout_shape) = (1.0, BlendMode::Normal, false, false); let mut group = Node::group(self.doc.alloc_id(), vec![Arc::new(look), Arc::new(object)]); (group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = state; + group.visible = visible; + group.locked = locked; self.text_looks.insert(group.id); if let Some(f) = self.frames.last_mut() { f.children.push(group); diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index dad13c569f..3cd6105029 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -43,7 +43,7 @@ use super::ate::{Story, Texts}; mod build; pub(super) mod compare; -mod layers; +pub(super) mod layers; mod plan; mod slots; diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index d46da2b8ff..d74029e0f0 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -172,6 +172,8 @@ pub fn layered_ai_from( } // The PDF part, its pages placed and named as the editing data's artboards are, when the // layers can't be used (`why`). + let structure = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)); + let private_layers = structure.as_ref().ok().map(|s| s.doc.layers.clone()).unwrap_or_default(); let from_pdf_part = |mut visible: Document, mut warnings: Vec, why: &str| { let mut read = ai::Names::new(names); let mut board_names = ai::Names::new(names); @@ -179,6 +181,7 @@ pub fn layered_ai_from( if place_pages(&boards, active, &mut visible, unit) { read.absorb(board_names); } + apply_private_layer_locks(&mut visible.layers, &private_layers); let have = visible.patterns.len(); let own_palette = use_palette(&data, &mut visible, &mut read); use_brushes(&data, &mut visible, have, &mut warnings, &mut read); @@ -192,7 +195,7 @@ pub fn layered_ai_from( // The envelopes of type the page doesn't hold against layers that don't draw as it, and how many // envelopes of type the layers had. let (mut free, mut count) = (None, 0); - let built = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)).and_then(|structure| { + let built = structure.and_then(|structure| { count = structure.warped_type.envelope_count(); build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text) }); @@ -238,6 +241,95 @@ fn holds_type_envelope(nodes: &[Arc]) -> bool { }) } +/// Apply lock states from private data layers to visible PDF layers. +pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], private_layers: &[Arc]) { + if private_layers.is_empty() { + return; + } + let mut priv_layer_names = std::collections::HashMap::new(); + for p in private_layers { + if let Some(name) = p.name.as_deref() { + *priv_layer_names.entry(name).or_insert(0usize) += 1; + } + } + + let same_len = visible_layers.len() == private_layers.len(); + for (i, vis) in visible_layers.iter_mut().enumerate() { + let priv_node = if let Some(vis_name) = vis.name.as_deref() { + if priv_layer_names.get(vis_name).copied() == Some(1) { + private_layers.iter().find(|p| p.name.as_deref() == Some(vis_name)) + } else if same_len && private_layers[i].name.as_deref() == Some(vis_name) { + Some(&private_layers[i]) + } else { + None + } + } else if same_len { + Some(&private_layers[i]) + } else { + None + }; + + if let Some(p) = priv_node { + apply_node_locks(Arc::make_mut(vis), p); + } + } +} + +fn apply_node_locks(vis: &mut Node, priv_: &Node) { + if priv_.locked { + vis.locked = true; + } + if let (Some(vis_kids), Some(priv_kids)) = (vis.children_mut(), priv_.children()) { + let mut priv_name_counts = std::collections::HashMap::new(); + for p in priv_kids { + if let Some(name) = p.name.as_deref() { + *priv_name_counts.entry(name).or_insert(0usize) += 1; + } + } + let mut matched_priv = vec![false; priv_kids.len()]; + let mut matched_vis = vec![false; vis_kids.len()]; + + // Pass 1: resolve unique named matches first. + for (v_idx, v) in vis_kids.iter_mut().enumerate() { + if let Some(v_name) = v.name.as_deref() + && priv_name_counts.get(v_name).copied() == Some(1) + && let Some((p_idx, p)) = priv_kids.iter().enumerate().find(|(_, p)| p.name.as_deref() == Some(v_name)) + { + apply_node_locks(Arc::make_mut(v), p); + matched_priv[p_idx] = true; + matched_vis[v_idx] = true; + } + } + + // Pass 2: positional match for remaining children when counts match. + let same_len = vis_kids.len() == priv_kids.len(); + if same_len { + for (idx, v) in vis_kids.iter_mut().enumerate() { + if matched_vis[idx] { + continue; + } + if !matched_priv[idx] && (priv_kids[idx].name.is_none() || v.name == priv_kids[idx].name) { + apply_node_locks(Arc::make_mut(v), &priv_kids[idx]); + matched_priv[idx] = true; + matched_vis[idx] = true; + } + } + } + + // Pass 3: match remaining unmatched unnamed children. + for (v_idx, v) in vis_kids.iter_mut().enumerate() { + if matched_vis[v_idx] || v.name.is_some() { + continue; + } + if let Some((p_idx, p)) = priv_kids.iter().enumerate().find(|(i, p)| !matched_priv[*i] && p.name.is_none()) { + apply_node_locks(Arc::make_mut(v), p); + matched_priv[p_idx] = true; + matched_vis[v_idx] = true; + } + } + } +} + /// The `.ai` whose editing copy is `private` (as [`layered_ai`] takes it) from its layers alone, /// without its PDF part, whose pages (each its trim box in points, width and height) are `pages` /// and are in units of `unit` points (its first page's `UserUnit`): the document and the notes of diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index ebd6deef88..902811af45 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -342,6 +342,8 @@ pub(super) fn fill_slots( (p.opacity, p.blend, p.isolate, p.knockout, p.knockout_shape) = (state.0, state.1, state.2, state.3, shape); } else if transparent { let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); + group.visible = visible; + group.locked = locked; (group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = (state.0, state.1, state.2, state.3, shape); parts.push(Arc::new(group)); @@ -352,6 +354,7 @@ pub(super) fn fill_slots( if parts.len() > 1 { let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); group.visible = visible; + group.locked = locked; parts.push(Arc::new(group)); } for p in &mut parts { diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index f809141202..7118d08481 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8312,3 +8312,133 @@ fn trusted_editing_data_keeps_an_artboard_taller_than_its_pdf_page() { let (_, w, read) = crate::layered_ai(&private(&art), Document::new(12000.0, 14400.0), vec![], false, true, 1.0); assert!(!read, "the uncapped dimension must still match: {w:?}"); } + +/// A locked layer as the format writes it. +fn locked_layer(name: &str, body: &str) -> String { + format!("%AI5_BeginLayer\n1 1 0 1 0 0 1 0 79 128 255 0 50 0 Lb\n({name}) Ln\n{body}\nLB\n%AI5_EndLayer--\n") +} + +#[test] +fn ai_locked_layers_and_groups_preserve_locks() { + let art_locked_group = format!("1 A\nu\n{}\nU\n0 A", square(10, 10)); + let plain_layer = layer("Unlocked Layer", true, &square(0, 0)); + let locked_l = locked_layer("Locked Layer", &art_locked_group); + let n = native(&format!("{plain_layer}{locked_l}")); + let file = private(&n); + let (doc, notes, read) = crate::layered_ai(&file, pdf_part(10.0, 86.0), vec![], false, true, 1.0); + assert!(read, "{notes:?}"); + let unlocked = doc.layers.iter().find(|l| l.name.as_deref() == Some("Unlocked Layer")).unwrap(); + let locked = doc.layers.iter().find(|l| l.name.as_deref() == Some("Locked Layer")).unwrap(); + assert!(!unlocked.locked, "Unlocked Layer is not locked"); + assert!(locked.locked, "Locked Layer retains locked == true"); + let group = locked.children().and_then(|c| c.iter().find(|n| matches!(n.kind, NodeKind::Group { .. }))); + assert!(group.is_some_and(|g| g.locked), "group with 1 A retains locked == true"); +} + +#[test] +fn ai_fallback_to_pdf_part_preserves_private_stream_layer_and_group_locks() { + use std::sync::Arc; + let art_locked_group = format!("1 A\nu\n%_/ArtDictionary :\n%(Locked Subgroup) /String (AIArtName) ,\n%_;\n{}\nU\n0 A", square(10, 10)); + let locked_l = locked_layer("Map Layer", &art_locked_group); + let n = native(&locked_l); + let file = private(&n); + let mut pdf = Document::new(100.0, 100.0); + pdf.layers.clear(); + let mut vis_layer = Node::layer(pdf.alloc_id(), "Map Layer", LayerColor::Preset(0)); + vis_layer.locked = false; + let mut vis_group = Node::group(pdf.alloc_id(), vec![]); + vis_group.name = Some("Locked Subgroup".to_string()); + vis_group.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_group)); + } + pdf.layers.push(Arc::new(vis_layer)); + + let layers = crate::AiLayers::decode(&file); + let (doc, _notes, read) = crate::layered_ai_from(layers, pdf, vec![], false, false, 1.0, crate::NameEncoding::default()); + assert!(!read, "falls back to PDF part"); + let map_layer = doc.layers.iter().find(|l| l.name.as_deref() == Some("Map Layer")).unwrap(); + assert!(map_layer.locked, "Map Layer preserved locked == true from private stream metadata"); + let subgroup = map_layer.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("Locked Subgroup"))).unwrap(); + assert!(subgroup.locked, "Locked Subgroup preserved locked == true from private stream metadata"); +} + +#[test] +fn ai_duplicate_group_names_under_different_layers_preserve_individual_lock_states() { + use std::sync::Arc; + let art_locked_group = format!("1 A\nu\n%_/ArtDictionary :\n%(SharedGroup) /String (AIArtName) ,\n%_;\n{}\nU\n0 A", square(10, 10)); + let art_unlocked_group = format!("0 A\nu\n%_/ArtDictionary :\n%(SharedGroup) /String (AIArtName) ,\n%_;\n{}\nU\n0 A", square(10, 10)); + let layer_a = layer("Layer A", true, &art_locked_group); + let layer_b = layer("Layer B", true, &art_unlocked_group); + let n = native(&format!("{layer_a}{layer_b}")); + let file = private(&n); + + let mut pdf = Document::new(100.0, 100.0); + pdf.layers.clear(); + let mut vis_a = Node::layer(pdf.alloc_id(), "Layer A", LayerColor::Preset(0)); + let mut vis_grp_a = Node::group(pdf.alloc_id(), vec![]); + vis_grp_a.name = Some("SharedGroup".to_string()); + vis_grp_a.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_a.kind { + children.push(Arc::new(vis_grp_a)); + } + + let mut vis_b = Node::layer(pdf.alloc_id(), "Layer B", LayerColor::Preset(1)); + let mut vis_grp_b = Node::group(pdf.alloc_id(), vec![]); + vis_grp_b.name = Some("SharedGroup".to_string()); + vis_grp_b.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_b.kind { + children.push(Arc::new(vis_grp_b)); + } + pdf.layers.push(Arc::new(vis_a)); + pdf.layers.push(Arc::new(vis_b)); + + let layers = crate::AiLayers::decode(&file); + let (doc, _notes, read) = crate::layered_ai_from(layers, pdf, vec![], false, false, 1.0, crate::NameEncoding::default()); + assert!(!read, "falls back to PDF part"); + + let l_a = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer A")).unwrap(); + let l_b = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer B")).unwrap(); + let grp_a = l_a.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("SharedGroup"))).unwrap(); + let grp_b = l_b.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("SharedGroup"))).unwrap(); + + assert!(grp_a.locked, "Layer A's SharedGroup is locked"); + assert!(!grp_b.locked, "Layer B's SharedGroup remains unlocked"); +} + +#[test] +fn ai_reordered_mixed_named_and_unnamed_children_preserve_locks() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + let mut priv_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0)); + let mut priv_unnamed = Node::group(doc.alloc_id(), vec![]); + priv_unnamed.locked = false; + let mut priv_roads = Node::group(doc.alloc_id(), vec![]); + priv_roads.name = Some("Roads".to_string()); + priv_roads.locked = true; + if let NodeKind::Layer { children, .. } = &mut priv_layer.kind { + children.push(Arc::new(priv_unnamed)); + children.push(Arc::new(priv_roads)); + } + + let mut vis_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0)); + let mut vis_roads = Node::group(doc.alloc_id(), vec![]); + vis_roads.name = Some("Roads".to_string()); + vis_roads.locked = false; + let mut vis_unnamed = Node::group(doc.alloc_id(), vec![]); + vis_unnamed.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_roads)); + children.push(Arc::new(vis_unnamed)); + } + + let mut visible_layers = vec![Arc::new(vis_layer)]; + let private_layers = vec![Arc::new(priv_layer)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + let roads = visible_layers[0].children().unwrap()[0].clone(); + let unnamed = visible_layers[0].children().unwrap()[1].clone(); + assert_eq!(roads.name.as_deref(), Some("Roads")); + assert!(roads.locked, "Roads matched by unique name and preserved locked == true"); + assert!(!unnamed.locked, "unnamed child matched to unlocked private child"); +} diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index 6b812224e2..0b21aadce9 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -83,6 +83,8 @@ pub(crate) struct Ocgs { view_auto: HashSet, /// The groups placed in the layer order. placed: HashSet, + /// The groups that are locked in configuration or dictionary flags. + locked: HashSet, } impl Ocgs { @@ -95,9 +97,13 @@ impl Ocgs { }; let config = props.get::>(b"D").unwrap_or_default(); let refs = |d: &Dict<'_>, key: &[u8]| -> Vec { - d.get::>(key) - .map(|a| items(&a).filter_map(|i| i.as_obj_ref()).map(ObjectIdentifier::from).take(MAX_GROUPS).collect()) - .unwrap_or_default() + if let Some(a) = d.get::>(key) { + items(&a).filter_map(|i| i.as_obj_ref()).map(ObjectIdentifier::from).take(MAX_GROUPS).collect() + } else if let Some(r) = d.get_ref(key) { + vec![ObjectIdentifier::from(r)] + } else { + Vec::new() + } }; let all = refs(&props, b"OCGs"); if config.get::>(b"BaseState").is_some_and(|n| n.as_ref() == b"OFF") { @@ -111,10 +117,13 @@ impl Ocgs { for d in auto.iter().filter(|d| d.get::>(b"Event").is_some_and(|e| e.as_ref() == b"View")) { o.view_auto.extend(refs(d, b"OCGs")); } - let locked: HashSet<_> = refs(&config, b"Locked").into_iter().collect(); + let mut locked: HashSet<_> = refs(&config, b"Locked").into_iter().collect(); + locked.extend(refs(&props, b"Locked")); + o.locked = locked; for id in all { if let Some(d) = xref.get::>(id) { - o.add(id, &d, locked.contains(&id)); + let is_locked = o.is_locked(id, &d); + o.add(id, &d, is_locked); } } if let Some(order) = config.get::>(b"Order") { @@ -170,6 +179,7 @@ impl Ocgs { if let Some(i) = self.index.get(&id) { return *i; } + let locked = locked || self.is_locked(id, d); let name = d.get::>(b"Name").map(|s| text_string(s.as_bytes())).unwrap_or_default(); let print = usage(d, b"Print", b"PrintState") != Some(false); // A view state applies when the configuration says so on opening; an off one hides the @@ -186,6 +196,11 @@ impl Ocgs { self.list.len() - 1 } + /// Is group `id` (dictionary `d`) locked according to configuration or dictionary flags? + fn is_locked(&self, id: ObjectIdentifier, d: &Dict<'_>) -> bool { + self.locked.contains(&id) || is_ocg_dict_locked(d) + } + /// Does the interpreter leave out the art of some group (off in the default configuration)? pub fn skips_any(&self) -> bool { self.index.keys().any(|id| self.off.contains(id)) @@ -206,11 +221,49 @@ impl Ocgs { fn note(&mut self, id: ObjectIdentifier, d: &Dict<'_>) -> Option { match self.index.get(&id) { Some(i) => Some(*i), - None => (self.list.len() < MAX_GROUPS).then(|| self.add(id, d, false)), + None => { + let is_locked = self.is_locked(id, d); + (self.list.len() < MAX_GROUPS).then(|| self.add(id, d, is_locked)) + } } } } +/// Is group dictionary `d` flagged as locked (directly or in its `/Usage`)? +fn is_ocg_dict_locked(d: &Dict<'_>) -> bool { + if d.get::(b"Locked") == Some(true) + || d.get::>(b"Locked").is_some_and(|n| { + let b = n.as_ref(); + b.eq_ignore_ascii_case(b"true") || b.eq_ignore_ascii_case(b"locked") || b.eq_ignore_ascii_case(b"on") + }) + { + return true; + } + if let Some(usage) = d.get::>(b"Usage") { + if usage.get::(b"Locked") == Some(true) + || usage.get::>(b"Locked").is_some_and(|n| { + let b = n.as_ref(); + b.eq_ignore_ascii_case(b"true") || b.eq_ignore_ascii_case(b"locked") || b.eq_ignore_ascii_case(b"on") + }) + { + return true; + } + if let Some(user) = usage.get::>(b"User") + && (user.get::(b"Locked") == Some(true) + || user.get::>(b"Type").is_some_and(|n| n.as_ref().eq_ignore_ascii_case(b"locked")) + || user.get::>(b"User").is_some_and(|s| s.as_bytes().eq_ignore_ascii_case(b"locked"))) + { + return true; + } + if let Some(lock) = usage.get::>(b"Lock") + && lock.get::(b"Locked") != Some(false) + { + return true; + } + } + false +} + /// The state (`ON` → true, `OFF` → false) group `d`'s usage `category` gives in `key`. fn usage(d: &Dict<'_>, category: &[u8], key: &[u8]) -> Option { let state = d.get::>(b"Usage")?.get::>(category)?.get::>(key)?; diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 688964d8db..76d7b0fb33 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -539,11 +539,30 @@ fn private_data(pdf: &Pdf) -> Option> { /// [`private_data`], with why a private data stream can't be read ([`inflated`]). fn read_private_data(pdf: &Pdf) -> Result>, String> { - let Some(private) = pdf + let xref = pdf.xref(); + let page_private = pdf .pages() .first() - .and_then(|page| page.raw().get::>(b"PieceInfo")?.get::>(PRIVATE_DATA_OWNER)?.get::>(b"Private")) - else { + .and_then(|page| page.raw().get::>(b"PieceInfo")?.get::>(PRIVATE_DATA_OWNER)?.get::>(b"Private")); + let root_private = xref + .get::>(xref.root_id()) + .and_then(|root| root.get::>(b"PieceInfo")?.get::>(PRIVATE_DATA_OWNER)?.get::>(b"Private")); + let has_supported_data = |dict: &Dict<'_>| dict.contains_key(b"AIPrivateData1") || dict.contains_key(b"AIPDFPrivateData1"); + let private = match (page_private, root_private) { + (Some(page), Some(root)) => { + if has_supported_data(&page) { + Some(page) + } else if has_supported_data(&root) { + Some(root) + } else { + Some(page) + } + } + (Some(page), None) => Some(page), + (None, Some(root)) => Some(root), + (None, None) => None, + }; + let Some(private) = private else { return Ok(None); }; let key = if private.contains_key(b"AIPrivateData1") { "AIPrivateData" } else { "AIPDFPrivateData" }; @@ -564,7 +583,9 @@ pub fn has_illustrator_data(bytes: &[u8], password: Option<&str>) -> bool { /// [`has_illustrator_data`] of a parsed PDF. fn has_private_data_keys(pdf: &Pdf) -> bool { + let xref = pdf.xref(); pdf.pages().first().is_some_and(|p| piece_info_has(p, &[b"AIPrivateData", b"AIPDFPrivateData"])) + || xref.get::>(xref.root_id()).is_some_and(|root| dict_piece_info_has(&root, &[b"AIPrivateData", b"AIPDFPrivateData"])) } /// `stream` decoded, up to `most` bytes: the decoder is run here rather than by the PDF reader's @@ -627,15 +648,41 @@ pub(crate) fn states_art(page: &Page<'_>) -> bool { [&b"ArtBox"[..], b"TrimBox", b"BleedBox"].iter().any(|k| page.raw().get::<[f32; 4]>(*k).is_some()) } +/// Does dictionary `d`'s `PieceInfo` hold a key starting with one of `prefixes`, up to four dictionaries in? +fn dict_has_piece_info_prefix(d: &Dict<'_>, prefixes: &[&[u8]]) -> bool { + const MAX_VISITS: usize = 128; + fn walk(d: &Dict<'_>, prefixes: &[&[u8]], depth: u32, budget: &mut usize) -> bool { + if depth >= 4 || *budget == 0 { + return false; + } + for k in d.keys() { + if *budget == 0 { + return false; + } + *budget -= 1; + if prefixes.iter().any(|p| k.starts_with(p)) { + return true; + } + if let Some(sub) = d.get::>(k.as_ref()) + && walk(&sub, prefixes, depth + 1, budget) + { + return true; + } + } + false + } + let mut budget = MAX_VISITS; + walk(d, prefixes, 0, &mut budget) +} + /// Does `page`'s `PieceInfo` hold a key starting with one of `prefixes`, up to four dictionaries in? fn piece_info_has(page: &Page<'_>, prefixes: &[&[u8]]) -> bool { - fn walk(d: &Dict<'_>, prefixes: &[&[u8]], depth: u32) -> bool { - depth < 4 - && d.keys().any(|k| { - prefixes.iter().any(|p| k.starts_with(p)) || d.get::>(k.as_ref()).is_some_and(|sub| walk(&sub, prefixes, depth + 1)) - }) - } - page.raw().get::>(b"PieceInfo").is_some_and(|d| walk(&d, prefixes, 0)) + page.raw().get::>(b"PieceInfo").is_some_and(|d| dict_has_piece_info_prefix(&d, prefixes)) +} + +/// Does dictionary `d`'s `PieceInfo` hold a key starting with one of `prefixes`, up to four dictionaries in? +fn dict_piece_info_has(d: &Dict<'_>, prefixes: &[&[u8]]) -> bool { + d.get::>(b"PieceInfo").is_some_and(|p| dict_has_piece_info_prefix(&p, prefixes)) } #[cfg(test)] diff --git a/crates/pdf/src/tests/import_layers.rs b/crates/pdf/src/tests/import_layers.rs index c0f9dfc970..56492fe30a 100644 --- a/crates/pdf/src/tests/import_layers.rs +++ b/crates/pdf/src/tests/import_layers.rs @@ -469,3 +469,108 @@ fn art_deep_in_tags_inside_a_layer_reaches_it() { let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); assert_eq!(colors(shapes), [Color::rgb(1.0, 0.0, 0.0)]); } + +#[test] +fn ocg_dictionary_locked_flag_is_read() { + let (a, b) = (first_extra(1), first_extra(1) + 1); + let objs = ["<< /Type /OCG /Name (Shapes) /Locked true >>".to_string(), "<< /Type /OCG /Name (Plain) >>".to_string()]; + let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << /Order [{a} 0 R {b} 0 R] >> >> "); + let bytes = pdf_with_catalog(&[page([a, b])], &[&objs[0], &objs[1]], &catalog, None); + let d = import(&bytes).unwrap(); + let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); + let plain = d.layers.iter().find(|l| l.name.as_deref() == Some("Plain")).unwrap(); + assert!(shapes.locked, "Shapes has /Locked true in its dictionary"); + assert!(!plain.locked, "Plain is not locked"); +} + +#[test] +fn ocg_dictionary_usage_locked_is_read() { + let (a, b) = (first_extra(1), first_extra(1) + 1); + let objs = ["<< /Type /OCG /Name (Shapes) /Usage << /User << /Type /Locked >> >> >>".to_string(), "<< /Type /OCG /Name (Plain) >>".to_string()]; + let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << /Order [{a} 0 R {b} 0 R] >> >> "); + let bytes = pdf_with_catalog(&[page([a, b])], &[&objs[0], &objs[1]], &catalog, None); + let d = import(&bytes).unwrap(); + let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); + let plain = d.layers.iter().find(|l| l.name.as_deref() == Some("Plain")).unwrap(); + assert!(shapes.locked, "Shapes has /Usage << /User << /Type /Locked >> >>"); + assert!(!plain.locked, "Plain is not locked"); +} + +#[test] +fn oc_properties_root_locked_is_read_and_configs_locked_is_ignored() { + let (a, b) = (first_extra(1), first_extra(1) + 1); + let objs = ["<< /Type /OCG /Name (RootLocked) >>".to_string(), "<< /Type /OCG /Name (ConfigUnlocked) >>".to_string()]; + let catalog = format!( + "/OCProperties << /OCGs [{a} 0 R {b} 0 R] /Locked [{a} 0 R] /Configs [<< /Locked [{b} 0 R] >>] /D << /Order [{a} 0 R {b} 0 R] >> >> " + ); + let bytes = pdf_with_catalog(&[page([a, b])], &[&objs[0], &objs[1]], &catalog, None); + let d = import(&bytes).unwrap(); + let root_locked = d.layers.iter().find(|l| l.name.as_deref() == Some("RootLocked")).unwrap(); + let config_unlocked = d.layers.iter().find(|l| l.name.as_deref() == Some("ConfigUnlocked")).unwrap(); + assert!(root_locked.locked, "RootLocked is in /OCProperties /Locked"); + assert!(!config_unlocked.locked, "ConfigUnlocked is only in alternate /Configs /Locked, so stays unlocked"); +} + +#[test] +fn ocg_noted_from_content_stream_retains_lock() { + let (a, b) = (first_extra(1), first_extra(1) + 1); + let objs = ["<< /Type /OCG /Name (UnlistedLocked) /Locked true >>".to_string(), "<< /Type /OCG /Name (Listed) >>".to_string()]; + // /OCGs only lists {b} (Listed). {a} (UnlistedLocked) is not in /OCGs or /Order. + let catalog = format!("/OCProperties << /OCGs [{b} 0 R] /D << /Order [{b} 0 R] >> >> "); + let content = "/OC /MC0 BDC 1 0 0 rg 10 10 30 30 re f EMC /OC /MC1 BDC 0 1 0 rg 0 0 5 5 re f EMC"; + let p = PdfPage { resources: format!("/Properties << /MC0 {a} 0 R /MC1 {b} 0 R >>"), ..PdfPage::new(100.0, 100.0, content) }; + let bytes = pdf_with_catalog(&[p], &[&objs[0], &objs[1]], &catalog, None); + let d = import(&bytes).unwrap(); + let unlisted = d.layers.iter().find(|l| l.name.as_deref() == Some("UnlistedLocked")).unwrap(); + let listed = d.layers.iter().find(|l| l.name.as_deref() == Some("Listed")).unwrap(); + assert!(unlisted.locked, "UnlistedLocked has /Locked true in its dictionary"); + assert!(!listed.locked, "Listed is not locked"); +} + +#[test] +fn ai_fixture_with_locked_group_and_locked_object_imports_with_locks_preserved() { + let (a, b, c, d) = (first_extra(1), first_extra(1) + 1, first_extra(1) + 2, first_extra(1) + 3); + let order_obj = first_extra(1) + 4; + let objs = [ + "<< /Type /OCG /Name (Layer1) >>".to_string(), + "<< /Type /OCG /Name (LockedGroup) /Locked true >>".to_string(), + "<< /Type /OCG /Name (UnlockedGroup) >>".to_string(), + "<< /Type /OCG /Name (LockedObject) /Locked true >>".to_string(), + ]; + let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R {c} 0 R {d} 0 R] /D << /Order {order_obj} 0 R >> >> "); + let order_body = format!("[{a} 0 R [{b} 0 R {c} 0 R]]"); + let content = "/OC /MC0 BDC 1 0 0 rg 10 10 20 20 re f EMC \ + /OC /MC1 BDC 0 1 0 rg 30 30 20 20 re f EMC \ + /OC /MC2 BDC 0 0 1 rg 50 50 20 20 re f EMC \ + /OC /MC3 BDC 1 1 0 rg 70 70 20 20 re f EMC \ + 0 0 0 rg 0 0 10 10 re f"; + let page = PdfPage { + resources: format!("/Properties << /MC0 {a} 0 R /MC1 {b} 0 R /MC2 {c} 0 R /MC3 {d} 0 R >>"), + entries: "/PieceInfo << /Illustrator << /Private << /AIPrivateData1 7 /NumBlock 1 >> >> >>".into(), + ..PdfPage::new(100.0, 100.0, content) + }; + let bytes = pdf_with_catalog(&[page], &[&objs[0], &objs[1], &objs[2], &objs[3], &order_body], &catalog, None); + let doc = import(&bytes).unwrap(); + + let layer1 = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer1")).expect("Layer1 exists"); + assert!(!layer1.locked, "Layer1 is not locked"); + + let children = layer1.children().expect("Layer1 has children"); + let locked_group = children.iter().find(|n| n.name.as_deref() == Some("LockedGroup")).expect("LockedGroup exists"); + assert!(locked_group.locked, "LockedGroup has locked: true"); + + let unlocked_group = children.iter().find(|n| n.name.as_deref() == Some("UnlockedGroup")).expect("UnlockedGroup exists"); + assert!(!unlocked_group.locked, "UnlockedGroup has locked: false"); + + let locked_obj = doc.layers.iter().find(|l| l.name.as_deref() == Some("LockedObject")).expect("LockedObject exists"); + assert!(locked_obj.locked, "LockedObject has locked: true"); + + if let Some(page_layer) = doc.layers.iter().find(|l| l.name.as_deref() == Some("Page 1")) { + assert!(!page_layer.locked, "Page layer is not locked"); + if let Some(kids) = page_layer.children() { + for kid in kids { + assert!(!kid.locked, "Non-locked object in page layer remains unlocked"); + } + } + } +} diff --git a/crates/pdf/tests/import_layers.rs b/crates/pdf/tests/import_layers.rs new file mode 100644 index 0000000000..a82bb7a415 --- /dev/null +++ b/crates/pdf/tests/import_layers.rs @@ -0,0 +1,53 @@ +//! Synthetic regression verifying locked group and locked object import in AI fixtures. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use vectorcraft_pdf::import; +use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with_catalog}; + +#[test] +fn ai_fixture_with_locked_group_and_locked_object_imports_with_locks_preserved() { + let (a, b, c, d) = (first_extra(1), first_extra(1) + 1, first_extra(1) + 2, first_extra(1) + 3); + let order_obj = first_extra(1) + 4; + let objs = [ + "<< /Type /OCG /Name (Layer1) >>".to_string(), + "<< /Type /OCG /Name (LockedGroup) /Locked true >>".to_string(), + "<< /Type /OCG /Name (UnlockedGroup) >>".to_string(), + "<< /Type /OCG /Name (LockedObject) /Locked true >>".to_string(), + ]; + let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R {c} 0 R {d} 0 R] /D << /Order {order_obj} 0 R >> >> "); + let order_body = format!("[{a} 0 R [{b} 0 R {c} 0 R]]"); + let content = "/OC /MC0 BDC 1 0 0 rg 10 10 20 20 re f EMC \ + /OC /MC1 BDC 0 1 0 rg 30 30 20 20 re f EMC \ + /OC /MC2 BDC 0 0 1 rg 50 50 20 20 re f EMC \ + /OC /MC3 BDC 1 1 0 rg 70 70 20 20 re f EMC \ + 0 0 0 rg 0 0 10 10 re f"; + let page = PdfPage { + resources: format!("/Properties << /MC0 {a} 0 R /MC1 {b} 0 R /MC2 {c} 0 R /MC3 {d} 0 R >>"), + entries: "/PieceInfo << /Illustrator << /Private << /AIPrivateData1 7 /NumBlock 1 >> >> >>".into(), + ..PdfPage::new(100.0, 100.0, content) + }; + let bytes = pdf_with_catalog(&[page], &[&objs[0], &objs[1], &objs[2], &objs[3], &order_body], &catalog, None); + let doc = import(&bytes).unwrap(); + + let layer1 = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer1")).expect("Layer1 exists"); + assert!(!layer1.locked, "Layer1 is not locked"); + + let children = layer1.children().expect("Layer1 has children"); + let locked_group = children.iter().find(|n| n.name.as_deref() == Some("LockedGroup")).expect("LockedGroup exists"); + assert!(locked_group.locked, "LockedGroup has locked: true"); + + let unlocked_group = children.iter().find(|n| n.name.as_deref() == Some("UnlockedGroup")).expect("UnlockedGroup exists"); + assert!(!unlocked_group.locked, "UnlockedGroup has locked: false"); + + let locked_obj = doc.layers.iter().find(|l| l.name.as_deref() == Some("LockedObject")).expect("LockedObject exists"); + assert!(locked_obj.locked, "LockedObject has locked: true"); + + if let Some(page_layer) = doc.layers.iter().find(|l| l.name.as_deref() == Some("Page 1")) { + assert!(!page_layer.locked, "Page layer is not locked"); + if let Some(kids) = page_layer.children() { + for kid in kids { + assert!(!kid.locked, "Non-locked object in page layer remains unlocked"); + } + } + } +} From 6c6c65b9e08bb178ba5649e5fc8a986758d0d2cf Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:45:06 +0530 Subject: [PATCH 02/14] Address CodeRabbit review feedback on layer and child lock matching --- crates/eps/src/import/native/layers.rs | 133 ++++++++++++++---------- crates/eps/src/import/tests_native.rs | 137 +++++++++++++++++++++++++ crates/pdf/src/pages.rs | 5 + 3 files changed, 222 insertions(+), 53 deletions(-) diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index d74029e0f0..fa64adbb67 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -243,36 +243,58 @@ fn holds_type_envelope(nodes: &[Arc]) -> bool { /// Apply lock states from private data layers to visible PDF layers. pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], private_layers: &[Arc]) { - if private_layers.is_empty() { + if private_layers.is_empty() || visible_layers.is_empty() { return; } - let mut priv_layer_names = std::collections::HashMap::new(); - for p in private_layers { + + // Index private layers: name -> (count, first_index) + let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new(); + for (i, p) in private_layers.iter().enumerate() { if let Some(name) = p.name.as_deref() { - *priv_layer_names.entry(name).or_insert(0usize) += 1; + let entry = priv_names.entry(name).or_insert((0, i)); + entry.0 += 1; } } - let same_len = visible_layers.len() == private_layers.len(); - for (i, vis) in visible_layers.iter_mut().enumerate() { - let priv_node = if let Some(vis_name) = vis.name.as_deref() { - if priv_layer_names.get(vis_name).copied() == Some(1) { - private_layers.iter().find(|p| p.name.as_deref() == Some(vis_name)) - } else if same_len && private_layers[i].name.as_deref() == Some(vis_name) { - Some(&private_layers[i]) - } else { - None - } - } else if same_len { - Some(&private_layers[i]) - } else { - None - }; - - if let Some(p) = priv_node { - apply_node_locks(Arc::make_mut(vis), p); + // Index visible layers: name -> count + let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for v in visible_layers.iter() { + if let Some(name) = v.name.as_deref() { + *vis_names.entry(name).or_insert(0) += 1; } } + + let mut matched_vis = vec![false; visible_layers.len()]; + let mut matched_priv = vec![false; private_layers.len()]; + let mut pairs = Vec::new(); + + // Pass 1: Unique named matches + for (v_idx, vis) in visible_layers.iter().enumerate() { + if let Some(name) = vis.name.as_deref() + && vis_names.get(name).copied() == Some(1) + && let Some(&(1, p_idx)) = priv_names.get(name) + && !matched_priv[p_idx] + { + matched_vis[v_idx] = true; + matched_priv[p_idx] = true; + pairs.push((v_idx, p_idx)); + } + } + + // Pass 2: Pair remaining unmatched layers in relative order when counts match + let unmatched_v: Vec = (0..visible_layers.len()).filter(|&i| !matched_vis[i]).collect(); + let unmatched_p: Vec = (0..private_layers.len()).filter(|&i| !matched_priv[i]).collect(); + if unmatched_v.len() == unmatched_p.len() { + for (&v_idx, &p_idx) in unmatched_v.iter().zip(unmatched_p.iter()) { + pairs.push((v_idx, p_idx)); + } + } else if unmatched_v.len() == 1 && unmatched_p.len() == 1 { + pairs.push((unmatched_v[0], unmatched_p[0])); + } + + for (v_idx, p_idx) in pairs { + apply_node_locks(Arc::make_mut(&mut visible_layers[v_idx]), &private_layers[p_idx]); + } } fn apply_node_locks(vis: &mut Node, priv_: &Node) { @@ -280,52 +302,57 @@ fn apply_node_locks(vis: &mut Node, priv_: &Node) { vis.locked = true; } if let (Some(vis_kids), Some(priv_kids)) = (vis.children_mut(), priv_.children()) { - let mut priv_name_counts = std::collections::HashMap::new(); - for p in priv_kids { + if vis_kids.is_empty() || priv_kids.is_empty() { + return; + } + + // Index private children: name -> (count, first_index) + let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new(); + for (i, p) in priv_kids.iter().enumerate() { if let Some(name) = p.name.as_deref() { - *priv_name_counts.entry(name).or_insert(0usize) += 1; + let entry = priv_names.entry(name).or_insert((0, i)); + entry.0 += 1; } } - let mut matched_priv = vec![false; priv_kids.len()]; + + // Index visible children: name -> count + let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for v in vis_kids.iter() { + if let Some(name) = v.name.as_deref() { + *vis_names.entry(name).or_insert(0) += 1; + } + } + let mut matched_vis = vec![false; vis_kids.len()]; + let mut matched_priv = vec![false; priv_kids.len()]; + let mut pairs = Vec::new(); // Pass 1: resolve unique named matches first. - for (v_idx, v) in vis_kids.iter_mut().enumerate() { + for (v_idx, v) in vis_kids.iter().enumerate() { if let Some(v_name) = v.name.as_deref() - && priv_name_counts.get(v_name).copied() == Some(1) - && let Some((p_idx, p)) = priv_kids.iter().enumerate().find(|(_, p)| p.name.as_deref() == Some(v_name)) + && vis_names.get(v_name).copied() == Some(1) + && let Some(&(1, p_idx)) = priv_names.get(v_name) + && !matched_priv[p_idx] { - apply_node_locks(Arc::make_mut(v), p); - matched_priv[p_idx] = true; matched_vis[v_idx] = true; + matched_priv[p_idx] = true; + pairs.push((v_idx, p_idx)); } } - // Pass 2: positional match for remaining children when counts match. - let same_len = vis_kids.len() == priv_kids.len(); - if same_len { - for (idx, v) in vis_kids.iter_mut().enumerate() { - if matched_vis[idx] { - continue; - } - if !matched_priv[idx] && (priv_kids[idx].name.is_none() || v.name == priv_kids[idx].name) { - apply_node_locks(Arc::make_mut(v), &priv_kids[idx]); - matched_priv[idx] = true; - matched_vis[idx] = true; - } + // Pass 2: pair remaining unmatched children in relative order when counts match. + let unmatched_v: Vec = (0..vis_kids.len()).filter(|&i| !matched_vis[i]).collect(); + let unmatched_p: Vec = (0..priv_kids.len()).filter(|&i| !matched_priv[i]).collect(); + if unmatched_v.len() == unmatched_p.len() { + for (&v_idx, &p_idx) in unmatched_v.iter().zip(unmatched_p.iter()) { + pairs.push((v_idx, p_idx)); } + } else if unmatched_v.len() == 1 && unmatched_p.len() == 1 { + pairs.push((unmatched_v[0], unmatched_p[0])); } - // Pass 3: match remaining unmatched unnamed children. - for (v_idx, v) in vis_kids.iter_mut().enumerate() { - if matched_vis[v_idx] || v.name.is_some() { - continue; - } - if let Some((p_idx, p)) = priv_kids.iter().enumerate().find(|(i, p)| !matched_priv[*i] && p.name.is_none()) { - apply_node_locks(Arc::make_mut(v), p); - matched_priv[p_idx] = true; - matched_vis[v_idx] = true; - } + for (v_idx, p_idx) in pairs { + apply_node_locks(Arc::make_mut(&mut vis_kids[v_idx]), &priv_kids[p_idx]); } } } diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 7118d08481..8fc5e2541b 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8442,3 +8442,140 @@ fn ai_reordered_mixed_named_and_unnamed_children_preserve_locks() { assert!(roads.locked, "Roads matched by unique name and preserved locked == true"); assert!(!unnamed.locked, "unnamed child matched to unlocked private child"); } + +#[test] +fn ai_reordered_three_children_roads_triangle_circle_preserve_locks() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + // Private children: [Roads (unlocked), locked triangle (unnamed), unlocked circle (unnamed)] + let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut priv_roads = Node::group(doc.alloc_id(), vec![]); + priv_roads.name = Some("Roads".to_string()); + priv_roads.locked = false; + let mut priv_triangle = Node::group(doc.alloc_id(), vec![]); + priv_triangle.locked = true; + let mut priv_circle = Node::group(doc.alloc_id(), vec![]); + priv_circle.locked = false; + if let NodeKind::Layer { children, .. } = &mut priv_layer.kind { + children.push(Arc::new(priv_roads)); + children.push(Arc::new(priv_triangle)); + children.push(Arc::new(priv_circle)); + } + + // Visible children: [triangle (unnamed), circle (unnamed), Roads] + let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut vis_triangle = Node::group(doc.alloc_id(), vec![]); + vis_triangle.locked = false; + let mut vis_circle = Node::group(doc.alloc_id(), vec![]); + vis_circle.locked = false; + let mut vis_roads = Node::group(doc.alloc_id(), vec![]); + vis_roads.name = Some("Roads".to_string()); + vis_roads.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_triangle)); + children.push(Arc::new(vis_circle)); + children.push(Arc::new(vis_roads)); + } + + let mut visible_layers = vec![Arc::new(vis_layer)]; + let private_layers = vec![Arc::new(priv_layer)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + let vis_tri = visible_layers[0].children().unwrap()[0].clone(); + let vis_circ = visible_layers[0].children().unwrap()[1].clone(); + let vis_rd = visible_layers[0].children().unwrap()[2].clone(); + + assert!(vis_tri.locked, "triangle matched to locked private triangle in relative order"); + assert!(!vis_circ.locked, "circle matched to unlocked private circle in relative order"); + assert!(!vis_rd.locked, "Roads matched to unlocked private Roads by unique name"); +} + +#[test] +fn ai_fallback_with_generated_page_name_preserves_private_layer_lock() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + let mut priv_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0)); + priv_layer.locked = true; + let mut vis_layer = Node::layer(doc.alloc_id(), "Page 1", LayerColor::Preset(0)); + vis_layer.locked = false; + + let mut visible_layers = vec![Arc::new(vis_layer)]; + let private_layers = vec![Arc::new(priv_layer)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + assert_eq!(visible_layers[0].name.as_deref(), Some("Page 1")); + assert!(visible_layers[0].locked, "Page 1 layer matched to locked private layer Map positionally"); +} + +#[test] +fn ai_named_locked_private_child_pairs_with_unnamed_visible_child() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut priv_unnamed = Node::group(doc.alloc_id(), vec![]); + priv_unnamed.locked = false; + let mut priv_roads = Node::group(doc.alloc_id(), vec![]); + priv_roads.name = Some("Roads".to_string()); + priv_roads.locked = true; + if let NodeKind::Layer { children, .. } = &mut priv_layer.kind { + children.push(Arc::new(priv_unnamed)); + children.push(Arc::new(priv_roads)); + } + + let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut vis_first = Node::group(doc.alloc_id(), vec![]); + vis_first.locked = false; + let mut vis_second = Node::group(doc.alloc_id(), vec![]); + vis_second.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_first)); + children.push(Arc::new(vis_second)); + } + + let mut visible_layers = vec![Arc::new(vis_layer)]; + let private_layers = vec![Arc::new(priv_layer)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + let first = visible_layers[0].children().unwrap()[0].clone(); + let second = visible_layers[0].children().unwrap()[1].clone(); + assert!(!first.locked, "first unnamed visible group is unlocked"); + assert!(second.locked, "second unnamed visible group pairs positionally with locked Roads group"); +} + +#[test] +fn ai_duplicate_visible_name_does_not_lock_multiple_from_single_private_node() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut priv_roads = Node::group(doc.alloc_id(), vec![]); + priv_roads.name = Some("Roads".to_string()); + priv_roads.locked = true; + let mut priv_buildings = Node::group(doc.alloc_id(), vec![]); + priv_buildings.name = Some("Buildings".to_string()); + priv_buildings.locked = false; + if let NodeKind::Layer { children, .. } = &mut priv_layer.kind { + children.push(Arc::new(priv_roads)); + children.push(Arc::new(priv_buildings)); + } + + let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut vis_roads1 = Node::group(doc.alloc_id(), vec![]); + vis_roads1.name = Some("Roads".to_string()); + vis_roads1.locked = false; + let mut vis_roads2 = Node::group(doc.alloc_id(), vec![]); + vis_roads2.name = Some("Roads".to_string()); + vis_roads2.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_roads1)); + children.push(Arc::new(vis_roads2)); + } + + let mut visible_layers = vec![Arc::new(vis_layer)]; + let private_layers = vec![Arc::new(priv_layer)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + let r1 = visible_layers[0].children().unwrap()[0].clone(); + let r2 = visible_layers[0].children().unwrap()[1].clone(); + assert!(r1.locked, "first Roads group receives the lock from private Roads"); + assert!(!r2.locked, "second Roads group remains unlocked, avoiding duplicate private lock propagation"); +} diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 76d7b0fb33..f058913a76 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -650,6 +650,11 @@ pub(crate) fn states_art(page: &Page<'_>) -> bool { /// Does dictionary `d`'s `PieceInfo` hold a key starting with one of `prefixes`, up to four dictionaries in? fn dict_has_piece_info_prefix(d: &Dict<'_>, prefixes: &[&[u8]]) -> bool { + if let Some(priv_dict) = d.get::>(PRIVATE_DATA_OWNER).and_then(|i| i.get::>(b"Private")) + && prefixes.iter().any(|p| priv_dict.keys().any(|k| k.starts_with(p))) + { + return true; + } const MAX_VISITS: usize = 128; fn walk(d: &Dict<'_>, prefixes: &[&[u8]], depth: u32, budget: &mut usize) -> bool { if depth >= 4 || *budget == 0 { From 052276373b1a1a95d84abee45afd3a32b94584eb Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:36:46 +0530 Subject: [PATCH 03/14] Address review feedback on lock propagation, node cloning, and catalog private data --- crates/eps/src/import/ai/read/ops.rs | 1 + crates/eps/src/import/native/layers.rs | 129 ++++++++++++------------- crates/eps/src/import/native/slots.rs | 6 ++ crates/eps/src/import/tests_native.rs | 71 +++++++++++--- crates/pdf/src/import/entry.rs | 5 +- crates/pdf/src/pages.rs | 9 +- crates/pdf/tests/import_layers.rs | 25 +++++ 7 files changed, 158 insertions(+), 88 deletions(-) diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index f267de09fb..acde018009 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -953,6 +953,7 @@ impl<'a> Reader<'a> { (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape) = (1.0, BlendMode::Normal, false, Knockout::Neutral, false); let (visible, locked) = (object.visible, object.locked); (object.opacity, object.blend, object.isolate, object.knockout_shape) = (1.0, BlendMode::Normal, false, false); + object.locked = false; let mut group = Node::group(self.doc.alloc_id(), vec![Arc::new(look), Arc::new(object)]); (group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = state; group.visible = visible; diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index fa64adbb67..1982fefd64 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -173,7 +173,8 @@ pub fn layered_ai_from( // The PDF part, its pages placed and named as the editing data's artboards are, when the // layers can't be used (`why`). let structure = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)); - let private_layers = structure.as_ref().ok().map(|s| s.doc.layers.clone()).unwrap_or_default(); + let private_layers: Vec = + structure.as_ref().ok().map(|s| s.doc.layers.iter().map(|l| LockTree::from_node(l)).collect()).unwrap_or_default(); let from_pdf_part = |mut visible: Document, mut warnings: Vec, why: &str| { let mut read = ai::Names::new(names); let mut board_names = ai::Names::new(names); @@ -241,13 +242,38 @@ fn holds_type_envelope(nodes: &[Arc]) -> bool { }) } +/// Lightweight lock metadata snapshot of a node hierarchy, preserving names and lock states +/// without holding `Arc` references to the artwork tree. +#[derive(Clone, Debug, Default)] +pub(crate) struct LockTree { + pub name: Option, + pub locked: bool, + pub children: Vec, +} + +impl LockTree { + pub fn from_node(node: &Node) -> Self { + Self { + name: node.name.clone(), + locked: node.locked, + children: node.children().map(|kids| kids.iter().map(|k| Self::from_node(k)).collect()).unwrap_or_default(), + } + } +} + /// Apply lock states from private data layers to visible PDF layers. -pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], private_layers: &[Arc]) { +pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], private_layers: &[LockTree]) { if private_layers.is_empty() || visible_layers.is_empty() { return; } - // Index private layers: name -> (count, first_index) + // A document with a single visible layer and a single private layer pairs them directly. + if visible_layers.len() == 1 && private_layers.len() == 1 { + apply_node_locks(Arc::make_mut(&mut visible_layers[0]), &private_layers[0]); + return; + } + + // Otherwise, match only layers with identifiable correspondence (matching unique names). let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new(); for (i, p) in private_layers.iter().enumerate() { if let Some(name) = p.name.as_deref() { @@ -256,7 +282,6 @@ pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], privat } } - // Index visible layers: name -> count let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); for v in visible_layers.iter() { if let Some(name) = v.name.as_deref() { @@ -264,96 +289,62 @@ pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], privat } } - let mut matched_vis = vec![false; visible_layers.len()]; - let mut matched_priv = vec![false; private_layers.len()]; let mut pairs = Vec::new(); - - // Pass 1: Unique named matches for (v_idx, vis) in visible_layers.iter().enumerate() { if let Some(name) = vis.name.as_deref() && vis_names.get(name).copied() == Some(1) && let Some(&(1, p_idx)) = priv_names.get(name) - && !matched_priv[p_idx] { - matched_vis[v_idx] = true; - matched_priv[p_idx] = true; pairs.push((v_idx, p_idx)); } } - - // Pass 2: Pair remaining unmatched layers in relative order when counts match - let unmatched_v: Vec = (0..visible_layers.len()).filter(|&i| !matched_vis[i]).collect(); - let unmatched_p: Vec = (0..private_layers.len()).filter(|&i| !matched_priv[i]).collect(); - if unmatched_v.len() == unmatched_p.len() { - for (&v_idx, &p_idx) in unmatched_v.iter().zip(unmatched_p.iter()) { - pairs.push((v_idx, p_idx)); - } - } else if unmatched_v.len() == 1 && unmatched_p.len() == 1 { - pairs.push((unmatched_v[0], unmatched_p[0])); - } + drop(vis_names); for (v_idx, p_idx) in pairs { apply_node_locks(Arc::make_mut(&mut visible_layers[v_idx]), &private_layers[p_idx]); } } -fn apply_node_locks(vis: &mut Node, priv_: &Node) { +fn apply_node_locks(vis: &mut Node, priv_: &LockTree) { if priv_.locked { vis.locked = true; } - if let (Some(vis_kids), Some(priv_kids)) = (vis.children_mut(), priv_.children()) { - if vis_kids.is_empty() || priv_kids.is_empty() { - return; - } + let Some(vis_kids) = vis.children_mut() else { return }; + if vis_kids.is_empty() || priv_.children.is_empty() { + return; + } - // Index private children: name -> (count, first_index) - let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new(); - for (i, p) in priv_kids.iter().enumerate() { - if let Some(name) = p.name.as_deref() { - let entry = priv_names.entry(name).or_insert((0, i)); - entry.0 += 1; - } + // Index private children: name -> (count, first_index) + let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new(); + for (i, p) in priv_.children.iter().enumerate() { + if let Some(name) = p.name.as_deref() { + let entry = priv_names.entry(name).or_insert((0, i)); + entry.0 += 1; } + } - // Index visible children: name -> count - let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); - for v in vis_kids.iter() { - if let Some(name) = v.name.as_deref() { - *vis_names.entry(name).or_insert(0) += 1; - } + // Index visible children: name -> count + let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for v in vis_kids.iter() { + if let Some(name) = v.name.as_deref() { + *vis_names.entry(name).or_insert(0) += 1; } + } - let mut matched_vis = vec![false; vis_kids.len()]; - let mut matched_priv = vec![false; priv_kids.len()]; - let mut pairs = Vec::new(); - - // Pass 1: resolve unique named matches first. - for (v_idx, v) in vis_kids.iter().enumerate() { - if let Some(v_name) = v.name.as_deref() - && vis_names.get(v_name).copied() == Some(1) - && let Some(&(1, p_idx)) = priv_names.get(v_name) - && !matched_priv[p_idx] - { - matched_vis[v_idx] = true; - matched_priv[p_idx] = true; - pairs.push((v_idx, p_idx)); - } + // Resolve unique named matches without positional blind pairing + let mut pairs = Vec::new(); + for (v_idx, v) in vis_kids.iter().enumerate() { + if let Some(v_name) = v.name.as_deref() + && vis_names.get(v_name).copied() == Some(1) + && let Some(&(1, p_idx)) = priv_names.get(v_name) + { + pairs.push((v_idx, p_idx)); } + } + drop(vis_names); - // Pass 2: pair remaining unmatched children in relative order when counts match. - let unmatched_v: Vec = (0..vis_kids.len()).filter(|&i| !matched_vis[i]).collect(); - let unmatched_p: Vec = (0..priv_kids.len()).filter(|&i| !matched_priv[i]).collect(); - if unmatched_v.len() == unmatched_p.len() { - for (&v_idx, &p_idx) in unmatched_v.iter().zip(unmatched_p.iter()) { - pairs.push((v_idx, p_idx)); - } - } else if unmatched_v.len() == 1 && unmatched_p.len() == 1 { - pairs.push((unmatched_v[0], unmatched_p[0])); - } - - for (v_idx, p_idx) in pairs { - apply_node_locks(Arc::make_mut(&mut vis_kids[v_idx]), &priv_kids[p_idx]); - } + for (v_idx, p_idx) in pairs { + apply_node_locks(Arc::make_mut(&mut vis_kids[v_idx]), &priv_.children[p_idx]); } } diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index 902811af45..414a2d321c 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -341,6 +341,9 @@ pub(super) fn fill_slots( let p = Arc::make_mut(p); (p.opacity, p.blend, p.isolate, p.knockout, p.knockout_shape) = (state.0, state.1, state.2, state.3, shape); } else if transparent { + for p in &mut parts { + Arc::make_mut(p).locked = false; + } let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); group.visible = visible; group.locked = locked; @@ -352,6 +355,9 @@ pub(super) fn fill_slots( // A wrap object stays one: the page's parts of it in a group, when there are several. if wrap.is_some() { if parts.len() > 1 { + for p in &mut parts { + Arc::make_mut(p).locked = false; + } let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); group.visible = visible; group.locked = locked; diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 8fc5e2541b..bc797c2e38 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8338,7 +8338,7 @@ fn ai_locked_layers_and_groups_preserve_locks() { #[test] fn ai_fallback_to_pdf_part_preserves_private_stream_layer_and_group_locks() { use std::sync::Arc; - let art_locked_group = format!("1 A\nu\n%_/ArtDictionary :\n%(Locked Subgroup) /String (AIArtName) ,\n%_;\n{}\nU\n0 A", square(10, 10)); + let art_locked_group = format!("1 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(Locked Subgroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10)); let locked_l = locked_layer("Map Layer", &art_locked_group); let n = native(&locked_l); let file = private(&n); @@ -8366,8 +8366,8 @@ fn ai_fallback_to_pdf_part_preserves_private_stream_layer_and_group_locks() { #[test] fn ai_duplicate_group_names_under_different_layers_preserve_individual_lock_states() { use std::sync::Arc; - let art_locked_group = format!("1 A\nu\n%_/ArtDictionary :\n%(SharedGroup) /String (AIArtName) ,\n%_;\n{}\nU\n0 A", square(10, 10)); - let art_unlocked_group = format!("0 A\nu\n%_/ArtDictionary :\n%(SharedGroup) /String (AIArtName) ,\n%_;\n{}\nU\n0 A", square(10, 10)); + let art_locked_group = format!("1 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(SharedGroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10)); + let art_unlocked_group = format!("0 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(SharedGroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10)); let layer_a = layer("Layer A", true, &art_locked_group); let layer_b = layer("Layer B", true, &art_unlocked_group); let n = native(&format!("{layer_a}{layer_b}")); @@ -8433,7 +8433,7 @@ fn ai_reordered_mixed_named_and_unnamed_children_preserve_locks() { } let mut visible_layers = vec![Arc::new(vis_layer)]; - let private_layers = vec![Arc::new(priv_layer)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)]; super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); let roads = visible_layers[0].children().unwrap()[0].clone(); @@ -8478,15 +8478,15 @@ fn ai_reordered_three_children_roads_triangle_circle_preserve_locks() { } let mut visible_layers = vec![Arc::new(vis_layer)]; - let private_layers = vec![Arc::new(priv_layer)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)]; super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); let vis_tri = visible_layers[0].children().unwrap()[0].clone(); let vis_circ = visible_layers[0].children().unwrap()[1].clone(); let vis_rd = visible_layers[0].children().unwrap()[2].clone(); - assert!(vis_tri.locked, "triangle matched to locked private triangle in relative order"); - assert!(!vis_circ.locked, "circle matched to unlocked private circle in relative order"); + assert!(!vis_tri.locked, "unnamed triangle does not pair blindly with private triangle"); + assert!(!vis_circ.locked, "unnamed circle remains unlocked"); assert!(!vis_rd.locked, "Roads matched to unlocked private Roads by unique name"); } @@ -8500,15 +8500,15 @@ fn ai_fallback_with_generated_page_name_preserves_private_layer_lock() { vis_layer.locked = false; let mut visible_layers = vec![Arc::new(vis_layer)]; - let private_layers = vec![Arc::new(priv_layer)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)]; super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); assert_eq!(visible_layers[0].name.as_deref(), Some("Page 1")); - assert!(visible_layers[0].locked, "Page 1 layer matched to locked private layer Map positionally"); + assert!(visible_layers[0].locked, "single-layer document pairs visible and private layers"); } #[test] -fn ai_named_locked_private_child_pairs_with_unnamed_visible_child() { +fn ai_unnamed_visible_child_does_not_pair_with_private_node() { use std::sync::Arc; let mut doc = Document::new(100.0, 100.0); let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); @@ -8533,13 +8533,33 @@ fn ai_named_locked_private_child_pairs_with_unnamed_visible_child() { } let mut visible_layers = vec![Arc::new(vis_layer)]; - let private_layers = vec![Arc::new(priv_layer)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)]; super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); let first = visible_layers[0].children().unwrap()[0].clone(); let second = visible_layers[0].children().unwrap()[1].clone(); assert!(!first.locked, "first unnamed visible group is unlocked"); - assert!(second.locked, "second unnamed visible group pairs positionally with locked Roads group"); + assert!(!second.locked, "second unnamed visible group does not pair positionally with locked Roads group"); +} + +#[test] +fn ai_multi_page_unlayered_pdf_does_not_blindly_pair_with_private_layers() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + let mut priv_1 = Node::layer(doc.alloc_id(), "Layer 1", LayerColor::Preset(0)); + priv_1.locked = true; + let mut priv_2 = Node::layer(doc.alloc_id(), "Layer 2", LayerColor::Preset(0)); + priv_2.locked = false; + + let vis_1 = Node::layer(doc.alloc_id(), "Page 1", LayerColor::Preset(0)); + let vis_2 = Node::layer(doc.alloc_id(), "Page 2", LayerColor::Preset(0)); + + let mut visible_layers = vec![Arc::new(vis_1), Arc::new(vis_2)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_1), super::native::layers::LockTree::from_node(&priv_2)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + assert!(!visible_layers[0].locked, "Page 1 does not pair with private Layer 1"); + assert!(!visible_layers[1].locked, "Page 2 does not pair with private Layer 2"); } #[test] @@ -8571,11 +8591,32 @@ fn ai_duplicate_visible_name_does_not_lock_multiple_from_single_private_node() { } let mut visible_layers = vec![Arc::new(vis_layer)]; - let private_layers = vec![Arc::new(priv_layer)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)]; super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); let r1 = visible_layers[0].children().unwrap()[0].clone(); let r2 = visible_layers[0].children().unwrap()[1].clone(); - assert!(r1.locked, "first Roads group receives the lock from private Roads"); - assert!(!r2.locked, "second Roads group remains unlocked, avoiding duplicate private lock propagation"); + assert!(!r1.locked, "ambiguous duplicate visible name does not receive private lock"); + assert!(!r2.locked, "second duplicate visible name remains unlocked"); +} + +#[test] +fn ai_wrapped_group_places_lock_only_on_wrapper_group_not_children() { + let text = "1 A\n0 0.5 0 0 0 Xy\n(Styled Text) 10 50 Tt\n0 A"; + let art = native(&layer("Live", true, text)); + let (doc, _notes, read) = crate::layered_ai(&private(&art), pdf_two_squares(), vec![], false, true, 1.0); + assert!(read); + for layer in &doc.layers { + if let Some(kids) = layer.children() { + for kid in kids { + if kid.locked + && let Some(subkids) = kid.children() + { + for sub in subkids { + assert!(!sub.locked, "inner child of locked wrapper group must not be locked"); + } + } + } + } + } } diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 07197309b2..943f10d4b4 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -312,7 +312,8 @@ fn read_opened( b.taken = taken; b.warnings = notes; b.intent_cmyk = crate::import_image::output_intent_cmyk(pdf); - b.colors.uncalibrated_rgb = opts.uncalibrated_rgb && picked.iter().filter_map(|&n| pages.get(n)).any(crate::pages::has_private_data); + let doc_ai = crate::pages::has_private_data_doc(pdf); + b.colors.uncalibrated_rgb = opts.uncalibrated_rgb && (doc_ai || picked.iter().filter_map(|&n| pages.get(n)).any(crate::pages::has_private_data)); let cache = InterpreterCache::new(); let mut x = 0.0; // Where the next page's art may begin (a `.ai` page's art reaches past its artboard). @@ -364,7 +365,7 @@ fn read_opened( } let mut parts = b.end_page(); // A PDF-compatible `.ai` (the editor's private data next to the PDF art). - let ai = crate::pages::has_private_data(page); + let ai = doc_ai || crate::pages::has_private_data(page); if ai { drop_page_fill(&mut parts, xf.transform_rect_bbox(crate::pages::page_box(page, CropTo::Crop))); b.warn(OFF_ARTBOARD_NOTE); diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index f058913a76..57516b2de4 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -634,10 +634,15 @@ fn inflated(stream: &Stream<'_>, most: usize) -> Result, String> { Ok(out) } -/// Does `page` carry an editor's private data (`PieceInfo` keys starting with `AIPrivateData`)? +/// Does `page` carry an editor's private data (`PieceInfo` keys starting with `AIPrivateData` or `AIPDFPrivateData`)? /// A file saved without PDF compatibility keeps its art there and shows a placeholder page. pub(crate) fn has_private_data(page: &Page<'_>) -> bool { - piece_info_has(page, &[b"AIPrivateData"]) + piece_info_has(page, &[b"AIPrivateData", b"AIPDFPrivateData"]) +} + +/// Does `pdf` carry an editor's private data at page or document catalog level? +pub(crate) fn has_private_data_doc(pdf: &Pdf) -> bool { + has_private_data_keys(pdf) } /// Does `page` state where its art is: an art, trim or bleed box (ISO 32000-1 §14.11.2, the diff --git a/crates/pdf/tests/import_layers.rs b/crates/pdf/tests/import_layers.rs index a82bb7a415..429897fdcd 100644 --- a/crates/pdf/tests/import_layers.rs +++ b/crates/pdf/tests/import_layers.rs @@ -51,3 +51,28 @@ fn ai_fixture_with_locked_group_and_locked_object_imports_with_locks_preserved() } } } + +#[test] +fn catalog_level_piece_info_with_aipdfprivatedata_detects_ai_data_and_preserves_locks() { + let (a, b) = (first_extra(1), first_extra(1) + 1); + let order_obj = first_extra(1) + 2; + let objs = ["<< /Type /OCG /Name (Layer1) >>".to_string(), "<< /Type /OCG /Name (LockedGroup) /Locked true >>".to_string()]; + let catalog = format!( + "/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << /Order {order_obj} 0 R >> >> \ + /PieceInfo << /Illustrator << /Private << /AIPDFPrivateData1 7 /NumBlock 1 >> >> >>" + ); + let order_body = format!("[{a} 0 R [{b} 0 R]]"); + let content = "/OC /MC0 BDC 1 0 0 rg 10 10 20 20 re f EMC \ + /OC /MC1 BDC 0 1 0 rg 30 30 20 20 re f EMC \ + 0 0 0 rg 0 0 10 10 re f"; + let page = PdfPage { resources: format!("/Properties << /MC0 {a} 0 R /MC1 {b} 0 R >>"), ..PdfPage::new(100.0, 100.0, content) }; + let bytes = pdf_with_catalog(&[page], &[&objs[0], &objs[1], &order_body], &catalog, None); + let doc = import(&bytes).unwrap(); + + let layer1 = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer1")).expect("Layer1 exists"); + assert!(!layer1.locked, "Layer1 is not locked"); + + let children = layer1.children().expect("Layer1 has children"); + let locked_group = children.iter().find(|n| n.name.as_deref() == Some("LockedGroup")).expect("LockedGroup exists"); + assert!(locked_group.locked, "LockedGroup has locked: true"); +} From 820610232b04af72a5aefbde5158b5d9100b7c7a Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:55:17 +0530 Subject: [PATCH 04/14] Fix catalog-level private data check to match only AIPrivateData --- crates/pdf/src/pages.rs | 9 +++++---- crates/pdf/tests/import_layers.rs | 4 ++-- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 57516b2de4..79a1b68a5d 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -634,15 +634,16 @@ fn inflated(stream: &Stream<'_>, most: usize) -> Result, String> { Ok(out) } -/// Does `page` carry an editor's private data (`PieceInfo` keys starting with `AIPrivateData` or `AIPDFPrivateData`)? +/// Does `page` carry an editor's private data (`PieceInfo` keys starting with `AIPrivateData`)? /// A file saved without PDF compatibility keeps its art there and shows a placeholder page. pub(crate) fn has_private_data(page: &Page<'_>) -> bool { - piece_info_has(page, &[b"AIPrivateData", b"AIPDFPrivateData"]) + piece_info_has(page, &[b"AIPrivateData"]) } -/// Does `pdf` carry an editor's private data at page or document catalog level? +/// Does `pdf` carry an editor's private data in its root document catalog (`AIPrivateData`)? pub(crate) fn has_private_data_doc(pdf: &Pdf) -> bool { - has_private_data_keys(pdf) + let xref = pdf.xref(); + xref.get::>(xref.root_id()).is_some_and(|root| dict_piece_info_has(&root, &[b"AIPrivateData"])) } /// Does `page` state where its art is: an art, trim or bleed box (ISO 32000-1 §14.11.2, the diff --git a/crates/pdf/tests/import_layers.rs b/crates/pdf/tests/import_layers.rs index 429897fdcd..a5ad8182c0 100644 --- a/crates/pdf/tests/import_layers.rs +++ b/crates/pdf/tests/import_layers.rs @@ -53,13 +53,13 @@ fn ai_fixture_with_locked_group_and_locked_object_imports_with_locks_preserved() } #[test] -fn catalog_level_piece_info_with_aipdfprivatedata_detects_ai_data_and_preserves_locks() { +fn catalog_level_piece_info_with_aiprivatedata_detects_ai_data_and_preserves_locks() { let (a, b) = (first_extra(1), first_extra(1) + 1); let order_obj = first_extra(1) + 2; let objs = ["<< /Type /OCG /Name (Layer1) >>".to_string(), "<< /Type /OCG /Name (LockedGroup) /Locked true >>".to_string()]; let catalog = format!( "/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << /Order {order_obj} 0 R >> >> \ - /PieceInfo << /Illustrator << /Private << /AIPDFPrivateData1 7 /NumBlock 1 >> >> >>" + /PieceInfo << /Illustrator << /Private << /AIPrivateData1 7 /NumBlock 1 >> >> >>" ); let order_body = format!("[{a} 0 R [{b} 0 R]]"); let content = "/OC /MC0 BDC 1 0 0 rg 10 10 20 20 re f EMC \ From bfcac4829f34b5092c6c2582f86d38e163ee3916 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:03:43 +0530 Subject: [PATCH 05/14] Narrow lock handling to spec and deduplicate name matching --- crates/eps/src/import/native/layers.rs | 88 ++++++++------------- crates/pdf/src/import/entry.rs | 5 +- crates/pdf/src/import_scan.rs | 65 ++------------- crates/pdf/src/pages.rs | 78 +++--------------- crates/pdf/src/tests/import_layers.rs | 105 ------------------------- crates/pdf/tests/import_layers.rs | 78 ------------------ 6 files changed, 49 insertions(+), 370 deletions(-) delete mode 100644 crates/pdf/tests/import_layers.rs diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index 1982fefd64..6a123242fd 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -261,6 +261,35 @@ impl LockTree { } } +/// Match unique names between visible nodes and private lock trees. +fn unique_name_pairs>(vis_nodes: &[T], priv_nodes: &[LockTree]) -> Vec<(usize, usize)> { + let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new(); + for (i, p) in priv_nodes.iter().enumerate() { + if let Some(name) = p.name.as_deref() { + let entry = priv_names.entry(name).or_insert((0, i)); + entry.0 += 1; + } + } + + let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for v in vis_nodes.iter() { + if let Some(name) = v.name.as_deref() { + *vis_names.entry(name).or_insert(0) += 1; + } + } + + let mut pairs = Vec::new(); + for (v_idx, vis) in vis_nodes.iter().enumerate() { + if let Some(name) = vis.name.as_deref() + && vis_names.get(name).copied() == Some(1) + && let Some(&(1, p_idx)) = priv_names.get(name) + { + pairs.push((v_idx, p_idx)); + } + } + pairs +} + /// Apply lock states from private data layers to visible PDF layers. pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], private_layers: &[LockTree]) { if private_layers.is_empty() || visible_layers.is_empty() { @@ -274,33 +303,7 @@ pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], privat } // Otherwise, match only layers with identifiable correspondence (matching unique names). - let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new(); - for (i, p) in private_layers.iter().enumerate() { - if let Some(name) = p.name.as_deref() { - let entry = priv_names.entry(name).or_insert((0, i)); - entry.0 += 1; - } - } - - let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); - for v in visible_layers.iter() { - if let Some(name) = v.name.as_deref() { - *vis_names.entry(name).or_insert(0) += 1; - } - } - - let mut pairs = Vec::new(); - for (v_idx, vis) in visible_layers.iter().enumerate() { - if let Some(name) = vis.name.as_deref() - && vis_names.get(name).copied() == Some(1) - && let Some(&(1, p_idx)) = priv_names.get(name) - { - pairs.push((v_idx, p_idx)); - } - } - drop(vis_names); - - for (v_idx, p_idx) in pairs { + for (v_idx, p_idx) in unique_name_pairs(visible_layers, private_layers) { apply_node_locks(Arc::make_mut(&mut visible_layers[v_idx]), &private_layers[p_idx]); } } @@ -314,36 +317,7 @@ fn apply_node_locks(vis: &mut Node, priv_: &LockTree) { return; } - // Index private children: name -> (count, first_index) - let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new(); - for (i, p) in priv_.children.iter().enumerate() { - if let Some(name) = p.name.as_deref() { - let entry = priv_names.entry(name).or_insert((0, i)); - entry.0 += 1; - } - } - - // Index visible children: name -> count - let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); - for v in vis_kids.iter() { - if let Some(name) = v.name.as_deref() { - *vis_names.entry(name).or_insert(0) += 1; - } - } - - // Resolve unique named matches without positional blind pairing - let mut pairs = Vec::new(); - for (v_idx, v) in vis_kids.iter().enumerate() { - if let Some(v_name) = v.name.as_deref() - && vis_names.get(v_name).copied() == Some(1) - && let Some(&(1, p_idx)) = priv_names.get(v_name) - { - pairs.push((v_idx, p_idx)); - } - } - drop(vis_names); - - for (v_idx, p_idx) in pairs { + for (v_idx, p_idx) in unique_name_pairs(vis_kids.as_slice(), &priv_.children) { apply_node_locks(Arc::make_mut(&mut vis_kids[v_idx]), &priv_.children[p_idx]); } } diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 943f10d4b4..07197309b2 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -312,8 +312,7 @@ fn read_opened( b.taken = taken; b.warnings = notes; b.intent_cmyk = crate::import_image::output_intent_cmyk(pdf); - let doc_ai = crate::pages::has_private_data_doc(pdf); - b.colors.uncalibrated_rgb = opts.uncalibrated_rgb && (doc_ai || picked.iter().filter_map(|&n| pages.get(n)).any(crate::pages::has_private_data)); + b.colors.uncalibrated_rgb = opts.uncalibrated_rgb && picked.iter().filter_map(|&n| pages.get(n)).any(crate::pages::has_private_data); let cache = InterpreterCache::new(); let mut x = 0.0; // Where the next page's art may begin (a `.ai` page's art reaches past its artboard). @@ -365,7 +364,7 @@ fn read_opened( } let mut parts = b.end_page(); // A PDF-compatible `.ai` (the editor's private data next to the PDF art). - let ai = doc_ai || crate::pages::has_private_data(page); + let ai = crate::pages::has_private_data(page); if ai { drop_page_fill(&mut parts, xf.transform_rect_bbox(crate::pages::page_box(page, CropTo::Crop))); b.warn(OFF_ARTBOARD_NOTE); diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index 0b21aadce9..6b812224e2 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -83,8 +83,6 @@ pub(crate) struct Ocgs { view_auto: HashSet, /// The groups placed in the layer order. placed: HashSet, - /// The groups that are locked in configuration or dictionary flags. - locked: HashSet, } impl Ocgs { @@ -97,13 +95,9 @@ impl Ocgs { }; let config = props.get::>(b"D").unwrap_or_default(); let refs = |d: &Dict<'_>, key: &[u8]| -> Vec { - if let Some(a) = d.get::>(key) { - items(&a).filter_map(|i| i.as_obj_ref()).map(ObjectIdentifier::from).take(MAX_GROUPS).collect() - } else if let Some(r) = d.get_ref(key) { - vec![ObjectIdentifier::from(r)] - } else { - Vec::new() - } + d.get::>(key) + .map(|a| items(&a).filter_map(|i| i.as_obj_ref()).map(ObjectIdentifier::from).take(MAX_GROUPS).collect()) + .unwrap_or_default() }; let all = refs(&props, b"OCGs"); if config.get::>(b"BaseState").is_some_and(|n| n.as_ref() == b"OFF") { @@ -117,13 +111,10 @@ impl Ocgs { for d in auto.iter().filter(|d| d.get::>(b"Event").is_some_and(|e| e.as_ref() == b"View")) { o.view_auto.extend(refs(d, b"OCGs")); } - let mut locked: HashSet<_> = refs(&config, b"Locked").into_iter().collect(); - locked.extend(refs(&props, b"Locked")); - o.locked = locked; + let locked: HashSet<_> = refs(&config, b"Locked").into_iter().collect(); for id in all { if let Some(d) = xref.get::>(id) { - let is_locked = o.is_locked(id, &d); - o.add(id, &d, is_locked); + o.add(id, &d, locked.contains(&id)); } } if let Some(order) = config.get::>(b"Order") { @@ -179,7 +170,6 @@ impl Ocgs { if let Some(i) = self.index.get(&id) { return *i; } - let locked = locked || self.is_locked(id, d); let name = d.get::>(b"Name").map(|s| text_string(s.as_bytes())).unwrap_or_default(); let print = usage(d, b"Print", b"PrintState") != Some(false); // A view state applies when the configuration says so on opening; an off one hides the @@ -196,11 +186,6 @@ impl Ocgs { self.list.len() - 1 } - /// Is group `id` (dictionary `d`) locked according to configuration or dictionary flags? - fn is_locked(&self, id: ObjectIdentifier, d: &Dict<'_>) -> bool { - self.locked.contains(&id) || is_ocg_dict_locked(d) - } - /// Does the interpreter leave out the art of some group (off in the default configuration)? pub fn skips_any(&self) -> bool { self.index.keys().any(|id| self.off.contains(id)) @@ -221,49 +206,11 @@ impl Ocgs { fn note(&mut self, id: ObjectIdentifier, d: &Dict<'_>) -> Option { match self.index.get(&id) { Some(i) => Some(*i), - None => { - let is_locked = self.is_locked(id, d); - (self.list.len() < MAX_GROUPS).then(|| self.add(id, d, is_locked)) - } + None => (self.list.len() < MAX_GROUPS).then(|| self.add(id, d, false)), } } } -/// Is group dictionary `d` flagged as locked (directly or in its `/Usage`)? -fn is_ocg_dict_locked(d: &Dict<'_>) -> bool { - if d.get::(b"Locked") == Some(true) - || d.get::>(b"Locked").is_some_and(|n| { - let b = n.as_ref(); - b.eq_ignore_ascii_case(b"true") || b.eq_ignore_ascii_case(b"locked") || b.eq_ignore_ascii_case(b"on") - }) - { - return true; - } - if let Some(usage) = d.get::>(b"Usage") { - if usage.get::(b"Locked") == Some(true) - || usage.get::>(b"Locked").is_some_and(|n| { - let b = n.as_ref(); - b.eq_ignore_ascii_case(b"true") || b.eq_ignore_ascii_case(b"locked") || b.eq_ignore_ascii_case(b"on") - }) - { - return true; - } - if let Some(user) = usage.get::>(b"User") - && (user.get::(b"Locked") == Some(true) - || user.get::>(b"Type").is_some_and(|n| n.as_ref().eq_ignore_ascii_case(b"locked")) - || user.get::>(b"User").is_some_and(|s| s.as_bytes().eq_ignore_ascii_case(b"locked"))) - { - return true; - } - if let Some(lock) = usage.get::>(b"Lock") - && lock.get::(b"Locked") != Some(false) - { - return true; - } - } - false -} - /// The state (`ON` → true, `OFF` → false) group `d`'s usage `category` gives in `key`. fn usage(d: &Dict<'_>, category: &[u8], key: &[u8]) -> Option { let state = d.get::>(b"Usage")?.get::>(category)?.get::>(key)?; diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 79a1b68a5d..688964d8db 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -539,30 +539,11 @@ fn private_data(pdf: &Pdf) -> Option> { /// [`private_data`], with why a private data stream can't be read ([`inflated`]). fn read_private_data(pdf: &Pdf) -> Result>, String> { - let xref = pdf.xref(); - let page_private = pdf + let Some(private) = pdf .pages() .first() - .and_then(|page| page.raw().get::>(b"PieceInfo")?.get::>(PRIVATE_DATA_OWNER)?.get::>(b"Private")); - let root_private = xref - .get::>(xref.root_id()) - .and_then(|root| root.get::>(b"PieceInfo")?.get::>(PRIVATE_DATA_OWNER)?.get::>(b"Private")); - let has_supported_data = |dict: &Dict<'_>| dict.contains_key(b"AIPrivateData1") || dict.contains_key(b"AIPDFPrivateData1"); - let private = match (page_private, root_private) { - (Some(page), Some(root)) => { - if has_supported_data(&page) { - Some(page) - } else if has_supported_data(&root) { - Some(root) - } else { - Some(page) - } - } - (Some(page), None) => Some(page), - (None, Some(root)) => Some(root), - (None, None) => None, - }; - let Some(private) = private else { + .and_then(|page| page.raw().get::>(b"PieceInfo")?.get::>(PRIVATE_DATA_OWNER)?.get::>(b"Private")) + else { return Ok(None); }; let key = if private.contains_key(b"AIPrivateData1") { "AIPrivateData" } else { "AIPDFPrivateData" }; @@ -583,9 +564,7 @@ pub fn has_illustrator_data(bytes: &[u8], password: Option<&str>) -> bool { /// [`has_illustrator_data`] of a parsed PDF. fn has_private_data_keys(pdf: &Pdf) -> bool { - let xref = pdf.xref(); pdf.pages().first().is_some_and(|p| piece_info_has(p, &[b"AIPrivateData", b"AIPDFPrivateData"])) - || xref.get::>(xref.root_id()).is_some_and(|root| dict_piece_info_has(&root, &[b"AIPrivateData", b"AIPDFPrivateData"])) } /// `stream` decoded, up to `most` bytes: the decoder is run here rather than by the PDF reader's @@ -640,12 +619,6 @@ pub(crate) fn has_private_data(page: &Page<'_>) -> bool { piece_info_has(page, &[b"AIPrivateData"]) } -/// Does `pdf` carry an editor's private data in its root document catalog (`AIPrivateData`)? -pub(crate) fn has_private_data_doc(pdf: &Pdf) -> bool { - let xref = pdf.xref(); - xref.get::>(xref.root_id()).is_some_and(|root| dict_piece_info_has(&root, &[b"AIPrivateData"])) -} - /// Does `page` state where its art is: an art, trim or bleed box (ISO 32000-1 §14.11.2, the /// extent of the page's meaningful content and of the finished page)? A page written from an /// artboard has them; the notice a file saved without its PDF part shows instead of its art is @@ -654,46 +627,15 @@ pub(crate) fn states_art(page: &Page<'_>) -> bool { [&b"ArtBox"[..], b"TrimBox", b"BleedBox"].iter().any(|k| page.raw().get::<[f32; 4]>(*k).is_some()) } -/// Does dictionary `d`'s `PieceInfo` hold a key starting with one of `prefixes`, up to four dictionaries in? -fn dict_has_piece_info_prefix(d: &Dict<'_>, prefixes: &[&[u8]]) -> bool { - if let Some(priv_dict) = d.get::>(PRIVATE_DATA_OWNER).and_then(|i| i.get::>(b"Private")) - && prefixes.iter().any(|p| priv_dict.keys().any(|k| k.starts_with(p))) - { - return true; - } - const MAX_VISITS: usize = 128; - fn walk(d: &Dict<'_>, prefixes: &[&[u8]], depth: u32, budget: &mut usize) -> bool { - if depth >= 4 || *budget == 0 { - return false; - } - for k in d.keys() { - if *budget == 0 { - return false; - } - *budget -= 1; - if prefixes.iter().any(|p| k.starts_with(p)) { - return true; - } - if let Some(sub) = d.get::>(k.as_ref()) - && walk(&sub, prefixes, depth + 1, budget) - { - return true; - } - } - false - } - let mut budget = MAX_VISITS; - walk(d, prefixes, 0, &mut budget) -} - /// Does `page`'s `PieceInfo` hold a key starting with one of `prefixes`, up to four dictionaries in? fn piece_info_has(page: &Page<'_>, prefixes: &[&[u8]]) -> bool { - page.raw().get::>(b"PieceInfo").is_some_and(|d| dict_has_piece_info_prefix(&d, prefixes)) -} - -/// Does dictionary `d`'s `PieceInfo` hold a key starting with one of `prefixes`, up to four dictionaries in? -fn dict_piece_info_has(d: &Dict<'_>, prefixes: &[&[u8]]) -> bool { - d.get::>(b"PieceInfo").is_some_and(|p| dict_has_piece_info_prefix(&p, prefixes)) + fn walk(d: &Dict<'_>, prefixes: &[&[u8]], depth: u32) -> bool { + depth < 4 + && d.keys().any(|k| { + prefixes.iter().any(|p| k.starts_with(p)) || d.get::>(k.as_ref()).is_some_and(|sub| walk(&sub, prefixes, depth + 1)) + }) + } + page.raw().get::>(b"PieceInfo").is_some_and(|d| walk(&d, prefixes, 0)) } #[cfg(test)] diff --git a/crates/pdf/src/tests/import_layers.rs b/crates/pdf/src/tests/import_layers.rs index 56492fe30a..c0f9dfc970 100644 --- a/crates/pdf/src/tests/import_layers.rs +++ b/crates/pdf/src/tests/import_layers.rs @@ -469,108 +469,3 @@ fn art_deep_in_tags_inside_a_layer_reaches_it() { let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); assert_eq!(colors(shapes), [Color::rgb(1.0, 0.0, 0.0)]); } - -#[test] -fn ocg_dictionary_locked_flag_is_read() { - let (a, b) = (first_extra(1), first_extra(1) + 1); - let objs = ["<< /Type /OCG /Name (Shapes) /Locked true >>".to_string(), "<< /Type /OCG /Name (Plain) >>".to_string()]; - let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << /Order [{a} 0 R {b} 0 R] >> >> "); - let bytes = pdf_with_catalog(&[page([a, b])], &[&objs[0], &objs[1]], &catalog, None); - let d = import(&bytes).unwrap(); - let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); - let plain = d.layers.iter().find(|l| l.name.as_deref() == Some("Plain")).unwrap(); - assert!(shapes.locked, "Shapes has /Locked true in its dictionary"); - assert!(!plain.locked, "Plain is not locked"); -} - -#[test] -fn ocg_dictionary_usage_locked_is_read() { - let (a, b) = (first_extra(1), first_extra(1) + 1); - let objs = ["<< /Type /OCG /Name (Shapes) /Usage << /User << /Type /Locked >> >> >>".to_string(), "<< /Type /OCG /Name (Plain) >>".to_string()]; - let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << /Order [{a} 0 R {b} 0 R] >> >> "); - let bytes = pdf_with_catalog(&[page([a, b])], &[&objs[0], &objs[1]], &catalog, None); - let d = import(&bytes).unwrap(); - let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); - let plain = d.layers.iter().find(|l| l.name.as_deref() == Some("Plain")).unwrap(); - assert!(shapes.locked, "Shapes has /Usage << /User << /Type /Locked >> >>"); - assert!(!plain.locked, "Plain is not locked"); -} - -#[test] -fn oc_properties_root_locked_is_read_and_configs_locked_is_ignored() { - let (a, b) = (first_extra(1), first_extra(1) + 1); - let objs = ["<< /Type /OCG /Name (RootLocked) >>".to_string(), "<< /Type /OCG /Name (ConfigUnlocked) >>".to_string()]; - let catalog = format!( - "/OCProperties << /OCGs [{a} 0 R {b} 0 R] /Locked [{a} 0 R] /Configs [<< /Locked [{b} 0 R] >>] /D << /Order [{a} 0 R {b} 0 R] >> >> " - ); - let bytes = pdf_with_catalog(&[page([a, b])], &[&objs[0], &objs[1]], &catalog, None); - let d = import(&bytes).unwrap(); - let root_locked = d.layers.iter().find(|l| l.name.as_deref() == Some("RootLocked")).unwrap(); - let config_unlocked = d.layers.iter().find(|l| l.name.as_deref() == Some("ConfigUnlocked")).unwrap(); - assert!(root_locked.locked, "RootLocked is in /OCProperties /Locked"); - assert!(!config_unlocked.locked, "ConfigUnlocked is only in alternate /Configs /Locked, so stays unlocked"); -} - -#[test] -fn ocg_noted_from_content_stream_retains_lock() { - let (a, b) = (first_extra(1), first_extra(1) + 1); - let objs = ["<< /Type /OCG /Name (UnlistedLocked) /Locked true >>".to_string(), "<< /Type /OCG /Name (Listed) >>".to_string()]; - // /OCGs only lists {b} (Listed). {a} (UnlistedLocked) is not in /OCGs or /Order. - let catalog = format!("/OCProperties << /OCGs [{b} 0 R] /D << /Order [{b} 0 R] >> >> "); - let content = "/OC /MC0 BDC 1 0 0 rg 10 10 30 30 re f EMC /OC /MC1 BDC 0 1 0 rg 0 0 5 5 re f EMC"; - let p = PdfPage { resources: format!("/Properties << /MC0 {a} 0 R /MC1 {b} 0 R >>"), ..PdfPage::new(100.0, 100.0, content) }; - let bytes = pdf_with_catalog(&[p], &[&objs[0], &objs[1]], &catalog, None); - let d = import(&bytes).unwrap(); - let unlisted = d.layers.iter().find(|l| l.name.as_deref() == Some("UnlistedLocked")).unwrap(); - let listed = d.layers.iter().find(|l| l.name.as_deref() == Some("Listed")).unwrap(); - assert!(unlisted.locked, "UnlistedLocked has /Locked true in its dictionary"); - assert!(!listed.locked, "Listed is not locked"); -} - -#[test] -fn ai_fixture_with_locked_group_and_locked_object_imports_with_locks_preserved() { - let (a, b, c, d) = (first_extra(1), first_extra(1) + 1, first_extra(1) + 2, first_extra(1) + 3); - let order_obj = first_extra(1) + 4; - let objs = [ - "<< /Type /OCG /Name (Layer1) >>".to_string(), - "<< /Type /OCG /Name (LockedGroup) /Locked true >>".to_string(), - "<< /Type /OCG /Name (UnlockedGroup) >>".to_string(), - "<< /Type /OCG /Name (LockedObject) /Locked true >>".to_string(), - ]; - let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R {c} 0 R {d} 0 R] /D << /Order {order_obj} 0 R >> >> "); - let order_body = format!("[{a} 0 R [{b} 0 R {c} 0 R]]"); - let content = "/OC /MC0 BDC 1 0 0 rg 10 10 20 20 re f EMC \ - /OC /MC1 BDC 0 1 0 rg 30 30 20 20 re f EMC \ - /OC /MC2 BDC 0 0 1 rg 50 50 20 20 re f EMC \ - /OC /MC3 BDC 1 1 0 rg 70 70 20 20 re f EMC \ - 0 0 0 rg 0 0 10 10 re f"; - let page = PdfPage { - resources: format!("/Properties << /MC0 {a} 0 R /MC1 {b} 0 R /MC2 {c} 0 R /MC3 {d} 0 R >>"), - entries: "/PieceInfo << /Illustrator << /Private << /AIPrivateData1 7 /NumBlock 1 >> >> >>".into(), - ..PdfPage::new(100.0, 100.0, content) - }; - let bytes = pdf_with_catalog(&[page], &[&objs[0], &objs[1], &objs[2], &objs[3], &order_body], &catalog, None); - let doc = import(&bytes).unwrap(); - - let layer1 = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer1")).expect("Layer1 exists"); - assert!(!layer1.locked, "Layer1 is not locked"); - - let children = layer1.children().expect("Layer1 has children"); - let locked_group = children.iter().find(|n| n.name.as_deref() == Some("LockedGroup")).expect("LockedGroup exists"); - assert!(locked_group.locked, "LockedGroup has locked: true"); - - let unlocked_group = children.iter().find(|n| n.name.as_deref() == Some("UnlockedGroup")).expect("UnlockedGroup exists"); - assert!(!unlocked_group.locked, "UnlockedGroup has locked: false"); - - let locked_obj = doc.layers.iter().find(|l| l.name.as_deref() == Some("LockedObject")).expect("LockedObject exists"); - assert!(locked_obj.locked, "LockedObject has locked: true"); - - if let Some(page_layer) = doc.layers.iter().find(|l| l.name.as_deref() == Some("Page 1")) { - assert!(!page_layer.locked, "Page layer is not locked"); - if let Some(kids) = page_layer.children() { - for kid in kids { - assert!(!kid.locked, "Non-locked object in page layer remains unlocked"); - } - } - } -} diff --git a/crates/pdf/tests/import_layers.rs b/crates/pdf/tests/import_layers.rs deleted file mode 100644 index a5ad8182c0..0000000000 --- a/crates/pdf/tests/import_layers.rs +++ /dev/null @@ -1,78 +0,0 @@ -//! Synthetic regression verifying locked group and locked object import in AI fixtures. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - -use vectorcraft_pdf::import; -use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with_catalog}; - -#[test] -fn ai_fixture_with_locked_group_and_locked_object_imports_with_locks_preserved() { - let (a, b, c, d) = (first_extra(1), first_extra(1) + 1, first_extra(1) + 2, first_extra(1) + 3); - let order_obj = first_extra(1) + 4; - let objs = [ - "<< /Type /OCG /Name (Layer1) >>".to_string(), - "<< /Type /OCG /Name (LockedGroup) /Locked true >>".to_string(), - "<< /Type /OCG /Name (UnlockedGroup) >>".to_string(), - "<< /Type /OCG /Name (LockedObject) /Locked true >>".to_string(), - ]; - let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R {c} 0 R {d} 0 R] /D << /Order {order_obj} 0 R >> >> "); - let order_body = format!("[{a} 0 R [{b} 0 R {c} 0 R]]"); - let content = "/OC /MC0 BDC 1 0 0 rg 10 10 20 20 re f EMC \ - /OC /MC1 BDC 0 1 0 rg 30 30 20 20 re f EMC \ - /OC /MC2 BDC 0 0 1 rg 50 50 20 20 re f EMC \ - /OC /MC3 BDC 1 1 0 rg 70 70 20 20 re f EMC \ - 0 0 0 rg 0 0 10 10 re f"; - let page = PdfPage { - resources: format!("/Properties << /MC0 {a} 0 R /MC1 {b} 0 R /MC2 {c} 0 R /MC3 {d} 0 R >>"), - entries: "/PieceInfo << /Illustrator << /Private << /AIPrivateData1 7 /NumBlock 1 >> >> >>".into(), - ..PdfPage::new(100.0, 100.0, content) - }; - let bytes = pdf_with_catalog(&[page], &[&objs[0], &objs[1], &objs[2], &objs[3], &order_body], &catalog, None); - let doc = import(&bytes).unwrap(); - - let layer1 = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer1")).expect("Layer1 exists"); - assert!(!layer1.locked, "Layer1 is not locked"); - - let children = layer1.children().expect("Layer1 has children"); - let locked_group = children.iter().find(|n| n.name.as_deref() == Some("LockedGroup")).expect("LockedGroup exists"); - assert!(locked_group.locked, "LockedGroup has locked: true"); - - let unlocked_group = children.iter().find(|n| n.name.as_deref() == Some("UnlockedGroup")).expect("UnlockedGroup exists"); - assert!(!unlocked_group.locked, "UnlockedGroup has locked: false"); - - let locked_obj = doc.layers.iter().find(|l| l.name.as_deref() == Some("LockedObject")).expect("LockedObject exists"); - assert!(locked_obj.locked, "LockedObject has locked: true"); - - if let Some(page_layer) = doc.layers.iter().find(|l| l.name.as_deref() == Some("Page 1")) { - assert!(!page_layer.locked, "Page layer is not locked"); - if let Some(kids) = page_layer.children() { - for kid in kids { - assert!(!kid.locked, "Non-locked object in page layer remains unlocked"); - } - } - } -} - -#[test] -fn catalog_level_piece_info_with_aiprivatedata_detects_ai_data_and_preserves_locks() { - let (a, b) = (first_extra(1), first_extra(1) + 1); - let order_obj = first_extra(1) + 2; - let objs = ["<< /Type /OCG /Name (Layer1) >>".to_string(), "<< /Type /OCG /Name (LockedGroup) /Locked true >>".to_string()]; - let catalog = format!( - "/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << /Order {order_obj} 0 R >> >> \ - /PieceInfo << /Illustrator << /Private << /AIPrivateData1 7 /NumBlock 1 >> >> >>" - ); - let order_body = format!("[{a} 0 R [{b} 0 R]]"); - let content = "/OC /MC0 BDC 1 0 0 rg 10 10 20 20 re f EMC \ - /OC /MC1 BDC 0 1 0 rg 30 30 20 20 re f EMC \ - 0 0 0 rg 0 0 10 10 re f"; - let page = PdfPage { resources: format!("/Properties << /MC0 {a} 0 R /MC1 {b} 0 R >>"), ..PdfPage::new(100.0, 100.0, content) }; - let bytes = pdf_with_catalog(&[page], &[&objs[0], &objs[1], &order_body], &catalog, None); - let doc = import(&bytes).unwrap(); - - let layer1 = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer1")).expect("Layer1 exists"); - assert!(!layer1.locked, "Layer1 is not locked"); - - let children = layer1.children().expect("Layer1 has children"); - let locked_group = children.iter().find(|n| n.name.as_deref() == Some("LockedGroup")).expect("LockedGroup exists"); - assert!(locked_group.locked, "LockedGroup has locked: true"); -} From a6e47e9d1e761e9c8d3c63f4cae1a78c693b7be2 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:36:52 +0530 Subject: [PATCH 06/14] Trigger CI re-run From afe9a98c689b0e30805974a2afb9c0b51672531a Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:12:35 +0530 Subject: [PATCH 07/14] Preserve single-owner hidden state on wrapper groups and add regressions --- crates/eps/src/import/ai/read/ops.rs | 1 + crates/eps/src/import/ai/tests.rs | 29 ++++++++++++++++ crates/eps/src/import/native/slots.rs | 50 +++++++++++++++++++++++++-- crates/eps/src/import/tests_native.rs | 21 ----------- 4 files changed, 78 insertions(+), 23 deletions(-) diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index acde018009..7ac992d089 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -953,6 +953,7 @@ impl<'a> Reader<'a> { (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape) = (1.0, BlendMode::Normal, false, Knockout::Neutral, false); let (visible, locked) = (object.visible, object.locked); (object.opacity, object.blend, object.isolate, object.knockout_shape) = (1.0, BlendMode::Normal, false, false); + object.visible = true; object.locked = false; let mut group = Node::group(self.doc.alloc_id(), vec![Arc::new(look), Arc::new(object)]); (group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = state; diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 1fcf87e7a0..0cf34dd15f 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -12029,6 +12029,35 @@ fn type_with_an_art_brush_keeps_its_drawn_look() { assert_eq!(brushed, 0, "{:?}", r.warnings); } +/// A hidden styled text wrapper group inherits hidden state while its inner text and look retain +/// intrinsic visibility, so showing the group makes the inner artwork visible. +#[test] +fn hidden_styled_text_look_wrapper_group_showing_reveals_inner_text() { + let own: String = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n7 /StoryIndex ,\n;\n".lines().map(|l| format!("%_{l}\n")).collect(); + let object = format!( + "0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n{RED}{}f\nU\n0 0.5 0 0 0 Xy\n0 0 Xd\n6 () XW\n1 Xw\n1 A\n{own}1 (Inked) XW\n0 Xw\n0 A\n", + rect_path(20.0, 18.0, 100.0, 62.0) + ); + let def = format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", RIBBON)); + let r = read_ok(&format!("{def}{}{}", art_style("Ribbon", 1.0, &STRETCHED, ""), layer(&object))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "wrapper group created: {a:#?}"); + let group = &a[0]; + assert!(!group.visible, "wrapper group must inherit hidden state"); + assert!(group.locked, "wrapper group must inherit locked state"); + let children = group.children().expect("must be a group of look and text"); + assert_eq!(children.len(), 2); + for child in children { + assert!(child.visible, "inner child must retain intrinsic visibility"); + assert!(!child.locked, "inner child must not be locked"); + } + let mut shown = (**group).clone(); + shown.visible = true; + for child in shown.children().unwrap() { + assert!(child.visible, "inner child remains visible when parent group is shown"); + } +} + /// Each copy a Scatter brush places is its section's art turned over before the copy's rotation: /// the side of the section with y up goes down the page with the rotation at 0° to the page, and /// to the right of the path's direction when the rotation follows the path. A rotation turns the diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index 414a2d321c..d67c8e3ef5 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -342,7 +342,9 @@ pub(super) fn fill_slots( (p.opacity, p.blend, p.isolate, p.knockout, p.knockout_shape) = (state.0, state.1, state.2, state.3, shape); } else if transparent { for p in &mut parts { - Arc::make_mut(p).locked = false; + let p = Arc::make_mut(p); + p.visible = true; + p.locked = false; } let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); group.visible = visible; @@ -356,7 +358,9 @@ pub(super) fn fill_slots( if wrap.is_some() { if parts.len() > 1 { for p in &mut parts { - Arc::make_mut(p).locked = false; + let p = Arc::make_mut(p); + p.visible = true; + p.locked = false; } let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); group.visible = visible; @@ -706,4 +710,46 @@ mod tests { let inner = nodes[0].children().unwrap()[0].id; assert_eq!(filled.get(&slot), Some(&Filled { text: vec![inner], objects: vec![nodes[0].id, nodes[1].id] })); } + + /// A transparent slot wrapper group inherits hidden state while its inner children retain + /// intrinsic visibility, so showing the group makes the inner artwork visible. + #[test] + fn transparent_slot_wrapper_group_showing_reveals_inner_art() { + let mut doc = Document::new(100.0, 100.0); + let mut slot = Node::group(doc.alloc_id(), vec![]); + slot.name = Some("\u{0}text0:0".into()); + slot.visible = false; + slot.locked = true; + slot.opacity = 0.5; // see_through(n) == true -> transparent == true + + let part = |doc: &mut Document, x: f64| { + let t = vectorcraft_doc::TextObject::point(Point::new(x, 50.0), "Part", Default::default()); + Arc::new(Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)))) + }; + let parts = vec![part(&mut doc, 10.0), part(&mut doc, 60.0)]; + let mut nodes = vec![Arc::new(slot)]; + let mut content = vec![Content::Page(parts)].into_iter(); + let (mut empty, mut made, mut filled) = (0, vec![], std::collections::HashMap::new()); + fill_slots(&mut doc, &mut nodes, &mut content, &Default::default(), &mut empty, &mut made, &mut vec![], &mut filled); + + assert_eq!(nodes.len(), 1); + let group = &nodes[0]; + assert!(!group.visible, "wrapper group must inherit hidden state (visible = false)"); + assert!(group.locked, "wrapper group must inherit locked state"); + + let children = group.children().expect("must be a group of parts"); + assert_eq!(children.len(), 2); + for child in children { + assert!(child.visible, "inner child must retain intrinsic visibility (visible = true)"); + assert!(!child.locked, "inner child must not remain locked"); + } + + // Showing the group updates only the group node's visible field: + let mut shown = (**group).clone(); + shown.visible = true; + assert!(shown.visible); + for child in shown.children().unwrap() { + assert!(child.visible, "inner child is visible when parent group is shown"); + } + } } diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index bc797c2e38..ca7844d69f 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8599,24 +8599,3 @@ fn ai_duplicate_visible_name_does_not_lock_multiple_from_single_private_node() { assert!(!r1.locked, "ambiguous duplicate visible name does not receive private lock"); assert!(!r2.locked, "second duplicate visible name remains unlocked"); } - -#[test] -fn ai_wrapped_group_places_lock_only_on_wrapper_group_not_children() { - let text = "1 A\n0 0.5 0 0 0 Xy\n(Styled Text) 10 50 Tt\n0 A"; - let art = native(&layer("Live", true, text)); - let (doc, _notes, read) = crate::layered_ai(&private(&art), pdf_two_squares(), vec![], false, true, 1.0); - assert!(read); - for layer in &doc.layers { - if let Some(kids) = layer.children() { - for kid in kids { - if kid.locked - && let Some(subkids) = kid.children() - { - for sub in subkids { - assert!(!sub.locked, "inner child of locked wrapper group must not be locked"); - } - } - } - } - } -} From af4266f4e3bc0ba713e6f739a2fd167c140d077f Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:42:10 +0530 Subject: [PATCH 08/14] Preserve intrinsic child visibility in slot wrapper groups without overwriting --- crates/eps/src/import/native/slots.rs | 99 +++++++++++++++++++-------- 1 file changed, 72 insertions(+), 27 deletions(-) diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index d67c8e3ef5..eb8959c9d4 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -307,12 +307,6 @@ pub(super) fn fill_slots( .iter() .map(|p| { let mut p = reid(doc, p); - if !visible { - Arc::make_mut(&mut p).visible = false; - } - if locked { - Arc::make_mut(&mut p).locked = true; - } if let Some(name) = name.filter(|_| matches!(p.kind, NodeKind::Text(_))) { Arc::make_mut(&mut p).name = Some(name.clone()); } @@ -321,6 +315,7 @@ pub(super) fn fill_slots( .collect(); let mut text = vec![]; text_ids(&parts, &mut text); + let mut wrapped = false; // When the page draws each of them with no transparency, the slot's, or the slot's // combined with that of the objects around it, the slot's takes its place: on the one // part, or on a group of several when the slot has transparency. Otherwise every part @@ -341,36 +336,39 @@ pub(super) fn fill_slots( let p = Arc::make_mut(p); (p.opacity, p.blend, p.isolate, p.knockout, p.knockout_shape) = (state.0, state.1, state.2, state.3, shape); } else if transparent { - for p in &mut parts { - let p = Arc::make_mut(p); - p.visible = true; - p.locked = false; - } let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); group.visible = visible; group.locked = locked; (group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = (state.0, state.1, state.2, state.3, shape); parts.push(Arc::new(group)); + wrapped = true; } } // A wrap object stays one: the page's parts of it in a group, when there are several. if wrap.is_some() { if parts.len() > 1 { - for p in &mut parts { - let p = Arc::make_mut(p); - p.visible = true; - p.locked = false; - } let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); group.visible = visible; group.locked = locked; parts.push(Arc::new(group)); + wrapped = true; } for p in &mut parts { Arc::make_mut(p).extras_mut().wrap = wrap; } } + if !wrapped { + for p in &mut parts { + let p = Arc::make_mut(p); + if !visible { + p.visible = false; + } + if locked { + p.locked = true; + } + } + } // One text object with the slot's appearance and transparency keeps its graphic style. if let ([p], Some(a)) = (parts.as_mut_slice(), styled.as_ref()) && linked.is_some() @@ -712,7 +710,8 @@ mod tests { } /// A transparent slot wrapper group inherits hidden state while its inner children retain - /// intrinsic visibility, so showing the group makes the inner artwork visible. + /// their original visibility (both visible and intrinsically hidden), so showing the group + /// reveals only the intrinsically visible artwork. #[test] fn transparent_slot_wrapper_group_showing_reveals_inner_art() { let mut doc = Document::new(100.0, 100.0); @@ -722,11 +721,14 @@ mod tests { slot.locked = true; slot.opacity = 0.5; // see_through(n) == true -> transparent == true - let part = |doc: &mut Document, x: f64| { + let part = |doc: &mut Document, x: f64, visible: bool| { let t = vectorcraft_doc::TextObject::point(Point::new(x, 50.0), "Part", Default::default()); - Arc::new(Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)))) + let mut node = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + node.visible = visible; + Arc::new(node) }; - let parts = vec![part(&mut doc, 10.0), part(&mut doc, 60.0)]; + // Page run contains both a visible child and an intrinsically hidden child: + let parts = vec![part(&mut doc, 10.0, true), part(&mut doc, 60.0, false)]; let mut nodes = vec![Arc::new(slot)]; let mut content = vec![Content::Page(parts)].into_iter(); let (mut empty, mut made, mut filled) = (0, vec![], std::collections::HashMap::new()); @@ -739,17 +741,60 @@ mod tests { let children = group.children().expect("must be a group of parts"); assert_eq!(children.len(), 2); - for child in children { - assert!(child.visible, "inner child must retain intrinsic visibility (visible = true)"); - assert!(!child.locked, "inner child must not remain locked"); - } + assert!(children[0].visible, "intrinsically visible child retains visible = true"); + assert!(!children[0].locked, "inner child must not be locked"); + assert!(!children[1].visible, "intrinsically hidden child retains visible = false"); + assert!(!children[1].locked, "inner child must not be locked"); // Showing the group updates only the group node's visible field: let mut shown = (**group).clone(); shown.visible = true; assert!(shown.visible); - for child in shown.children().unwrap() { - assert!(child.visible, "inner child is visible when parent group is shown"); - } + let shown_children = shown.children().unwrap(); + assert!(shown_children[0].visible, "intrinsically visible child is visible when parent group is shown"); + assert!(!shown_children[1].visible, "intrinsically hidden child remains hidden when parent group is shown"); + } + + /// A wrap slot wrapper group inherits hidden and locked states without overwriting children's + /// original visibility flags when a page run contains both visible and intrinsically hidden children. + #[test] + fn wrap_slot_wrapper_group_preserves_child_visibility_and_showing_reveals_art() { + let mut doc = Document::new(100.0, 100.0); + let mut slot = Node::group(doc.alloc_id(), vec![]); + slot.name = Some("\u{0}text0:0".into()); + slot.visible = false; + slot.locked = true; + let wrap = vectorcraft_doc::TextWrap { offset: 3.0, invert: true }; + slot.extras_mut().wrap = Some(wrap); + + let part = |doc: &mut Document, x: f64, visible: bool| { + let t = vectorcraft_doc::TextObject::point(Point::new(x, 50.0), "Part", Default::default()); + let mut node = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + node.visible = visible; + Arc::new(node) + }; + let parts = vec![part(&mut doc, 10.0, true), part(&mut doc, 60.0, false)]; + let mut nodes = vec![Arc::new(slot)]; + let mut content = vec![Content::Page(parts)].into_iter(); + let (mut empty, mut made, mut filled) = (0, vec![], std::collections::HashMap::new()); + fill_slots(&mut doc, &mut nodes, &mut content, &Default::default(), &mut empty, &mut made, &mut vec![], &mut filled); + + assert_eq!(nodes.len(), 1); + let group = &nodes[0]; + assert!(!group.visible, "wrap wrapper group must inherit hidden state"); + assert!(group.locked, "wrap wrapper group must inherit locked state"); + + let children = group.children().expect("must be a group of parts"); + assert_eq!(children.len(), 2); + assert!(children[0].visible, "intrinsically visible child retains visible = true"); + assert!(!children[0].locked, "inner child must not be locked"); + assert!(!children[1].visible, "intrinsically hidden child retains visible = false"); + assert!(!children[1].locked, "inner child must not be locked"); + + let mut shown = (**group).clone(); + shown.visible = true; + let shown_children = shown.children().unwrap(); + assert!(shown_children[0].visible, "intrinsically visible child is visible when parent group is shown"); + assert!(!shown_children[1].visible, "intrinsically hidden child remains hidden when parent group is shown"); } } From f94380622b405d3e4c40e934e24f2ca6fd3c6cb0 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Sun, 29 Nov 2026 21:07:31 +0530 Subject: [PATCH 09/14] Open .ai files with many made text objects through their layers (#9176) The reported file has 2106 text objects; its text document makes the type of all but 5. The import still counted every text object against each of the page's 2049 text objects (4.3 million pairs, past MAX_PAIRS), so it fell back to the PDF part, which has no groups or names to carry locks. Only the text objects whose type isn't made are matched with the page's words. The made ones are weighed only by where they lie, a box against a box, so they get their own limit, MAX_PLACE_PAIRS (4 x MAX_PAIRS). The reported file now opens through its layers with its 20 locked objects locked. The fallback's lock snapshot is now read only when the PDF part is used, and only when the layers could be read. The regression builds its own editing data and PDF part with the reported file's structure; nothing of the reported file is committed. --- crates/eps/src/import/native/build.rs | 10 ++++--- crates/eps/src/import/native/layers.rs | 16 ++++++---- crates/eps/src/import/native/slots.rs | 5 ++++ crates/eps/src/import/tests_native.rs | 41 ++++++++++++++++++++++++++ 4 files changed, 62 insertions(+), 10 deletions(-) diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 2cba146548..81c1181659 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -4,8 +4,8 @@ use super::compare::{ }; use super::plan::{made_only, make_slots, plan, readable_all}; use super::slots::{ - ART_LEFT_OUT, Content, DREW_DIFFERENTLY, Filled, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT, - collect_slots, extent, few, fill_slots, letters, text_objects, words, + ART_LEFT_OUT, Content, DREW_DIFFERENTLY, Filled, MAX_PAIRS, MAX_PLACE_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, + TYPE_LEFT_OUT, collect_slots, extent, few, fill_slots, letters, text_objects, words, }; use super::{ Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, VariableKind, Vec2, ai, @@ -1487,9 +1487,11 @@ fn slot_content( } // The page's type is matched with every text object whose type isn't made, and weighed against // where every made one draws: that has its limits (the slots of type that looks draw are within - // them, see `build_from`). + // them, see `build_from`). A file whose text document makes all but a few text objects is + // matched only with those few (#9176). let open = infos.iter().zip(&made).filter(|(i, m)| i.look.is_none() && m.is_none()).count(); - if open > MAX_SLOTS || infos.len().saturating_mul(pages[0].len()) > MAX_PAIRS { + let shown = pages[0].len(); + if open > MAX_SLOTS || open.saturating_mul(shown) > MAX_PAIRS || infos.len().saturating_mul(shown) > MAX_PLACE_PAIRS { return Err("it has too many text objects".into()); } let mut content = plan(infos, stories, made, template, to_doc, pages, notes); diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index 6a123242fd..21ab411985 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -172,17 +172,19 @@ pub fn layered_ai_from( } // The PDF part, its pages placed and named as the editing data's artboards are, when the // layers can't be used (`why`). - let structure = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)); - let private_layers: Vec = - structure.as_ref().ok().map(|s| s.doc.layers.iter().map(|l| LockTree::from_node(l)).collect()).unwrap_or_default(); - let from_pdf_part = |mut visible: Document, mut warnings: Vec, why: &str| { + let from_pdf_part = |mut visible: Document, mut warnings: Vec, why: &str, layers_read: bool| { let mut read = ai::Names::new(names); let mut board_names = ai::Names::new(names); let (boards, active) = ai::artboards(&data, &mut board_names); if place_pages(&boards, active, &mut visible, unit) { read.absorb(board_names); } - apply_private_layer_locks(&mut visible.layers, &private_layers); + // The editing data's locks, read again only here (and only when its layers could be read): + // the layers read below are spent on the editable document, which most files open as. + if let Some(layers) = layers_read.then(|| ai::read_over_page(&data, false, names).ok()).flatten() { + let private_layers: Vec = layers.doc.layers.iter().map(|l| LockTree::from_node(l)).collect(); + apply_private_layer_locks(&mut visible.layers, &private_layers); + } let have = visible.patterns.len(); let own_palette = use_palette(&data, &mut visible, &mut read); use_brushes(&data, &mut visible, have, &mut warnings, &mut read); @@ -196,6 +198,8 @@ pub fn layered_ai_from( // The envelopes of type the page doesn't hold against layers that don't draw as it, and how many // envelopes of type the layers had. let (mut free, mut count) = (None, 0); + let structure = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)); + let layers_read = structure.is_ok(); let built = structure.and_then(|structure| { count = structure.warped_type.envelope_count(); build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text) @@ -227,7 +231,7 @@ pub fn layered_ai_from( all.extend(notes.into_iter().filter(|n| !all.contains(n)).collect::>()); (done, all, true) } - Err(why) => from_pdf_part(visible, warnings, &why), + Err(why) => from_pdf_part(visible, warnings, &why, layers_read), } } diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index eb8959c9d4..f285cf4028 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -50,6 +50,11 @@ pub(crate) const MAX_TEXT: usize = 16 << 20; /// kept as outlines and a node of the page's type. pub(super) const MAX_PAIRS: usize = 4_000_000; +/// Most pairs of a text object whose type is made and a piece of the page's type weighed only by +/// where each lies (a box against a box, far cheaper than matching the page's type with a text +/// object's words, which [`MAX_PAIRS`] limits). +pub(super) const MAX_PLACE_PAIRS: usize = 4 * MAX_PAIRS; + /// `names` for a note: the first few, and how many more. pub(super) fn few(names: BTreeSet) -> String { const SHOWN: usize = 5; diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index ca7844d69f..b94b4aa7b1 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8599,3 +8599,44 @@ fn ai_duplicate_visible_name_does_not_lock_multiple_from_single_private_node() { assert!(!r1.locked, "ambiguous duplicate visible name does not receive private lock"); assert!(!r2.locked, "second duplicate visible name remains unlocked"); } + +/// #9176: a file with more text objects than the page's type can be matched with each, all but one +/// of them made from its text document, opens with its layers, and what is locked in it stays +/// locked. Only the one text object whose type isn't made is matched with the page's type; the made +/// ones are weighed by where they lie. (Our own minimized copy of the reported file's structure: +/// about two thousand text objects whose type the text document makes, a few it can't, and as many +/// pieces of type on the page, with locked groups.) +#[test] +fn a_file_with_many_made_text_objects_and_one_unread_keeps_its_layers_and_locks() { + // Every text object against every piece of the page's type is past `MAX_PAIRS` (four million). + let many = 2050; + let doc = + last_frame_unread(&text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Odd\r", 0, (8200.0, 8160.0), (0.0, 0.0), 0.0)])); + let locked_group = format!("1 A\nu\n{}\nU\n0 A\n", square(10, 10)); + let art = native_with_text(&layer("Map", true, &(locked_group + &text_object(0).repeat(many) + &text_object(1))), &doc); + // The PDF part: the square, the made type where the text document puts it, once per text object, + // and as many small pieces of type apart from one another, which the one text object whose type + // isn't made takes. + let mut page = pdf_part(10.0, 86.0); + let layer_id = page.layers[0].id; + let put = |page: &mut Document, at: (f64, f64), text: &str, size: f64| { + let style = vectorcraft_doc::CharStyle { size, ..Default::default() }; + let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(at.0, at.1), text, style); + let id = page.alloc_id(); + let end = page.layers[0].children().map_or(0, |c| c.len()); + page.insert(Some(layer_id), end, Node::new(id, NodeKind::Text(Box::new(text)))).unwrap(); + }; + for _ in 0..many { + put(&mut page, (58.5, 38.5), "Hi there", 14.0); + } + for k in 0..many { + // Down each column, so that no two pieces painted one after the other are on one line. + put(&mut page, (1.0 + (k / 46) as f64 * 2.1, 1.0 + (k % 46) as f64 * 2.1), "o", 1.0); + } + let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{w:?}"); + assert_eq!(names(&d), ["Map"], "{w:?}"); + let group = d.layers[0].children().and_then(|c| c.iter().find(|n| matches!(n.kind, NodeKind::Group { .. }))); + assert!(group.is_some_and(|g| g.locked), "the group locked in the file stays locked: {w:?}"); + assert!(all_texts(&d).iter().filter(|t| *t == "Hi there").count() >= many, "{w:?}"); +} From 9f6afc8403b07f6152bce456da25ca61a95d6b5a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:22:31 -0800 Subject: [PATCH 10/14] MCP: dialog params texts name the keys ui.inspect reports ui.inspect lists each open dialog with a key. The params text of these commands, and docs/mcp.md and docs/control-protocol.md, named a key that no open dialog reports: - Layer Options (ui.layerOptions, ui.newLayer): layerOptions, now ui.layerOptions. - The Layers panel's Panel Options: layersPanelOptions, now ui.layersPanelOptions. - The Navigator panel's Panel Options: navigatorPanelOptions, now ui.navigatorPanelOptions. - Document Raster Effects Settings (ui.rasterEffectsSettingsDialog): rasterEffectsSettings, now document.rasterEffectsSettings. - The PDF preset editor (ui.pdfPresetDialog): pdfPreset, now pdf-export. - Save for Web (file.saveForWeb): saveForWeb, now save-for-web. - The Actions panel's Reset Actions question (ui.actionSet.reset): resetActions, now actionsQuestion. Each command now has a test that opens the dialog and checks that its params text names the key ui.inspect lists. --- crates/mcp/src/ui_catalog.rs | 16 ++++++++-------- crates/ui-egui/src/dialogs/layer_options.rs | 16 ++++++++++++++++ .../ui-egui/src/dialogs/layers_panel_options.rs | 13 +++++++++++++ .../src/dialogs/navigator_panel_options.rs | 14 ++++++++++++++ crates/ui-egui/src/dialogs/raster_effects.rs | 14 ++++++++++++++ crates/ui-egui/src/dialogs/save_for_web/tests.rs | 15 +++++++++++++++ crates/ui-egui/src/dialogs/save_pdf/tests.rs | 14 ++++++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 16 ++++++++-------- crates/ui-egui/src/panels/actions/tests_edits.rs | 14 ++++++++++++++ docs/control-protocol.md | 8 ++++---- docs/mcp.md | 8 ++++---- 11 files changed, 124 insertions(+), 24 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 9730bd7853..abbf2d89e6 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1274,7 +1274,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.layerOptions", "Options for Selection…", "", - "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog", + "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `ui.layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog", ), ( "ui.layerDelete", @@ -1292,7 +1292,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.newLayer", "New Layer Options…", "Cmd+Alt+L", - "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer", + "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `ui.layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer", ), ( "ui.newArtboard", @@ -1310,13 +1310,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.layersPanelOptions", "Panel Options…", "", - "{} open the Layers panel's Panel Options: dialog `layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)", + "{} open the Layers panel's Panel Options: dialog `ui.layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)", ), ( "ui.navigatorPanelOptions", "Panel Options…", "", - "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", + "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `ui.navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", ), ( "ui.attributesPanelOptions", @@ -1645,7 +1645,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.rasterEffectsSettingsDialog", "Document Raster Effects Settings Dialog", "", - "{} open Document Raster Effects Settings (dialog `rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too", + "{} open Document Raster Effects Settings (dialog `document.rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too", ), ( "ui.effectGalleryDialog", @@ -1663,7 +1663,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.pdfPresetDialog", "PDF Preset", "", - "{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdfPreset`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets", + "{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdf-export`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets", ), ("file.openRecent11", "Open Recent File 11", "", "{}"), ("file.openRecent12", "Open Recent File 12", "", "{}"), @@ -1918,7 +1918,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.actionSet.reset", "Reset Actions", "", - "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", + "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `actionsQuestion`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", ), ( "ui.actionSet.clear", @@ -1949,7 +1949,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.saveForWeb", "Save for Web (Legacy)…", "Cmd+Alt+Shift+S", - "{} open Save for Web (dialog `saveForWeb`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}", + "{} open Save for Web (dialog `save-for-web`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}", ), ( "file.saveForWeb.browser", diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index fb0ad99911..0553775449 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -1185,4 +1185,20 @@ mod tests { ok(&mut app); assert_eq!(app.session.active().unwrap().doc.node(layer).unwrap().display_name(), "Fresh Draft"); } + + /// `ui.layerOptions` and `ui.newLayer` open the dialog whose `key` their params text names, as `ui.inspect` + /// lists it. + #[test] + fn layer_options_params_text_names_the_dialog_key_ui_inspect_lists() { + for (command, arguments) in [("ui.layerOptions", json!({})), ("ui.newLayer", json!({})), ("ui.newLayer", json!({"sublayer": true}))] { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == command).expect("registered").3; + let mut app = app(); + app.run(command, arguments).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, KEY); + assert!(doc.contains(&format!("dialog `{key}`")), "{command} opens `{key}`, which its params text does not name"); + } + } } diff --git a/crates/ui-egui/src/dialogs/layers_panel_options.rs b/crates/ui-egui/src/dialogs/layers_panel_options.rs index 290641848d..0771d6ca38 100644 --- a/crates/ui-egui/src/dialogs/layers_panel_options.rs +++ b/crates/ui-egui/src/dialogs/layers_panel_options.rs @@ -127,4 +127,17 @@ mod tests { let old: crate::UiState = serde_json::from_value(json!({"layers_panel": {"layersOnly": true}})).unwrap(); assert!(old.layers_panel.layers_only && !old.layers_panel.locate_selected, "options saved without it"); } + + /// `ui.layersPanelOptions` opens the dialog whose `key` its params text names, as `ui.inspect` lists it. + #[test] + fn panel_options_params_text_names_the_dialog_key_ui_inspect_lists() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == CMD).expect("registered").3; + let mut app = app(); + app.run(CMD, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, CMD); + assert!(doc.contains(&format!("dialog `{key}`")), "{CMD} opens `{key}`, which its params text does not name"); + } } diff --git a/crates/ui-egui/src/dialogs/navigator_panel_options.rs b/crates/ui-egui/src/dialogs/navigator_panel_options.rs index c3639dbf49..b37a541ac8 100644 --- a/crates/ui-egui/src/dialogs/navigator_panel_options.rs +++ b/crates/ui-egui/src/dialogs/navigator_panel_options.rs @@ -208,4 +208,18 @@ mod tests { let old: crate::UiState = serde_json::from_value(json!({})).unwrap(); assert_eq!(old.navigator_panel, crate::panels::navigator::PanelOptions::default(), "UI state saved without them"); } + + /// `ui.navigatorPanelOptions` without options opens the dialog whose `key` its params text names, as `ui.inspect` + /// lists it. + #[test] + fn panel_options_params_text_names_the_dialog_key_ui_inspect_lists() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == KEY).expect("registered").3; + let mut app = app(); + app.run(KEY, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, KEY); + assert!(doc.contains(&format!("dialog `{key}`")), "{KEY} opens `{key}`, which its params text does not name"); + } } diff --git a/crates/ui-egui/src/dialogs/raster_effects.rs b/crates/ui-egui/src/dialogs/raster_effects.rs index 6e7f191f8f..be61dbe02b 100644 --- a/crates/ui-egui/src/dialogs/raster_effects.rs +++ b/crates/ui-egui/src/dialogs/raster_effects.rs @@ -217,4 +217,18 @@ mod tests { assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }), "the rectangle stays a path"); assert_eq!(st.history.undo.len(), steps + 1); } + + /// `ui.rasterEffectsSettingsDialog` opens the dialog whose `key` its params text names, as `ui.inspect` lists it. + #[test] + fn settings_dialog_params_text_names_the_dialog_key_ui_inspect_lists() { + const COMMAND: &str = "ui.rasterEffectsSettingsDialog"; + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3; + let mut app = app(); + app.run(COMMAND, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, super::CMD); + assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name"); + } } diff --git a/crates/ui-egui/src/dialogs/save_for_web/tests.rs b/crates/ui-egui/src/dialogs/save_for_web/tests.rs index 6c79fb69da..1bf7819ecb 100644 --- a/crates/ui-egui/src/dialogs/save_for_web/tests.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/tests.rs @@ -898,3 +898,18 @@ fn optimize_to_file_size_starts_at_the_size_of_the_art_as_it_is_now() { let bytes = fields(&app)["optimizeK"].as_f64().unwrap() * 1024.0; assert!(bytes >= after as f64 && bytes < after as f64 + 2.0, "{bytes} for {after}"); } + +/// `file.saveForWeb` without settings opens the dialog whose `key` its params text names, as `ui.inspect` lists it. +#[test] +fn params_text_names_the_dialog_key_ui_inspect_lists() { + const COMMAND: &str = "file.saveForWeb"; + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3; + let dir = vectorcraft_testkit::temp_dir("sfw-dialog-key"); + let (mut app, _) = app(&dir, false); + app.run(COMMAND, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, "save-for-web"); + assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name"); +} diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 091a2d5d97..1dad06f331 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -1175,3 +1175,17 @@ fn the_range_bleed_and_subset_fields_are_named() { } } } + +/// `ui.pdfPresetDialog` opens the preset editor whose `key` its params text names, as `ui.inspect` lists it. +#[test] +fn preset_editor_params_text_names_the_dialog_key_ui_inspect_lists() { + const COMMAND: &str = "ui.pdfPresetDialog"; + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3; + let (mut app, _) = app(); + app.run(COMMAND, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, PDF_KEY); + assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name"); +} diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f5e6908a8a..63cf0eaa47 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1275,7 +1275,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.layerOptions", "Options for Selection…", "", - "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog", + "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `ui.layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog", ), ( "ui.layerDelete", @@ -1293,7 +1293,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.newLayer", "New Layer Options…", "Cmd+Alt+L", - "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer", + "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `ui.layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer", ), ( "ui.newArtboard", @@ -1311,13 +1311,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.layersPanelOptions", "Panel Options…", "", - "{} open the Layers panel's Panel Options: dialog `layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)", + "{} open the Layers panel's Panel Options: dialog `ui.layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)", ), ( "ui.navigatorPanelOptions", "Panel Options…", "", - "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", + "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `ui.navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", ), ( "ui.attributesPanelOptions", @@ -1646,7 +1646,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.rasterEffectsSettingsDialog", "Document Raster Effects Settings Dialog", "", - "{} open Document Raster Effects Settings (dialog `rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too", + "{} open Document Raster Effects Settings (dialog `document.rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too", ), ( "ui.effectGalleryDialog", @@ -1664,7 +1664,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.pdfPresetDialog", "PDF Preset", "", - "{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdfPreset`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets", + "{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdf-export`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets", ), ("file.openRecent11", "Open Recent File 11", "", "{}"), ("file.openRecent12", "Open Recent File 12", "", "{}"), @@ -1919,7 +1919,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ crate::panels::actions::RESET, "Reset Actions", "", - "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", + "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `actionsQuestion`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", ), ( crate::panels::actions::CLEAR, @@ -1950,7 +1950,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.saveForWeb", "Save for Web (Legacy)…", "Cmd+Alt+Shift+S", - "{} open Save for Web (dialog `saveForWeb`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}", + "{} open Save for Web (dialog `save-for-web`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}", ), ( "file.saveForWeb.browser", diff --git a/crates/ui-egui/src/panels/actions/tests_edits.rs b/crates/ui-egui/src/panels/actions/tests_edits.rs index 1fe2f13711..14ecbd97d3 100644 --- a/crates/ui-egui/src/panels/actions/tests_edits.rs +++ b/crates/ui-egui/src/panels/actions/tests_edits.rs @@ -1342,3 +1342,17 @@ fn insert_select_object_refuses_bad_params_and_changes_nothing() { } assert!(app.run(INSERT_SELECT_OBJECT, place(json!({"note": "x".repeat(1024)}))).is_ok(), "1,024 bytes goes in"); } + +/// The panel menu's Reset Actions asks in the dialog whose `key` the params text of [`RESET`] names, as `ui.inspect` +/// lists it. +#[test] +fn reset_params_text_names_the_question_key_ui_inspect_lists() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == RESET).expect("registered").3; + let mut app = new_app(); + edits::ask_reset(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, "actionsQuestion"); + assert!(doc.contains(&format!("dialog `{key}`")), "Reset Actions opens `{key}`, which the params text of {RESET} does not name"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index df9b36eee8..7c010b90df 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -597,7 +597,7 @@ keeps the dialog's options as a saved preset. PDF presets: `ui.pdfPresetsDialog {selected?}` opens Edit → PDF Presets (dialog `pdfPresets`, field `selected`: a preset name). Built-in presets are read-only. New… and Edit… open the preset editor, which `ui.pdfPresetDialog {name? -(a saved preset to edit) | preset? (the preset a new one starts from)}` opens too: dialog `pdfPreset`, the Save PDF +(a saved preset to edit) | preset? (the preset a new one starts from)}` opens too: dialog `pdf-export`, the Save PDF dialog's option fields plus `name` and `description`; `ui.dialog.confirm` runs `pdf.preset.save` and returns to PDF Presets (a new preset can't take a name in use). Delete, Import… and Export… are `pdf.preset.delete`, `pdf.preset.import` and `pdf.preset.export`; `ui.dialog.confirm` closes. Opening a `.vcpdfpresets` file with `app.open` @@ -754,7 +754,7 @@ the dock's tab strip while Layers shows) lists the layer commands (New Layer…, Options for Selection…, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Release to Layers, Reverse Order, Template, Hide/Outline/Lock Others or Show/Preview/Unlock All Layers), Paste Remembers Layers (`layer.pasteRemembersLayers`, checked when on) and Panel Options…. Layer Options is the -`layerOptions` dialog (`ui.layerOptions {ids?}`, `ui.newLayer {sublayer?}`), Panel Options the `layersPanelOptions` +`ui.layerOptions` dialog (`ui.layerOptions {ids?}`, `ui.newLayer {sublayer?}`), Panel Options the `ui.layersPanelOptions` dialog (`ui.layersPanelOptions`), and `ui.layersExpand {ids?, open?}` opens or closes rows; see the Layers panel section of `docs/mcp.md` for the row commands (`layer.setCurrent`, `layer.highlight`, `layer.move`…). @@ -766,7 +766,7 @@ File Info: File → File Info… (`file.info` from the menu or Cmd+Alt+Shift+I; stays open. Document Raster Effects Settings: Effect → Document Raster Effects Settings… (`ui.rasterEffectsSettingsDialog` for -agents) opens the `rasterEffectsSettings` dialog. Its fields are what `document.rasterEffectsSettings` reports +agents) opens the `document.rasterEffectsSettings` dialog. Its fields are what `document.rasterEffectsSettings` reports (`resolution`, `colorModel`, `background`, `antiAlias`, `clippingMask`, `addAround` in pt, `preserveSpotColors`); `ui.dialog.confirm` runs it with them as one undo step; a bad value keeps the dialog open. Object → Rasterize… opens a `command` dialog for `object.rasterize` whose fields (`ppi`, `colorModel`, `background`, `antiAlias`, `clippingMask`, @@ -994,7 +994,7 @@ the save dialog) opens `tiffOptions`, `bmpOptions` or `tgaOptions`: the raster r rows off; RLE turns flipped rows off). `ui.dialog.set` the fields and `ui.dialog.confirm` writes the file(s) with `document.export`. -Save for Web: File → Export → Save for Web (Legacy)… (`file.saveForWeb`, Ctrl/Cmd+Alt+Shift+S) opens the `saveForWeb` +Save for Web: File → Export → Save for Web (Legacy)… (`file.saveForWeb`, Ctrl/Cmd+Alt+Shift+S) opens the `save-for-web` dialog on the remembered settings (`webExport.settings`). Its fields are the `document.exportForWeb` settings (`format`, `colors`, `reduction`, `dither`, `quality`, `colorTable`, `width`, `percent`, `output`…; set `preset` to load a preset) plus `__view` (`original`, `optimized`, `2up`, `4up`), `__zoom` (`fit` or a percentage), `__kbps` and diff --git a/docs/mcp.md b/docs/mcp.md index 7ed0eebae6..c077c8211d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4686,7 +4686,7 @@ shows no notice. ## Navigator panel options -The Navigator panel menu's Panel Options… opens the `navigatorPanelOptions` dialog (fields `color`, `solidDashes`), +The Navigator panel menu's Panel Options… opens the `ui.navigatorPanelOptions` dialog (fields `color`, `solidDashes`), and `ui.navigatorPanelOptions {color?, solidDashes?, viewArtboardContentsOnly?}` sets the options without it → `{color, solidDashes, viewArtboardContentsOnly}`; with none of the keys it opens the dialog. `color` is the color the panel's view box is drawn in: `#rrggbb` or a preset name. @@ -5855,7 +5855,7 @@ already walks Image Trace. Short agent entry points: next free number when its name is in use (`Default Actions 2`), and keeps the current set and the selection. Omitted params count as `{}`. Params of another type, another key, another `mode`, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. Reset records no undo step. The panel menu's Reset - Actions is disabled while an action records or plays; it opens a `resetActions` question (fields `message`, + Actions is disabled while an action records or plays; it opens an `actionsQuestion` question (fields `message`, `detail`, `append`): OK runs this with `replace`, Append with `append`, and `ui.dialog.cancel` changes nothing. `ui.actionSet.clear {ids?: [id]}` is Clear Actions, and returns `{cleared}`, the number of sets deleted. It deletes every set in the panel with its actions, the built-in Default Actions set included, so no set is current or @@ -7736,14 +7736,14 @@ and `layerRows`, the rows highlighted in the panel. `object.setProps` return an error when they would give either name to another path directly in the group, and a path pasted directly into the group under either name loses its name. - **Dialogs and panel state** (control channel and the app's MCP): `ui.layerOptions {ids?}` and `ui.newLayer - {sublayer?}` open Layer Options (dialog `layerOptions`: name, color, template, locked, visible, printable, preview, + {sublayer?}` open Layer Options (dialog `ui.layerOptions`: name, color, template, locked, visible, printable, preview, dimImages, dimPercent; for existing rows, unchanged approval adds no undo step; an edit is one undo step. Existing rows keep their stored names unless Name is edited or explicitly set through `ui.dialog.set`, so generated labels remain automatic. `ui.dialog.set` of `template` also sets `locked` and `dimImages`, as the checkbox does, except a Dim Images set before it; for several `ids` the dialog shows the first row's settings, and OK sends only the fields set with a control or `ui.dialog.set`; Cmd/Ctrl+Alt+L runs `ui.newLayer` for a new layer; in isolation mode `ui.newLayer` for a layer that would be outside the isolated art is an error, OK in the dialog checks again and returns the same error, - and the Layers panel's New Layer and New Sublayer are off then), `ui.layersPanelOptions` opens Panel Options (`layersPanelOptions`: + and the Layers panel's New Layer and New Sublayer are off then), `ui.layersPanelOptions` opens Panel Options (`ui.layersPanelOptions`: layersOnly, locateSelected, rowSize small|medium|large|other, otherSize, thumbLayers, thumbGroups, thumbObjects), and `ui.layersExpand {ids?, open?}` opens or closes rows as their triangles do (Alt-click: everything inside). With `locateSelected` on (Locate Selected Objects, off by default), when the last selected object changes on the canvas From 57631406d7e6fd1b6eb6666820d41b23126a13b3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:03:39 -0800 Subject: [PATCH 11/14] Symbols: art dropped on a symbol with Alt+Shift redefines it and stays as it was Art dragged off the canvas and released on a symbol's tile or row with Alt (Option on macOS) held redefines that symbol, and the dropped art becomes an instance of it. With Shift held as well, the panel now sends `symbol.update` with `keepArt: true`, so the art stays ordinary art in its place, as Redefine Symbol from the panel menu with Shift leaves it. The redefine is one undo step either way. Docs: docs/mcp.md (symbol.update). --- crates/ui-egui/src/panels/symbols.rs | 11 +++++++--- crates/ui-egui/src/panels/symbols/tests.rs | 25 ++++++++++++++++++++++ docs/mcp.md | 5 +++-- 3 files changed, 36 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index e8dbf1a468..63edfcb53b 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -535,7 +535,7 @@ const AT_START: usize = 4; /// A click makes a symbol current and a double click edits it; a symbol drags out to the canvas, /// onto New Symbol (duplicated) or onto Delete Symbol. Art dragged off the canvas and dropped on the /// list becomes a symbol (Shift at the release keeps the art as ordinary art); dropped on a symbol -/// with Alt it redefines that symbol in one undo step. +/// with Alt it redefines that symbol in one undo step, and Alt+Shift also keeps the art. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let Some((doc, revision, uid, reverts, has_sel)) = app.session.active().map(|st| (st.doc.clone(), st.revision, st.uid, st.reverts, !st.selection.is_empty())) @@ -651,8 +651,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { && redefines(&doc, ids) { // Redefine Symbol with the dropped art, which becomes an instance of it, in one - // undo step. Alt art that cannot redefine changes nothing. - run_reported(app, "symbol.update", json!({ "name": target.name, "ids": node_ids(ids) })); + // undo step; Shift keeps the art as ordinary art, as the menu's Redefine Symbol + // does. Alt art that cannot redefine changes nothing. + let mut params = json!({ "name": target.name, "ids": node_ids(ids) }); + if mods.shift { + params["keepArt"] = json!(true); + } + run_reported(app, "symbol.update", params); } } PresetEvent::Menu { target, command, .. } => item_command(app, &target.name, &command), diff --git a/crates/ui-egui/src/panels/symbols/tests.rs b/crates/ui-egui/src/panels/symbols/tests.rs index 262f1d7cdb..23bd444373 100644 --- a/crates/ui-egui/src/panels/symbols/tests.rs +++ b/crates/ui-egui/src/panels/symbols/tests.rs @@ -1638,6 +1638,31 @@ fn alt_art_drop_on_a_symbol_redefines_that_symbol_in_one_step() { } } +/// Art released with Alt and Shift held on a symbol's tile or row, in each view, redefines that +/// symbol and stays ordinary art in its place, as Redefine Symbol with Shift leaves it, in one +/// undo step. +#[test] +fn alt_shift_art_drop_on_a_symbol_redefines_it_and_keeps_the_art() { + for view in ["thumbnail", "smallList", "largeList"] { + let (app, shape, placed) = alt_drop_doc(view); + let leaf = symbol_art(&app, "Leaf"); + let undo = undo_len(&app); + let mut p = harness(app, art_and_symbols); + p.drag("Art", "Leaf", Modifiers::ALT | Modifiers::SHIFT); + let mut app = p.app(); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "{view}: no symbol added"); + assert_eq!(undo_len(&app), undo + 1, "{view}: one undo step"); + let doc = app.session.active().unwrap().doc.clone(); + let ratio = doc.node(placed).and_then(|n| n.geometric_bounds()).map(|b| b.width() / b.height()); + assert!(ratio.is_some_and(|r| (r - 2.0).abs() < 1e-6), "{view}: Leaf is the dropped art: {ratio:?}"); + assert!(doc.node(shape).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })), "{view}: the art keeps its id as a path"); + assert_eq!(art(&app, "Leaf"), (1, 1), "{view}: the art stays ordinary art, not a Leaf instance"); + app.run("edit.undo", json!({})).unwrap(); + assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "{view}: undo restores Leaf"); + assert_eq!(art(&app, "Leaf"), (1, 1), "{view}: undo leaves the art"); + } +} + /// An Alt drop that cannot redefine the symbol under the pointer changes nothing, makes no new /// symbol and adds no undo step: art holding an instance of the symbol, which the redefine /// refuses, a layer, and art released outside the list. diff --git a/docs/mcp.md b/docs/mcp.md index d984e7b92d..0695a42dae 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5083,8 +5083,9 @@ already walks Image Trace. Short agent entry points: 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; art that holds an instance of the symbol (opacity masks included), directly or through the art of the symbols it holds instances of, is refused and nothing changes; the Symbols panel menu's Redefine Symbol sends `keepArt: true` when it - is chosen with Shift held, and the panel sends it with the dragged art's `ids` when art dragged - off the canvas is released on a symbol's tile or row with Alt (Option on macOS) held), + is chosen with Shift held, and the panel sends `symbol.update` with the dragged art's `ids` when art dragged + off the canvas is released on a symbol's tile or row with Alt (Option on macOS) held, with `keepArt: true` when Shift + is held too), `symbol.edit {id?, ids?, name?, x?, y?, artboard?, viewCenter?}` (symbol editing mode: the symbol's art on a temporary isolated layer, where the instance `id` shows it or centered on (x, y), by default on the center of artboard `artboard`, the active one the app passes, or in a document without artboards on `viewCenter`, the view's center the From 62199b98b3d1b9f11cc73a554f9a3abc380e2c05 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:29:52 -0800 Subject: [PATCH 12/14] Links: Placement Options applies to the images it opened on Opened without ids (the menu, a shortcut or ui.placementOptionsDialog {}), the dialog read the selected images but sent null ids on OK, and links.placementOptions read null as the selection at that moment. Selecting another image while the dialog was open applied the options to that image, and emptying the selection made OK fail. links.placementOptions without options now returns {ids, placement}, and the dialog sends those ids on OK. OK is refused when one of them has been deleted. Callers that pass ids are unchanged, as is the check that OK edits only the drawing the dialog opened in. --- crates/engine/src/cmd/links.rs | 4 +- crates/engine/src/tests/linkspanel.rs | 5 +- .../ui-egui/src/dialogs/placement_options.rs | 6 +- crates/ui-egui/src/panels/tests_links.rs | 88 +++++++++++++++++++ docs/control-protocol.md | 2 +- 5 files changed, 99 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 65f268f2b0..142cb8a654 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -135,7 +135,7 @@ pub fn specs() -> Vec { "Placement Options", [], None, - "{ids?: [image or placed document ids] (default: the selected ones), preserve?: transforms|bounds (default)|fileDimensions|fit|fill, align?: topLeft|top|topRight|left|center (default)|right|bottomLeft|bottom|bottomRight (where the new art sits; not for bounds), clip?: false (clip it to the old bounds where it is larger)} how a file read again (links.relink, links.update) takes each image's place: transforms keeps its scale (relative to each file's 100% size), rotation and position; bounds stretches it into the old bounds; fileDimensions puts it at 100%, unrotated; fit and fill scale it proportionally to fit inside or cover the old bounds. Without options → {placement} of the first image; else one undo step → {ids, placement}", + "{ids?: [image or placed document ids] (default: the selected ones), preserve?: transforms|bounds (default)|fileDimensions|fit|fill, align?: topLeft|top|topRight|left|center (default)|right|bottomLeft|bottom|bottomRight (where the new art sits; not for bounds), clip?: false (clip it to the old bounds where it is larger)} how a file read again (links.relink, links.update) takes each image's place: transforms keeps its scale (relative to each file's 100% size), rotation and position; bounds stretches it into the old bounds; fileDimensions puts it at 100%, unrotated; fit and fill scale it proportionally to fit inside or cover the old bounds. Without options → {ids, placement} (the images read, and the placement of the first); else one undo step → {ids, placement}", has_doc, placement_options ), @@ -3230,7 +3230,7 @@ fn placement_options(s: &mut Session, p: &Value) -> Result { let first = ids.first().and_then(|id| placement_of(&doc, *id)).unwrap_or_default(); drop(doc); if preserve.is_none() && align.is_none() && clip.is_none() { - return Ok(json!({ "placement": placement_json(first) })); + return Ok(json!({ "ids": ids_json(&ids), "placement": placement_json(first) })); } let set = |o: &mut PlacementOptions| { o.preserve = preserve.unwrap_or(o.preserve); diff --git a/crates/engine/src/tests/linkspanel.rs b/crates/engine/src/tests/linkspanel.rs index cd844fa28d..26f6ca51ce 100644 --- a/crates/engine/src/tests/linkspanel.rs +++ b/crates/engine/src/tests/linkspanel.rs @@ -578,7 +578,10 @@ fn placement_options_read_set_and_round_trip() { let mut s = session(); let id = place(&mut s, &pic); run(&mut s, "select.set", json!({"ids": [id.0]})); - assert_eq!(run(&mut s, "links.placementOptions", json!({})), json!({"placement": {"preserve": "bounds", "align": "center", "clip": false}})); + assert_eq!( + run(&mut s, "links.placementOptions", json!({})), + json!({"ids": [id.0], "placement": {"preserve": "bounds", "align": "center", "clip": false}}) + ); let r = run(&mut s, "links.placementOptions", json!({"preserve": "fill", "align": "topRight", "clip": true})); assert_eq!(r, json!({"ids": [id.0], "placement": {"preserve": "fill", "align": "topRight", "clip": true}})); assert!(s.execute("links.placementOptions", &json!({"preserve": "stretch"})).is_err()); diff --git a/crates/ui-egui/src/dialogs/placement_options.rs b/crates/ui-egui/src/dialogs/placement_options.rs index d6f05d0af7..03b4cc19bd 100644 --- a/crates/ui-egui/src/dialogs/placement_options.rs +++ b/crates/ui-egui/src/dialogs/placement_options.rs @@ -3,8 +3,8 @@ //! clipped to them. //! //! Fields: `preserve` (transforms|bounds|fileDimensions|fit|fill), `align` (0-8, row by row from -//! the top left) and `clip`. OK runs `links.placementOptions` with them and `ids` (null: the -//! selected images): one undo step. +//! the top left) and `clip`. OK runs `links.placementOptions` with them and the `ids` the dialog +//! opened on (by default the images selected then): one undo step. // PLAN: assumed craft_ui paths for ParamDialog, ParamKind, Param, DialogFields, FieldValue, HostedParamDialog and Label. use craft::ui::contract::Bind; @@ -48,6 +48,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let source = (active.uid, active.reverts); let ids = p.get("ids").cloned().unwrap_or(Value::Null); let r = app.session.execute(CMD, &json!({ "ids": ids })).map_err(|e| e.to_string())?; + // The images read: OK applies to these, whatever is selected by then. + let ids = r["ids"].clone(); let placement = &r["placement"]; let align = ALIGN.iter().position(|a| Some(*a) == placement["align"].as_str()).unwrap_or(CENTRE); let mut fields = DialogFields::from_pairs([ diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index af34acbd8e..d6be853ad4 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -681,6 +681,94 @@ fn placement_options_dialog_sets_the_options() { assert_eq!(r["placement"], json!({"preserve": "fit", "align": "bottomRight", "clip": false})); } +#[test] +fn placement_options_dialog_keeps_the_links_it_opened_on_when_the_selection_changes() { + use crate::tests::picks::{answer_dialog, open_dialogs}; + let dir = Folder::new("dialog-selection"); + let (app, first, _) = app(&dir); + let mut app = crate::testing::windowed(app); + let c = dir.file("second.png", &png(60, 40)); + let second = app.run("file.place", json!({"path": c, "at": [200, 150]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("links.placementOptions", json!({"ids": [first], "preserve": "fill"})).unwrap(); + app.run("links.placementOptions", json!({"ids": [second], "preserve": "bounds"})).unwrap(); + let placement = |app: &mut VectorcraftApp, id: u64| app.run("links.placementOptions", json!({"ids": [id]})).unwrap()["placement"].clone(); + let second_before = placement(&mut app, second); + + app.run("select.set", json!({"ids": [first]})).unwrap(); + app.run("ui.placementOptionsDialog", json!({})).unwrap(); + let open = open_dialogs(&app); + assert_eq!(open.len(), 1, "the dialog is open"); + app.run("select.set", json!({"ids": [second]})).unwrap(); + answer_dialog(&mut app, open[0].id, &[("preserve", json!("fit"))], true); + + assert_eq!(placement(&mut app, second), second_before, "the image selected after the dialog opened keeps its options"); + assert_eq!(placement(&mut app, first)["preserve"], json!("fit"), "OK applies to the image the dialog opened on"); +} + +/// Two linked images, the first with preserve `fill` and the second with `bounds`, in a window. +fn two_links(dir: &Folder) -> (VectorcraftApp, u64, u64) { + let (app, first, _) = app(dir); + let mut app = crate::testing::windowed(app); + let c = dir.file("second.png", &png(60, 40)); + let second = app.run("file.place", json!({"path": c, "at": [200, 150]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("links.placementOptions", json!({"ids": [first], "preserve": "fill"})).unwrap(); + app.run("links.placementOptions", json!({"ids": [second], "preserve": "bounds"})).unwrap(); + (app, first, second) +} + +fn preserve_of(app: &mut VectorcraftApp, id: u64) -> serde_json::Value { + app.run("links.placementOptions", json!({"ids": [id]})).unwrap()["placement"]["preserve"].clone() +} + +#[test] +fn placement_options_dialog_keeps_the_links_it_opened_on_when_the_selection_is_emptied() { + use crate::tests::picks::{answer_dialog, open_dialogs}; + let dir = Folder::new("dialog-deselect"); + let (mut app, first, second) = two_links(&dir); + app.run("select.set", json!({"ids": [first]})).unwrap(); + app.run("ui.placementOptionsDialog", json!({})).unwrap(); + let open = open_dialogs(&app); + app.run("select.set", json!({"ids": []})).unwrap(); + answer_dialog(&mut app, open[0].id, &[("preserve", json!("fit"))], true); + assert!(open_dialogs(&app).is_empty(), "OK closes the dialog"); + assert_eq!(preserve_of(&mut app, first), json!("fit")); + assert_eq!(preserve_of(&mut app, second), json!("bounds")); +} + +#[test] +fn placement_options_dialog_changes_nothing_when_a_link_it_opened_on_is_deleted() { + use craft::ui::dialog::HeldOk; + + use crate::tests::picks::{answer_dialog, open_dialogs}; + let dir = Folder::new("dialog-deleted"); + let (mut app, first, second) = two_links(&dir); + app.run("select.set", json!({"ids": [first]})).unwrap(); + app.run("ui.placementOptionsDialog", json!({})).unwrap(); + let open = open_dialogs(&app); + app.run("edit.clear", json!({})).unwrap(); + app.run("select.set", json!({"ids": [second]})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + answer_dialog(&mut app, open[0].id, &[("preserve", json!("fit"))], true); + let refused = app.dialogs().unwrap().with(|h| matches!(h.held_state(open[0].id), Some(HeldOk::Refused(_)))); + assert!(refused, "OK is refused and the dialog stays open"); + assert_eq!(preserve_of(&mut app, second), json!("bounds"), "the selected image keeps its options"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "no undo step"); +} + +#[test] +fn placement_options_dialog_applies_to_the_ids_it_was_given() { + use crate::tests::picks::{answer_dialog, open_dialogs}; + let dir = Folder::new("dialog-ids"); + let (mut app, first, second) = two_links(&dir); + app.run("select.set", json!({"ids": [first]})).unwrap(); + app.run("ui.placementOptionsDialog", json!({"ids": [second]})).unwrap(); + let open = open_dialogs(&app); + assert_eq!(open.len(), 1, "the dialog is open"); + answer_dialog(&mut app, open[0].id, &[("preserve", json!("fit"))], true); + assert_eq!(preserve_of(&mut app, second), json!("fit")); + assert_eq!(preserve_of(&mut app, first), json!("fill"), "the selected image keeps its options"); +} + #[test] fn properties_shows_the_selected_image_and_its_link_actions() { let dir = Folder::new("props"); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index df9b36eee8..25bdc8206f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -881,7 +881,7 @@ art too large at that scale) keeps the dialog open. Placement Options: the Links panel's flyout (or `ui.placementOptionsDialog {ids?}` for agents) opens the `placementOptions` dialog for the selected images (fields `ids`, `preserve`: `transforms`/`bounds`/`fileDimensions`/ `fit`/`fill`, `align`: `topLeft` … `bottomRight`, `clip`). `ui.dialog.confirm` runs `links.placementOptions` with them as -one undo step. +one undo step, on the images the dialog opened on even when the selection has changed since. Relink: the Links panel's Relink… button and flyout item (or `ui.relinkDialog {ids?}` for agents) open the `relink` dialog for the selected images and placed documents (fields `ids`, `links`: `[{name, ids}]`, one row per linked file, From 59d7c483c976ac3b43fba75a0d4e2e54af6dcc5f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:20:08 -0800 Subject: [PATCH 13/14] New Document: file.new refuses artboard counts that are not whole numbers file.new rounded artboards, artboardLayout.columns and artboardLayout.rows before checking them, so a value such as 2.4 or 0.6 was quietly taken as a different count, and artboards or columns outside 1 to 1000 were clamped. A direct call now refuses a count that is not a whole number from 1 to 1000 and opens no document. A step replayed from a journal or played from the Actions panel keeps the earlier rounding, so saved steps still play. The artboardLayout error messages now list rows among the keys. --- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/newdoc.rs | 49 ++++++++------- crates/engine/src/tests/newdoc.rs | 73 ++++++++++++++++++++++ crates/engine/src/tests/script_dom.rs | 2 +- crates/ui-egui/src/dialogs/new_document.rs | 3 +- docs/mcp.md | 7 ++- 6 files changed, 111 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 4fc1b83c29..e0dee8f105 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 21f3661c89..058d0c93aa 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -299,7 +299,11 @@ impl DocSettings { } /// These settings with `p`'s changes (the params of `file.new`) → validated. - pub fn with_params(mut self, p: &Value, cmd: &str) -> Result { + pub fn with_params(self, p: &Value, cmd: &str) -> Result { + self.with_params_inner(p, cmd, false) + } + + fn with_params_inner(mut self, p: &Value, cmd: &str, replaying: bool) -> Result { if let Some(u) = p.get("units").filter(|v| !v.is_null()) { let u = u.as_str().unwrap_or(""); self.units = Unit::named(u).ok_or_else(|| bad(cmd, format!("unknown units `{u}`")))?; @@ -329,11 +333,11 @@ impl DocSettings { Some(o) => return Err(bad(cmd, format!("orientation must be portrait or landscape, not `{o}`"))), } if let Some(n) = p.get("artboards").filter(|v| !v.is_null()) { - let n = n.as_f64().filter(|n| n.is_finite()).ok_or_else(|| bad(cmd, "artboards must be a number"))?; - self.artboards = n.round().clamp(1.0, MAX_ARTBOARDS as f64) as u32; + self.artboards = if replaying { n.as_f64().map(|n| n.round().clamp(1.0, f64::from(MAX_ARTBOARDS)) as u32) } else { count(n) } + .ok_or_else(|| bad(cmd, format!("artboards must be a whole number from 1 to {MAX_ARTBOARDS}")))?; } if let Some(l) = p.get("artboardLayout").filter(|v| !v.is_null()) { - self.layout_params(l, cmd)?; + self.layout_params(l, cmd, replaying)?; } if let Some(b) = p.get("bleed").filter(|v| !v.is_null()) { self.bleed = super::docsetup::bleed_param(b, self.bleed, cmd)?; @@ -371,7 +375,7 @@ impl DocSettings { } /// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id. - fn layout_params(&mut self, l: &Value, cmd: &str) -> Result<()> { + fn layout_params(&mut self, l: &Value, cmd: &str, replaying: bool) -> Result<()> { let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column"); if let Some(id) = l.as_str() { self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?; @@ -380,25 +384,22 @@ impl DocSettings { } return Ok(()); } - let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?; + let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?}"))?; for (k, v) in o { match k.as_str() { "layout" => self.layout = v.as_str().and_then(ArtboardLayout::parse).ok_or_else(bad_layout)?, "columns" => { - self.columns = v - .as_f64() - .filter(|c| c.is_finite() && *c >= 1.0) - .ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))? - .round() - .min(MAX_ARTBOARDS as f64) as u32 + self.columns = + if replaying { v.as_f64().filter(|n| *n >= 1.0).map(|n| n.round().min(f64::from(MAX_ARTBOARDS)) as u32) } else { count(v) } + .ok_or_else(|| bad(cmd, format!("artboardLayout.columns must be a whole number from 1 to {MAX_ARTBOARDS}")))? } "rows" => { - self.rows = v - .as_f64() - .map(f64::round) - .filter(|r| (1.0..=MAX_ARTBOARDS as f64).contains(r)) - .map(|r| r as u32) - .ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be from 1 to {MAX_ARTBOARDS}")))? + self.rows = if replaying { + v.as_f64().map(f64::round).filter(|n| (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32) + } else { + count(v) + } + .ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be a whole number from 1 to {MAX_ARTBOARDS}")))? } "spacing" => { self.spacing = v @@ -407,7 +408,7 @@ impl DocSettings { .ok_or_else(|| bad(cmd, format!("artboardLayout.spacing must be 0–{MAX_SPACING} pt")))? } "rightToLeft" => self.right_to_left = v.as_bool().ok_or_else(|| bad(cmd, "artboardLayout.rightToLeft must be true or false"))?, - _ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft)"))), + _ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft)"))), } } if o.contains_key("rows") && self.layout != ArtboardLayout::GridByColumn { @@ -610,6 +611,12 @@ fn de_rows<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result Option { + v.as_f64().filter(|n| n.fract() == 0.0 && (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32) +} + /// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points. fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING)) @@ -871,7 +878,7 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { // A preset keeps its name in Recent unless its size changed (turning it doesn't count). let sorted = |d: &DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units); let size = str_param(p, "preset").map(|_| sorted(&base)); - let mut settings = base.with_params(p, C)?; + let mut settings = base.with_params_inner(p, C, s.replaying())?; if size != Some(sorted(&settings)) { settings.name = "Custom".into(); } @@ -956,7 +963,7 @@ fn save(s: &mut Session, p: &Value) -> Result { Some(from) => find(s, from).ok_or_else(|| bad(C, format!("no preset called `{from}` (see file.newPresets)")))?, None => s.default_settings(), }; - let mut preset = base.with_params(p, C)?; + let mut preset = base.with_params_inner(p, C, s.replaying())?; preset.name = name.to_string(); let saved = &mut s.prefs.new_doc_presets; match saved.iter_mut().find(|q| q.name.eq_ignore_ascii_case(name)) { diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index ad2711558e..94caaf4348 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -173,6 +173,79 @@ fn ppi_overprint_preview_and_bad_params() { } } +/// Artboard counts, columns and rows are whole numbers in range: a fraction or a count outside +/// 1 to 1000 is an error, not rounded or clamped to one. +#[test] +fn counts_that_are_not_whole_or_out_of_range_are_errors() { + for p in [ + json!({"artboards": 2.4}), + json!({"artboards": 0}), + json!({"artboards": -0.5}), + json!({"artboards": 1001}), + json!({"artboardLayout": {"columns": 2.4}}), + json!({"artboardLayout": {"columns": 1001}}), + json!({"artboardLayout": {"layout": "gridByColumn", "rows": 2.4}}), + json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0.6}}), + json!({"artboardLayout": {"layout": "gridByColumn", "rows": 1000.4}}), + ] { + let mut s = Session::new(); + assert!(s.execute("file.new", &p).is_err(), "{p}"); + assert!(s.active().is_none(), "{p}: no document on an error"); + } + let s = new_doc(json!({"artboards": 6.0, "artboardLayout": {"layout": "gridByColumn", "rows": 2.0}})); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 6, "a whole number written 6.0 is a count"); +} + +#[test] +fn replaying_a_journal_rounds_an_older_artboard_count() { + let mut recorded = new_doc(json!({"artboards": 2})); + recorded.journal.last_mut().unwrap().1["artboards"] = json!(2.4); + let mut s = Session::new(); + for (id, p) in &recorded.journal { + s.replay(id, p).unwrap(); + } + assert_eq!(boards(&s), boards(&recorded)); + assert_eq!(boards(&s).len(), 2); + assert!(s.execute("file.new", &json!({"artboards": 2.4})).is_err()); +} + +#[test] +fn replayed_counts_keep_their_rounding_and_range_rules() { + for (key, value, expected) in [ + ("artboards", 0.0, 1), + ("artboards", 1001.0, 1000), + ("columns", 2.4, 2), + ("columns", 1001.0, 1000), + ("rows", 2.4, 2), + ("rows", 0.6, 1), + ("rows", 1000.4, 1000), + ] { + let mut p = json!({"width": 10, "height": 10, "artboards": 4, + "artboardLayout": {"layout": "gridByColumn", "spacing": 0}}); + if key == "artboards" { + p[key] = json!(value); + } else { + p["artboardLayout"][key] = json!(value); + } + let mut s = Session::new(); + s.replay("file.new", &p).unwrap(); + assert!(s.execute("file.new", &p).is_err(), "{p}"); + if key == "artboards" { + p[key] = json!(expected); + } else { + p["artboardLayout"][key] = json!(expected); + } + assert_eq!(boards(&s), boards(&new_doc(p))); + } + for layout in [json!({"columns": 0.6}), json!({"rows": 0.4}), json!({"rows": 1000.6})] { + let mut p = json!({"artboardLayout": layout}); + p["artboardLayout"]["layout"] = json!("gridByColumn"); + let mut s = Session::new(); + assert!(s.replay("file.new", &p).is_err(), "{p}"); + assert!(s.active().is_none(), "{p}"); + } +} + #[test] fn categories_list_generated_presets_with_neutral_names() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index bb333e91d8..f006b5217e 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1017,7 +1017,7 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { let (plain, spaced) = (plain.with_params(&to_row, "file.new").unwrap(), spaced.with_params(&to_row, "file.new").unwrap()); assert_eq!(plain.grid_columns(), spaced.grid_columns()); let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string(); - assert!(e.contains("rows must be from 1 to 1000"), "{e}"); + assert!(e.contains("rows must be a whole number from 1 to 1000"), "{e}"); for layout in ["gridByRow", "row", "column"] { let e = s.execute("file.new", &json!({"artboardLayout": {"layout": layout, "rows": 2}})).unwrap_err().to_string(); assert!(e.contains("rows needs the gridByColumn layout"), "{layout}: {e}"); diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index c20582141e..8d4b9aa247 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -1293,7 +1293,8 @@ mod tests { let mut app = app(); open(&mut app); set(&app, "artboards", json!(5)).unwrap(); - set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6, "spacing": 10})).unwrap(); + assert!(set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6, "spacing": 10})).is_err(), "a fraction is refused"); + set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4, "spacing": 10})).unwrap(); assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4)); create(&mut app); let st = app.session.active().unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index d984e7b92d..ad2d536722 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -632,6 +632,11 @@ of `appearance.setItem`, `anchor` of `path.removeAnchor` and `addon.pen.removePo value such as `"3"`, `2.5`, `-1` or `true` with `` `index` must be a whole number ``, naming the key, and reports a key left out or null as missing (such as `` missing integer `index` ``). An optional one, such as `subpath`, keeps its default when left out or null; `appearance.setActiveItem` reads a null `index` as clearing the active item. +`file.new` refuses a number given for `artboards`, `artboardLayout.columns` or `artboardLayout.rows` that is not a +whole number from 1 to 1000, such as `2.4`, `0` or `1001`, and opens no document. A null `artboards` keeps the +default or the preset's count; a null `columns` or `rows` is an error. A `file.new` step replayed from a journal or +played from the Actions panel keeps the earlier rules: `artboards` is rounded and kept within 1 to 1000, a `columns` of +1 or more is rounded and kept to at most 1000, and a `rows` is rounded and must then be from 1 to 1000. A command that leaves out an object selected inside a selected group also leaves it out when `ids` list it together with a group that holds it. Every command that takes `ids` (or `slices`, for the slice commands) refuses a list with an entry that is not a non-negative integer, or a value @@ -10504,7 +10509,7 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes `file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`), `name`, `width`/`height` (points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns, -rows, spacing, rightToLeft}` (`rows`, 1 to 1000 and rounded to a whole number, gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is +rows, spacing, rightToLeft}` (`artboards`, `columns` and `rows` are whole numbers from 1 to 1000, and any other number is an error; `rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are fewer artboards, until `columns` without `rows`, or another layout, is given; New Document's Columns shows the columns the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes), From 2604dab38a69fe1a6bb4e8b749cdf70ba57e80a1 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Tue, 1 Dec 2026 22:01:26 +0530 Subject: [PATCH 14/14] Copy a fallback layer lock only between layers that share a name (#9176) A PDF part without layers comes in on one layer named for its page. When the editing data is set aside (a stale copy of another page size, say), pairing that layer with the editing data's one layer locked art nothing ties to it. Layers now take locks only by a name unique on both sides. --- crates/eps/src/import/native/layers.rs | 14 +++-------- crates/eps/src/import/tests_native.rs | 35 +++++++++++++++++++++++--- 2 files changed, 34 insertions(+), 15 deletions(-) diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index e62af0e938..dcaa95a141 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -303,17 +303,9 @@ fn unique_name_pairs>(vis_nodes: &[T], priv_no /// Apply lock states from private data layers to visible PDF layers. pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], private_layers: &[LockTree]) { - if private_layers.is_empty() || visible_layers.is_empty() { - return; - } - - // A document with a single visible layer and a single private layer pairs them directly. - if visible_layers.len() == 1 && private_layers.len() == 1 { - apply_node_locks(Arc::make_mut(&mut visible_layers[0]), &private_layers[0]); - return; - } - - // Otherwise, match only layers with identifiable correspondence (matching unique names). + // Only layers that are evidently the same one (a name unique on both sides) take its locks: one + // layer each is no evidence, since a PDF part without layers comes in on a layer named for its + // page, and the editing data it was set aside for may not be the art on it. for (v_idx, p_idx) in unique_name_pairs(visible_layers, private_layers) { apply_node_locks(Arc::make_mut(&mut visible_layers[v_idx]), &private_layers[p_idx]); } diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index a3041244f3..c5b6b61d58 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8841,21 +8841,48 @@ fn ai_reordered_three_children_roads_triangle_circle_preserve_locks() { assert!(!vis_rd.locked, "Roads matched to unlocked private Roads by unique name"); } +/// The PDF part's one layer, named for its page because the PDF part has no layers, isn't the +/// editing data's one layer: nothing says the art on it is that layer's, so the layer's lock and +/// those of what it holds stay out of it. #[test] -fn ai_fallback_with_generated_page_name_preserves_private_layer_lock() { +fn ai_fallback_with_generated_page_name_does_not_take_private_layer_lock() { use std::sync::Arc; let mut doc = Document::new(100.0, 100.0); let mut priv_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0)); priv_layer.locked = true; + let mut priv_roads = Node::group(doc.alloc_id(), vec![]); + priv_roads.name = Some("Roads".to_string()); + priv_roads.locked = true; + if let NodeKind::Layer { children, .. } = &mut priv_layer.kind { + children.push(Arc::new(priv_roads)); + } let mut vis_layer = Node::layer(doc.alloc_id(), "Page 1", LayerColor::Preset(0)); - vis_layer.locked = false; + let mut vis_roads = Node::group(doc.alloc_id(), vec![]); + vis_roads.name = Some("Roads".to_string()); + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_roads)); + } let mut visible_layers = vec![Arc::new(vis_layer)]; let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)]; super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); - assert_eq!(visible_layers[0].name.as_deref(), Some("Page 1")); - assert!(visible_layers[0].locked, "single-layer document pairs visible and private layers"); + assert!(!visible_layers[0].locked, "the page's layer doesn't take the editing data's layer lock"); + assert!(!visible_layers[0].children().unwrap()[0].locked, "nor does what it holds"); +} + +/// An editing copy that doesn't fit the PDF part (a stale copy of another page size) is set aside, +/// and the PDF part without layers comes in on one layer named for its page: the editing copy's +/// locked layer doesn't lock that art, which nothing ties to it. +#[test] +fn a_stale_editing_copy_does_not_lock_the_pdf_parts_page_layer() { + let art = native(&locked_layer("Map", &square(10, 10))); + let mut page = Document::new(300.0, 300.0); + std::sync::Arc::make_mut(&mut page.layers[0]).name = Some("Page 1".into()); + let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(!read, "the editing copy of another page size is set aside: {w:?}"); + assert_eq!(names(&d), ["Page 1"], "{w:?}"); + assert!(!d.layers[0].locked, "the page's layer isn't locked: {w:?}"); } #[test]